1

I am playing around with the google maps API and was trying to drop in an array of zipcodes and have lines drawn on the map between each location. The problem I have is that, because of asynchronous behavior, the lines do not get drawn in the correct order and are different each time. Is there a simple way to edit this code so that the geocoder goes through the full loop before making the next request?

const geocoder = new google.maps.Geocoder();

    for(let i = 0; i < array1.length; i++){

        geocoder.geocode( { address: array1[i]}, function(results, status) {
              
        if (status == 'OK') {
            markers.push(results[0].geometry.location);
            
            
            if(markers.length > 0){
            const line = new google.maps.Polyline({
                path: [
                    markers[i-1],
                    markers[i],
                ],
                    strokeOpacity: 0,
                    icons: [{
                            icon: lineSymbol,
                            offset: "0",
                            repeat: "20px",
                          },
                ],
                map: map,
              });
            }
        
        var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
        });
      } else {
        alert('Geocode was not successful for the following reason: ' + status);
      }
      
    });
    }
  

0 Answers0