[英]Google maps - returning getPosition from function undefined
I have a function that initializes my google map, and within that function it calls another function which works with the geocoder for setting some markers. 我有一个初始化我的Google地图的函数,在该函数中,它调用了另一个与Geocoder一起使用的函数,用于设置一些标记。 I create the markers in that second function.
我在第二个功能中创建了标记。
Why is it that within that second function I can alert(marker.getPosition()) and get a latlng value. 为什么在第二个函数中我可以发出alert(marker.getPosition())并获取latlng值。 However if I do return marker.getPosition() then alert the return value of that function it displays as undefined?
但是,如果我确实返回marker.getPosition(),然后警告该函数的返回值,则显示为未定义?
Example code: 示例代码:
function initMap() {
//Defined Map/Geocoder
//Defined Array of addresses
for (var i = 0; i < address.length; i++) {
alert(geocodeAddress(address[i], geocoder, map)); //Alert shows undefined
}
}
function geocodeAddress(address, geocoder, resultsMap) {
geocoder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
alert(maker.getPosition()); //Displays latlng data
return marker.getPosition();
}
});
}
You're just returning from your anonymous callback. 您只是从匿名回调中返回。 You don't assign that to a variable or anything else, and your
geocodeAddress
function isn't returning anything to the initMap function. 您无需将其分配给变量或其他任何对象,并且
geocodeAddress
函数不会将任何内容返回给initMap函数。 Try: 尝试:
function geocodeAddress(address, geocoder, resultsMap) {
return geocoder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
return marker.getPosition();
}
});
}
You'll need to also handle the case when you don't get a successful geocoder response. 如果您未成功获得地址解析器的响应,则还需要处理这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.