I am trying to take an array of coordinates, do a Nearby Search (https://developers.google.com/maps/documentation/javascript/places) for each item in the array, and then add each set of results to a separate array of results (placesOfInterest
).
Instead of doing:
Search -> Put results to array -> Search -> Push results to array
, it seems to be doing Search -> Search -> Search -> Push results to array -> Push results to array
but I can't figure out why.
I was originally trying to push the search results to the placesOfInterest array, but then changed to an async version because I thought the callback wasn't getting hit due to some time delay. I created superPush
function, based on the 'appendOutput(item) I found on this guide https://codeburst.io/asynchronous-code-inside-an-array-loop-c5d704006c99 but this still didn't fix the problem.
HTML
...
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<APIKEY>k&libraries=places"></script>
...
JS
var points = [[2.627365,49.215369],[2.760591, 49.647163],[2.952975, 50.057504],[3.344742, 50.280862],[3.768293, 50.451306],[4.21659, 50.534029]]
for (point of points) {
googlePlaces(point);
}
function googlePlaces(point) {
var latLng = new google.maps.LatLng(point[1],point[0])
var request = {
location: latLng,
radius: '10000'
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback); // hits this code [i] times first...
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
//results.forEach(result => placesOfInterest.push(result)) // originally tried this way
results.forEach(result => superPush(result)) // ...then hits this code [i] times
}
}
function superPush(result) {
fetchData(result).then(function() {
placesOfInterest.push(result);
})
}
What can I do? There's no way to not call the callback, but I can't think of a way to get around it.