Search code examples
javascriptgoogle-mapsgoogle-maps-api-3google-geocoder

Google Maps geocoding an array on address not working properly - only one marker


I am trying to have a map with multiple markers on it.

If I do it with coordinates, it works fine. The problem is I have not the coordinates of all the places. What I certainly have is the address.

So I opted for the geocoding. It works fine with only one marker, but I don't understand why, it doesn't loop through the array of locations.

Here is my code:

    var locations = [

    ['B&B Al Centro Storico', 41.203517, 16.600466, 2,'Via Samuelli 83','Barletta'],
    ['B&B Cortile Fondo Noce', 41.276672, 16.417772, 3,'Via Fondo Noce 29','Bisceglie']
    ];

    var map = new google.maps.Map(document.getElementById('mappa'), {
        zoom: 9,
        center: new google.maps.LatLng(41.239162, 16.500301),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        scrollwheel: false,
        disableDefaultUI: true
    });


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




    var infowindow = new google.maps.InfoWindow();

    var marker, i;
    var infoWindowContent = [];


    function setPin(indirizzo,mappa)
    {
        geocoder.geocode({'address':  indirizzo}, function(results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                marker = new google.maps.Marker({
                    map: mappa,
                    position: results[0].geometry.location
                });
                }                       
        });                 
    }


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


        // geocoder.geocode({'address':  locations[i][4] + ', ' + locations[i][5]}, function(results, status) {
            // if (status === google.maps.GeocoderStatus.OK) {
                // marker = new google.maps.Marker({
                    // map: map,
                    // position: results[0].geometry.location
                // });
                // }                        
        // });          


        setPin(locations[i][4] + ' ' + locations[i][5],map);


        // marker = new google.maps.Marker({
            // position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            // map: map 
        // });

        infoWindowContent[i] = '<b>'+locations[i][0]+'</b>';                    


        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
                infowindow.setContent(infoWindowContent[i]);
                infowindow.open(map, marker);
            }
        })(marker, i));
    }

You can see the commented out lines of the lat,long version that works as expected.


Solution

  • Put the code that depends on the marker inside the setPin function.

    function setPin(indirizzo, i, mappa) {
      var geocoder = new google.maps.Geocoder();
      geocoder.geocode({
        'address': indirizzo
      }, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
          marker = new google.maps.Marker({
            map: mappa,
            position: results[0].geometry.location
          });
              infoWindowContent[i] = '<b>' + locations[i][0] + '</b>';
    
      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(infoWindowContent[i]);
          infowindow.open(mappa, marker);
        }
      })(marker, i));
        } else alert("geocode failed:"+indirizzo+" status="+status)
      });
    }
    

    code snippet:

    function initialize() {
      var locations = [
    
        ['B&B Al Centro Storico', 41.203517, 16.600466, 2, 'Via Samuelli 83', 'Barletta'],
        ['B&B Cortile Fondo Noce', 41.276672, 16.417772, 3, 'Via Fondo Noce 29', 'Bisceglie']
      ];
    
      var map = new google.maps.Map(document.getElementById('mappa'), {
        zoom: 9,
        center: new google.maps.LatLng(41.239162, 16.500301),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        scrollwheel: false,
        disableDefaultUI: true
      });
    
      var infowindow = new google.maps.InfoWindow();
      var marker, i;
      var infoWindowContent = [];
    
      function setPin(indirizzo, i, mappa) {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({
          'address': indirizzo
        }, function(results, status) {
          if (status === google.maps.GeocoderStatus.OK) {
            marker = new google.maps.Marker({
              map: mappa,
              position: results[0].geometry.location
            });
            infoWindowContent[i] = '<b>' + locations[i][0] + '</b>';
    
            google.maps.event.addListener(marker, 'click', (function(marker, i) {
              return function() {
                infowindow.setContent(infoWindowContent[i]);
                infowindow.open(mappa, marker);
              }
            })(marker, i));
          } else alert("geocode failed:" + indirizzo + " status=" + status)
        });
      }
    
      for (i = 0; i < locations.length; i++) {
        setPin(locations[i][4] + ' ' + locations[i][5], i, map);
      }
    }
    google.maps.event.addDomListener(window, "load", initialize);
    html,
    body,
    #mappa {
      height: 100%;
      width: 100%;
      margin: 0px;
      padding: 0px
    }
    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <div id="mappa"></div>