Return address from Google Maps Geocoder v3

半城伤御伤魂 提交于 2019-12-08 04:32:30

You can do it this way, and call the outputGeo function within the Geocode's callback function. Basically, you are accessing r before the Geocode callback and thus r is still undefined:

$(function() {
     var address = $("address").text();
     var r;

     function encodeAddress() {
       geocoder = new google.maps.Geocoder();
       geocoder.geocode({'address' : address}, function(results, status) {
         if (status == google.maps.GeocoderStatus.OK) {
           results[0].geometry.location;
           r = results[0].geometry.location;
           outputGeo(r);
         } else {
           alert("Google Maps had some trouble finding" + address + status);
         }
       });
     }

    encodeAddress();
    function outputGeo(result){
         console.log("outside:" + result);
    }
});

Here is an explanation of how Geocoding service works.

Accessing the Geocoding service is asynchronous, since the Google Maps API needs to make a call to an external server. For that reason, you need to pass a callback method to execute upon completion of the request. This callback method processes the result(s). Note that the geocoder may return more than one result.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!