如果我理解你的话,你正在尝试做这样的事情:
var latlng1;
geocoder.geocode({
'address': acity
}, function( results, status ) {
if( status == google.maps.GeocoderStatus.OK ) {
latlng1 = new google.maps.LatLng(
results[0].geometry.location.lat(),
results[0].geometry.location.lng()
);
}
});
// Now do stuff with latlng1 here
这永远不会奏效,而且你也无法让它发挥作用。正如您所发现的,“现在使用 latlng1 进行操作”代码在收到结果之前运行。
地理编码器 API 与访问服务器获取数据的任何 JavaScript API 一样,是异步的。API调用立即返回,数据准备好时调用回调函数。
所以你需要做的是在数据准备好时调用LatLng
你自己的函数,像这样(也简化以删除冗余的构造函数调用):
geocoder.geocode({
'address': acity
}, function( results, status ) {
if( status == google.maps.GeocoderStatus.OK ) {
doStuffWithLatLng( results[0].geometry.location );
}
});
function doStuffWithLatLng( latlng ) {
// Now do stuff with latlng1 here
}
或者,您当然可以将“do stuff”代码放在地理编码器回调中:
geocoder.geocode({
'address': acity
}, function( results, status ) {
if( status == google.maps.GeocoderStatus.OK ) {
var latlng1 = results[0].geometry.location;
// Now do stuff with latlng1 here
}
});