我使用此函数从谷歌地图中获取纬度/经度:
function getLatLong(address){
var geo = new google.maps.Geocoder;
geo.geocode({'address':address},function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
return (results[0].geometry.location.k + ',' + results[0].geometry.location.D);
} else {
return;
}
});
}
它做了我想让它做的事情,但当我在另一个函数中使用它时,比如getLatLong('new york, times square')
,我会得到undefined
作为回报。如果我设置了console.log(results[0].geometry.location.k + ',' + results[0].geometry.location.D);
而不是return
,我会在控制台中获得位置(如果我调用函数,例如document.ready
)。
为什么是这样?我应该如何正确使用它?
这里的笑话是geoCode不返回任何内容,但它希望您直接处理函数回调中显示的映射。您可以将它正确地放在console.log中并执行任何操作,但不能返回和处理函数外的内容。
例如https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple你就会明白这是怎么回事。
编辑:
一些变通方法仍然存在,看看这个代码:
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.730885,-73.997383);
codeLatLng(function(addr){
alert(addr);
});
}
function codeLatLng(callback) {
var latlng = new google.maps.LatLng(40.730885,-73.997383);
if (geocoder) {
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
callback(results[1].formatted_address);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
}
上面的代码片段告诉如何使用显式回调。
来源:如何从Google Maps JavaScript地理编码器回调返回变量?
第2版:
您的代码相应修改:
function getLatLong(address, callback){
var geo = new google.maps.Geocoder;
geo.geocode({'address':address, function(results, status){
if (status == google.maps.GeocoderStatus.OK) {
callback (results[0].geometry.location.k + ',' + results[0].geometry.location.D);
} else {
// do sth with error.
}
});
}
并称之为:
getLatLong(address, function(addr){
// do whatever with addr attribute
alert(addr);
});
也许这有助于你想出一个主意。
您正在调用getLantLong('new york, times square');
而不是getLatLong('new york, times square');
检查您的拼写