我的map.js文件中有一个名为getNameOfCity()的函数(函数如下)通过执行以下var city = getNameOfCity();
从我的actions.js文件中调用它然后我提醒城市并且它显示未定义。
这是map.js中的函数
function getNameOfCity() {
geocoder.geocode({'latLng': map.getCenter()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]){
jQuery.each(results[0].address_components, function(key, value){
if(value.types[0] == 'locality') {
return value.long_name;
}
});
}
} else {
return false;
}
});
}
当我在返回正确的城市之前提醒value.long_name时会发出警报。但是当我从调用函数的位置向城市提醒时,它返回undefined。关于为什么的任何想法?
由于
答案 0 :(得分:1)
您在匿名函数中返回一个值 - 因此您将其返回到任何值。
你需要做的是在回复你的回复说“我已经完成,这是城市名称”时调用一个函数。
答案 1 :(得分:0)
function getNameOfCity() {
var city = '';
geocoder.geocode({'latLng': map.getCenter()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]){
jQuery.each(results[0].address_components, function(key, value){
if(value.types[0] == 'locality') {
city = value.long_name;
}
});
return city;
}
} else {
return false;
}
});
}
<强>更新强> 正如你所建议的那样回调方式......
function getNameOfCity(callback) {
geocoder.geocode({'latLng': map.getCenter()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]){
jQuery.each(results[0].address_components, function(key, value){
if(value.types[0] == 'locality') {
callback(value.long_name); // call the function, pass the city name.
}
});
}
} else {
callback(false); // not found? pass false instead.
}
});
}
更新2
您现在可以使用此功能以这种方式获取城市名称:
getNameOfCity(function(city) {
alert(city); // or do something less useless.
});