【问题标题】:Store result of Google Maps geocode function谷歌地图地理编码功能的存储结果
【发布时间】:2012-07-04 11:42:04
【问题描述】:

我想检索并存储 Google Maps API 函数 geocode() 的结果,以便以后使用。 我已将下面的代码放在OnClick 事件上,以对地图上单击的点的地址进行反向地理编码。

问题是它总是包含上一个点击点的值。 例子:我第一次点击是'undefined',第二次是我之前点击的点的地址,以此类推。

var address ;


my_listener = google.maps.event.addListener(map, 'click', function(event) {
   codeLatLng(event.latLng);
});

function codeLatLng(mylatLng) {
    
    geocoder = new google.maps.Geocoder();
    var latlng = mylatLng;

    geocoder.geocode({'latLng': latlng}, function(results, status) 
    {
        if (status == google.maps.GeocoderStatus.OK) 
        {
            if (results[1]) 
            {
                address = results[1].formatted_address;
            }
        }
    });

    alert(address);
}

【问题讨论】:

    标签: google-maps geocode


    【解决方案1】:

    如果你移动alert,在回调里面,你会看到新地址:

    geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) 
        {
            if (results[1]) 
            {
                address = results[1].formatted_address;
                alert(address);   //moved here
            }//   ^
        }//       |
    });//         |  
    //-------------
    

    地理编码过程是异步的,所以在这种情况下:

    geocoder.geocode({'latLng': latlng}, function(results, status) {
        //We be called after `alert(address);`
    });
    alert(address);
    

    alert 将在从服务器接收地理编码数据之前执行,并调用回调 function(results, status){}

    【讨论】:

    • 我如何存储address 值以便在其他功能中使用它?
    • @SportBilly 你可以使用它,只有在从服务器接收数据之后。这意味着您需要在 function(results, status){} 回调中调用您的函数(需要对地址执行一些操作)。
    • 谢谢,但我不想在地理编码函数中调用函数。我想调用显示结果的函数。
    • @SportBilly 在address = results[1].formatted_address; 行之后,编写代码,显示address。有什么问题?
    • @SportBilly,支持工程师所说的。创建一个使用地址更新的全局变量。其他函数都可以访问它,并且可能想要检查它的长度或其他任何东西,以防它们在地理编码函数完成之前被执行
    猜你喜欢
    • 1970-01-01
    • 2017-06-22
    • 2015-10-21
    • 1970-01-01
    • 2012-04-10
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多