储存Google Maps地理编码功能的结果 [英] Store result of Google Maps geocode function
问题描述
我想获取Google Maps API geocode()函数的结果,以便将其用于其他函数.我已将以下代码放在OnClick事件上,以对地址进行地理编码,以对地图上单击的点的地址进行地理编码.
I want to get the result of Google Maps API geocode() function in order to use it to other functions. I have put the code below on an OnClick event to reverse geocode the address of the point clicked on map.
总是单击先前的point值.例如:我第一次单击它具有未定义",第二次具有它之前单击的点的地址,依此类推.
It is always having the previous value of point clicked. Example: the first time i click it has 'undefined', 2nd time it has the address of the point i clicked before and so on.
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);
}
推荐答案
如果要在回调内移动 alert
,则会看到新地址:
If you will move alert
, inside of callback, you will see the new address:
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
}// ^
}// |
});// |
//-------------
地理编码过程是异步,因此在这种情况下:
Geocoding process is asyncronous, so in this case:
geocoder.geocode({'latLng': latlng}, function(results, status) {
//We be called after `alert(address);`
});
alert(address);
警报
将在从服务器接收地理编码数据并调用回调 function(results,status){}
之前执行.
alert
will be executed before the geocoding data will be recieved from server and callback function(results, status){}
will be called.
这篇关于储存Google Maps地理编码功能的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!