1

I've created a function to return latitute and longitude.
The problem is that alert('outside:') is triggered before geocoder.geocode.

Looking at this similar example, this function should work.

 function getLatLng(geocoder, adr) {
    var latLng = '';
    geocoder.geocode({ 
      address: adr}, function(results, status){
        if (status == google.maps.GeocoderStatus.OK && results.length) {
          latLng = results[0].geometry.location;
          alert('inside: ' + latLng); // This works
        } 
      }
    );
    alert('outside: ' + latLng); // This shows NULL
    return latLng;
 }

So what do I need to to in order to return latlng value?

Community
  • 1
  • 1
Steven
  • 19,224
  • 47
  • 152
  • 257

2 Answers2

5

You will see this pattern used a lot in JavaScript for asynchronous operations - the second argument to geocode() is a callback function which gets invoked when the potentially expensive and long-lived geocoding operation finishes. If the call was synchronous, it would lock up your web-page and any other JavaScript code until it returned.

A minor setback to using asynchronous functions is that they return immediately so you can't use return to return a value; just like you've found out in your geocoding example - the call to geocode() returns immediately without a result and works in the background, invoking the callback function with the actual result sometime later.

One solution would be to specify a callback function yourself in the call to getLatLng:

function getLatLng(geocoder, adr, myCallback){
    var latLng = '';
    geocoder.geocode({
                address: adr
            }, 
            function(results, status){
                if (status == google.maps.GeocoderStatus.OK && results.length) {
                    latLng = results[0].geometry.location;
                    if(myCallback){
                        myCallback(latlng);
                    }
                }
            });
}
no.good.at.coding
  • 20,221
  • 2
  • 60
  • 51
0

It's an asynchronous function, you can't do that

AlfonsoML
  • 12,634
  • 2
  • 46
  • 53