Google Maps Multiple Markers

Addresses

by Ryan Brackett

HTML

<script src="//maps.google.com/maps/api/js?sensor=false"></script>
<div id="map_canvas"></div>
<ul id="location-list"></ul>

CSS

#map_canvas {
  width: 100%;
  height: 400px;
}

JavaScript

// Multiple Markers
var addresses = [
  'Atlanta, GA',
  'Gainesville, GA',
  'Houston, TX',
  'Washington, DC',
  'New York, NY',
  'Miami, FL'
];

// Info Window Content
var infoWindowContent = [];

function initialize() {

  var bounds = new google.maps.LatLngBounds();
  var myOptions = {
    mapTypeId: 'roadmap'
  };

  geocoder = new google.maps.Geocoder();
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

  if (geocoder) {

    // Display multiple markers on a map
    var infoWindow = new google.maps.InfoWindow();
    var counter = 0;

    for (var x = 0; x < addresses.length; x++) {

      geocoder.geocode({
        'address': addresses[x]
      }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {

            var iwContent = infoWindowContent[counter];
            var iwTitle = addresses[counter];
            var marker = new google.maps.Marker({
              position: results[0].geometry.location,
              map: map,
              title: addresses[counter]
            });
            $("#location-list").append("<li>" + addresses[counter] + "</li>");


            google.maps.event.addListener(marker, 'click', function() {
              infoWindow.setContent(iwTitle);
              infoWindow.open(map, marker);
            });



            counter++;

            // Automatically center the map fitting all markers on the screen
            bounds.extend(results[0].geometry.location);
            map.fitBounds(bounds);
          }
        }
      });
    }



  }
}

initialize();