Maps API v3 Infowindows with multiple markers

http://stackoverflow.com/questions/24803074

by Glynne Turner

HTML

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false"></script>
 

51.384 1.38811

CSS

html, body, #map {
     height: 100%;
     width: 100%;
     margin: 0px;
     padding: 0px;
 }

JavaScript

var markers = [];

    function initialize() {
    
        var beaches = [
            ['Bondi Beach', -33.890542, 151.274856 ],
            ['Coogee Beach', -33.923036, 151.259052 ],
            ['Cronulla Beach', -34.028249, 151.157507 ],
            ['Manly Beach', -33.800101, 151.287478 ],
            ['Maroubra Beach', -33.950198, 151.259302 ]
        ];
    
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 10,
            center: new google.maps.LatLng(-33.88, 151.28),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
    
        var infowindow = new google.maps.InfoWindow();
    
        for (var i = 0; i < beaches.length; i++) {
    
            var newMarker = new google.maps.Marker({
                position: new google.maps.LatLng(beaches[i][1], beaches[i][2]),
                map: map,
                title: beaches[i][0]
            });
    
            google.maps.event.addListener(newMarker, 'click', (function (newMarker, i) {
                return function () {
                    infowindow.setContent(beaches[i][0]);
                    infowindow.open(map, newMarker);
                }
            })(newMarker, i));
    
            markers.push(newMarker);
        }
    }
    
    initialize();