Skip to content Skip to sidebar Skip to footer

Asynchronous Google Maps Request Throwing Off Javascript

I'm working on someone else's code, and I am trying to use Google maps API to convert a street address into latitude and longitude coordinates: var start_lng; var end_lat

Solution 1:

For the "handler" code, use a callback instead:

functiongetLatLng(loc, callback) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'address': loc}, functionpostcodesearch(results, status) 
    {   
        if (status == google.maps.GeocoderStatus.OK) 
        {
            var lat = results[0].geometry.location.lat();
            var lng = results[0].geometry.location.lng();
            callback(lat, lng);
        }
    }
}

getLatLng(function(lat, lng) {
    alert("DO REST");
    var start_p = new google.maps.LatLng(lat, lng);
});

If you need to make two calls to the geocoder, then you can always nest those calls, and put the callback after both are complete. Something like:

functiongetLatLng(locStart, locEnd, callback) {
    geocoder.geocode({ }, function(results1) {

        geocoder.geocode({ }, function(results2) {

            callback(results1.lat, results1.lng, results2.lat, results2.lng);
        });
    });
}

getLatLng(loc1, loc2, function(lat1, lng1, lat2, lng2) {

});

Solution 2:

use global flag variables

for example:

var flag_lat = var flag_lnt = 0;

then add in your postcodesearch functions flag_lat=1; and flag_lng=1; respectively

and in the end of each postcodesearch function check

if (flag_lat && flag_lng) 
{ 
  do_the_things_function(); 
  flag_lat = flag_lng = 0; //reset the flags
}

Post a Comment for "Asynchronous Google Maps Request Throwing Off Javascript"