I am writing an app that uses the google javascript api; Everything is working splendidly, until I want to add the reverse geo-coding.
The problem that I have is as follows: I am making a call to this method below, geocodeLatLng, per record, for a minimum of one record.
I have put traces in, and the it will print out as follows:
coordinates: -33.88091325759888, 18.635687828063965
coordinates: -33.874990940093994, 18.639239072799683
coordinates: -33.90454888343811, 18.627684116363525
coordinates: -33.849005699157715, 18.63781213760376
coordinates: -33.85634422302246, 18.639850616455078
then after this, it prints out:
returned status is: OK (x5)
I would really want each call to the geocodeLatLng method to be completed in its entirety, before the next one attempts to start processing. How do I accomplish this?
function geocodeLatLng(callID, lat, lng) {
var returnString = "";
var latlng = {lat,lng};
console.log("coordinates: " + lat + ", " + lng);
var geocoder = new google.maps.Geocoder;
geocoder.geocode({'location': latlng}, function(results, status) {
console.log("returned status is: " + status);
if (status === 'OK') {
if (results[0]) {
var marker = new google.maps.Marker({position: latlng,});
returnString = results[0].formatted_address;
id_address_map.set(callID, returnString);
} else {
returnString = 'Address unknown';
id_address_map.set(callID, returnString);
}
} else {
returnString = 'Geocoder failed due to: ' + status;
id_address_map.set(callID, returnString);
}
});
}
Proposed solution:
function asyncGeoCode(callID, lat, lng) {
var returnString = "";
var latlng = {lat,lng};
console.log("coordinates: " + lat + ", " + lng);
var geocoder = new google.maps.Geocoder;
return new Promise((resolve, reject) => {
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === "OK") { resolve(results);}
else {reject("some error msg")}
});
});
}
}
and when it is called:
for(var i = 0; i< markers.length; i++) {
asyncGeoCode(markers[i].CallID, markers[i].Latitude, markers[i].Longitude)
.then(
function() {
console.log("the address is known");
},
function(err) {
console.log("unknown address");
}
);
}