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. 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. However if I do return marker.getPosition() then alert the return value of that function it displays as undefined?
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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.