我想使用谷歌地理编码器API V3根据用户指定的地址在地图上绘制位置,代码如下。谷歌地图地理编码API V3不返回结果在JavaScript函数
当我直接发出请求(例如到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中设置了断点result = 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);
...
}
感谢Brady,已经尝试了这种方法,但结果仍然不会返回与初始化值不同的值。 – Jason 2010-11-09 13:45:58
@jibberish - 你必须有其他地方出了问题,因为如果我运行getLatLong(“约克”)它返回53.9577018,-1.0822855 – Brady 2010-11-09 13:55:46
我必须的。我可以直接在调试器中找到geocoder.geocode行,然后直接跳过函数调用返回。我猜会继续堵塞! – Jason 2010-11-09 14:03:09