Skip to content

Instantly share code, notes, and snippets.

@drmmr763
Created June 17, 2014 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drmmr763/4a3c6475bceeaa9ee678 to your computer and use it in GitHub Desktop.
Save drmmr763/4a3c6475bceeaa9ee678 to your computer and use it in GitHub Desktop.
Pass anonymous function result to parent function?
/*
* Takes a zipcode in string format
* Sends it to Google Maps API
* Returns an object containing latitude & longitude
*/
function geocodeZipcode(zip)
{
var geocodeOptions =
{
'address': zip
}
// instiate the google map geocoder class
var geocoder = new google.maps.Geocoder();
// places the results into a function
geocoder.geocode(geocodeOptions, function(results, status) {
// validate response and return location or error
if (status != google.maps.GeocoderStatus.OK)
{
// something wasn't okay, send error message
return status; // exit early
}
var location = results[0].geometry.location;
// build json object
var latlong =
{
'latitude': location.lat(),
'longitude': location.lng()
}
return latlong;
});
// return ??
// how to pass the return statements from the anonymous function as the geocodeZipcode function's return??
}
@drmmr763
Copy link
Author

So apparently the answer here is this thing called 'callbacks'. This is some mystical javascripty thingy that I don't understand yet. But somehow this works:

function callingFunction()
{
  geocodeZipcode(zip, function(results){
       console.log(results);
    });
}

function geocodeZipcode(zip, callback)
{
    var geocodeOptions =
    {
        'address': zip
    }

    // instiate the google map geocoder class
    var geocoder = new google.maps.Geocoder();

    // places the results into a function
    geocoder.geocode(geocodeOptions, function(results, status) {

        // validate response and return location or error
        if (status != google.maps.GeocoderStatus.OK)
        {
            // something wasn't okay, send error message
            callback(status); // exit early
        }

        var location = results[0].geometry.location;

        // build json object
        var latlong =
        {
            'latitude': location.lat(),
            'longitude': location.lng()
        }

        // callbacks are some unknown return-y thing that apparently work
        callback(latlong);
    });
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment