简体   繁体   English

从Google Maps Geocoder v3返回地址

[英]Return address from Google Maps Geocoder v3

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. 我正在尝试返回地理编码的地址,以便与街景视图和Gmap一起使用。 Inside returns the correct value and the outside returns underfined. Inside返回正确的值,外部返回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. 非常感谢所有的帮助,我确实在其他地方读过这样不可能以这种方式返回值,但必须与可靠的StackOverflow社区一起检查。

Thank you in advance. 先感谢您。

You can do it this way, and call the outputGeo function within the Geocode's callback function. 您可以这样做,并在Geocode的回调函数中调用outputGeo函数。 Basically, you are accessing r before the Geocode callback and thus r is still undefined: 基本上,您在Geocode回调之前访问r,因此r仍未定义:

$(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. 访问地理编码服务是异步的,因为Google Maps API需要调用外部服务器。 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. 请注意,地理编码器可能会返回多个结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM