开发者

Not able to return Geocode latLng

I've created a function to return latitute and longitude.

The problem is that alert('outside:'开发者_如何学Go) 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?


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);
                    }
                }
            });
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜