Im trying to create a set of functions that translates a set of addresses to lat long values using the Google Maps Geocoder API.
Currently, I have it successfully translating the addresses to lat long values but the function fully executes before theyre returned. I know this because it throws undefined errors before it logs the proper lat long values after.
I heard that javascripts promises can be a solution to this type of problem so I did a little bit of research but it doesn't seem to be helping the issues. Im new to promises so excuse me if Im going about this in the wrong way.
Here`s the relevant code
function getPoints(geocoder,map) {
let locationData = [];
let latValue;
for(let i = 0; i < addressData.length; i++){
let getLatLong = new Promise(function(resolve,reject){
latValue = findLatLang(addressData[i].location, geocoder, map);
if(latValue!=undefined){
resolve(latValue());
} else {
reject();
}
});
getLatLong.then(function(){
console.log(latValue);
//returns a GMap latLng Object.
locationData.push( new google.maps.LatLng(latValue[0],latValue[1]));
})
}
return locationData;
}
function findLatLang(address, geocoder, mainMap) {
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
console.log(results);
return [results[0].geometry.location.lat , results[0].geometry.location.lng];
} else {
alert('Couldnt't find the location ' + address);
return;
}
})
}
Thanks in advance for any help or pointers you would have!
See Question&Answers more detail:os