我正在尝试使用 Google geocoder API V3 根据用户指定的地址在地图上绘制位置,代码如下。
当我直接发出请求时(例如向http://maps.googleapis.com/maps/api/geocode/json?address=peterborough&sensor=false),我得到了预期的响应。但是,当我使用下面的代码发出相同的请求时,在getLatLong函数退出后,中点变量始终未定义。
我做错了什么?
function loadFromSearch(address)
{
midpoint = getLatLong(address);
mapCentre = midpoint;
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
...
}
function getLatLong(address)
{
var result;
var url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(address) + '&sensor=false'
$.getJSON(url,
function (data){
if (data.status == "OK")
{
result = data.results[0].geometry.location;
}
});
return result;
}
==================================================== =================================
根据响应,我现在已将代码更新为以下内容。不过,我仍然没有得到任何结果,在 Firebug 中设置了断点,结果 = data.results[0].geometry.location; 永远不会被击中。
function loadFromSearch(address)
{
midpoint = getLatLong(address, loadWithMidpoint);
}
function getLatLong(address, callback)
{
var result;
var url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(address) + '&sensor=false'
$.getJSON(url,{},
function (data) {
if (data.status == "OK")
{
result = data.results[0].geometry.location;
callback(result);
}
});
}
function loadWithMidpoint(centre)
{
mapCentre = centre;
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
...
}
==================================================== ============================
我有!有效的最终代码如下所示:
function loadFromSearch(coordinates, address)
{
midpoint = getLatLong(address, latLongCallback);
}
function getLatLong(address, callback)
{
var geocoder = new google.maps.Geocoder();
var result = "";
geocoder.geocode({ 'address': address, 'region': 'uk' }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
result = results[0].geometry.location;
latLongCallback(result);
}
else
{
result = "Unable to find address: " + status;
}
});
return result;
}
function latLongCallback(result)
{
mapCentre = result;
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
...
}