Return address from Google Maps Geocoder v3

此生再无相见时 提交于 2019-12-23 01:42:18

问题


I have the following function:

$(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
           console.log("inside:" + r);
         } else {
           alert("Google Maps had some trouble finding" + address + status);
         }
       });
     }

    encodeAddress()
    console.log("outside:" + r);
});

I am trying to return the geocoded address for use with Street View as well as Gmap. Inside returns the correct value and the outside returns underfined.

All help is greatly appreciated, I did read somewhere else that it is not possible to return the value this way but had to check with the trusty StackOverflow community.

Thank you in advance.


回答1:


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.



来源:https://stackoverflow.com/questions/5517120/return-address-from-google-maps-geocoder-v3

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