[英]Using Google Maps: a custom javascript function returning undefined
I'm trying to return the variable coord
from GetLocation, but it only returns undefined. 我正在尝试从GetLocation返回变量
coord
,但它只返回undefined。 Any help appreciated! 任何帮助赞赏!
var coord = "";
function GetLocation(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { "address": address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
coord = ParseLocation(results[0].geometry.location);
// This alert shows the proper coordinates
alert(coord);
}
else{ }
});
// this alert is undefined
alert(coord);
return coord;
}
function ParseLocation(location) {
var lat = location.lat().toString().substr(0, 12);
var lng = location.lng().toString().substr(0, 12);
return lat+","+lng;
}
When you are returning coords
from the outer function it is still in fact undefined
. 当你从外部函数返回
coords
,它仍然是undefined
。 The inner function executes later when the asynchronous operation (if it wasn't asynchronous, the API would just give the result to you normally) is done. 内部函数稍后执行异步操作(如果它不是异步操作,API只是通常给你的结果)。
Try passing a callback: 尝试传递回调:
function GetLocation(address, cb) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { "address": address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
cb(ParseLocation(results[0].geometry.location));
}
else{ }
});
}
You can then use it like so: 然后您可以像这样使用它:
GetLocation( "asd", function(coord){
alert(coord);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.