Gabotronix
1 month ago
147
0
General

How to deal with Google Maps API calls inside a for loop

Posted 1 month ago by Gabotronix

Hi everybody, I have an array of rectangular boundaries which I want to search for restaurants with Google Places API javascript.

At first I thought about iterating through boundaries array with for loop, issue is in each iteration I'll be making an async API call and for loop is sync action...

Ideally I'd like to iterate through all boundaries with a one minute difference between each API call and finish once all boundaries have been search, maybe with setInterval but I can't quite get my grap around how I 'd deal with this?

How can I do this?

loopSearch(zoneBoundaries)
    {
        for (var i = 0; i <= zoneBoundaries.length; i++)
        {
            const self = this;

            var bounds = new google.maps.LatLngBounds(
                new google.maps.LatLng(zoneBoundaries[i].sw),
                new google.maps.LatLng(zoneBoundaries[i].ne)
            );

            self.placesService = new google.maps.places.PlacesService(self.map);

            var request = { bounds: bounds, types: [ 'restaurant', 'bar'] };

            self.placesService.search(request, self.placesCallback);
        }
    },

Please sign in or create an account to participate in this conversation.