【发布时间】:2014-10-24 20:08:48
【问题描述】:
有人可以查看我的代码并告诉我我做错了什么吗?我知道 Googlemaps 地理编码器是一个异步函数,因此需要一个回调来处理结果。所以我按照这里的例子,但我仍然无法让它工作:
How do I return a variable from Google Maps JavaScript geocoder callback?
我想给我的codeAddress 函数一个实际地址和一个回调函数。如果results 数组有东西,我将 lat 和 lng 发送到回调函数。
codeAddress = function(address, callback) {
var gpsPosition = {};
if (geocoder) {
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
console.log("got results!");
var lat = results[0].geometry.location['B'];
var lng = results[0].geometry.location['k'];
callback(lat, lng);
} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
};
这是回调函数。基本上,它从 codeAddress 函数中获取 lat 和 lng 并将 lat 和 lng 放入哈希中并返回它。这个想法是然后将哈希存储到一个名为location 的变量中,并在我创建新地图标记时引用location。
createGPSPosition = function(lat, lng){
console.log("createGPSPosition called with lat and lng:");
console.log(lat);
console.log(lng);
var gpsPosition = {};
gpsPosition.B = lat;
gpsPosition.k = lng;
console.log("gpsPosition:");
console.log(gpsPosition);
return gpsPosition;
};
当我运行此代码时,console.log(gpsPosition); 实际上记录了最终的哈希对象。但我仍然没有看到对象被返回......所以当我这样做时:
var stuff = codeAddress("1600 Amphitheatre Pkwy, Mountain View, CA 94043", createGPSPosition)
stuff 仍然显示为undefined。这是怎么回事?
【问题讨论】: