Google Maps Multiple Markers

by Arkadiy68

HTML

<script src="//maps.google.com/maps/api/js?sensor=false"></script>
<div id="map" style="width: 100%; height: 400px;"></div>

<ul class="list locations">
  <li>
    <div class="location-name">Place 1</div>
    <div class="location-address">Washington, DC</div>
  </li>
  <li>
    <div class="location-name">Place 2</div>
    <div class="location-address">Houston, TX</div>
  </li>
  <li>
    <div class="location-name">Place 3</div>
    <div class="location-address">New York, NY</div>
  </li>
  <li>
    <div class="location-name">Place 4</div>
    <div class="location-address">Miami, FL</div>
  </li>
  <li>
    <div class="location-name">Place 5</div>
    <div class="location-address">Atlanta, GA</div>
  </li>
</ul>

JavaScript

// Get all location names and make an array
var locationName = [];
$('.locations li div.location-name').each(function() {
  locationName.push($(this).text());
});

// Get all location addresses and make an array
var locationAddress = [];
$('.locations li div.location-address').each(function() {
  locationAddress.push($(this).text());
});

// Combine location names and location addresses into one multidimensional array
var locations = [];
for (var i = 0; i < locationName.length; i++) {
  locations.push([locationName[i], locationAddress[i]]);
}

var infowindow = new google.maps.InfoWindow();
var geocoder = new google.maps.Geocoder();
var marker, i;

for (i = 0; i < locations.length; i++) {
  geocodeAddress((locations[i]));
}

function geocodeAddress(location) {
  geocoder.geocode({
    'address': location[1]
  }, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {

      //alert(results[0].geometry.location);
      map.setCenter(results[i].geometry.location);
      
      createMarker(results[0].geometry.location, "<b>" + $(".location-name").html() + "</b><br>" + $(".location-address").html());
    } else {
      alert("some problem in geocode" + status);
    }
  });
}

function createMarker(latlng, html) {
  var marker = new google.maps.Marker({
    position: latlng,
    map: map
  });

  google.maps.event.addListener(marker, 'mouseover', function() {
    infowindow.setContent(html);
    infowindow.open(map, marker);
  });

  google.maps.event.addListener(marker, 'mouseout', function() {
    infowindow.close();
  });
}

var markers = []; //some array
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
  bounds.extend(markers.getPosition());
}

var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 18,
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

map.fitBounds(bounds);