使用谷歌地图:一个返回undefined的自定义javascript函数
Using Google Maps: a custom javascript function returning undefined
我试图从GetLocation返回变量coord
,但它只返回undefined。感谢您的帮助!
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;
}
当您从外部函数返回coords
时,它实际上仍然是undefined
。内部函数稍后在异步操作(如果不是异步操作,API将正常地向您提供结果)完成时执行。
尝试传递回调:
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{ }
});
}
然后你可以这样使用它:
GetLocation( "asd", function(coord){
alert(coord);
});
相关文章:
- RequireJS向模块传递配置总是返回undefined
- JSON数组数据返回Undefined
- JavaScript”;.方法“;返回undefined
- jQuery可以't获取data-*属性值,返回undefined
- Javascript/JSON警报返回Undefined
- Javascript:firstChild对象返回undefined
- 使用在函数外部声明的变量的 Javascript 返回值 + undefined
- 当尝试使用ajax读取文件时,变量返回undefined
- 如何避免JSON.stringify在特殊情况下返回undefined,从而为JSON.parse创建字符串失败
- 使用谷歌地图:一个返回undefined的自定义javascript函数
- Json在nodeJs和AngularJs中返回undefined
- 为什么像 Firefox 和 Chrome 控制台中的 '}{' 这样的结构会返回 'undefined'?
- 使用 HTML 和 JavaScript 从表单访问值时返回 undefined
- 在 CoffeeScript 中,当尝试调用类中的方法 (@_methodName) 时,它会返回 undefined
- 解析承诺'当'返回undefined(Javascript)
- NodeJS:zlib.gunzip(body)错误地返回“undefined”
- window.open在chrome扩展中返回undefined
- javascript中的If/else不会为undefined返回else
- “undefined"返回而不是游戏名称
- 为什么“typeof false || undefined”返回"布尔值”;