95

I am trying to add multiple markers each with its own infowindow that comes up when clicked on. I am having trouble with getting the infowindows coming up, when I try it either shows up only one marker without an infowindow.

Thanks, let me know if you need some more information

<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<style type="text/css">
html {
    height: 100%
}

body {
    height: 100%;
    margin: 0;
    padding: 0
}

#map_canvas {
    height: 100%
}
</style>
<script type="text/javascript"
    src="http://maps.googleapis.com/maps/api/js?key=AIzaSyB1tbIAqN0XqcgTR1-FxYoVTVq6Is6lD98&sensor=false">
</script>
<script type="text/javascript">

var locations = [
    ['loan 1', 33.890542, 151.274856, 'address 1'],
    ['loan 2', 33.923036, 151.259052, 'address 2'],
    ['loan 3', 34.028249, 151.157507, 'address 3'],
    ['loan 4', 33.80010128657071, 151.28747820854187, 'address 4'],
    ['loan 5', 33.950198, 151.259302, 'address 5']
];

function initialize() {

    var myOptions = {
        center: new google.maps.LatLng(33.890542, 151.274856),
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP

    };
    var map = new google.maps.Map(document.getElementById("default"),
        myOptions);

    setMarkers(map, locations)
}


function setMarkers(map, locations) {

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

        var loan = locations[i][0]
        var lat = locations[i][1]
        var long = locations[i][2]
        var add = locations[i][3]

        latlngset = new google.maps.LatLng(lat, long);

        var marker = new google.maps.Marker({
            map: map, title: loan, position: latlngset
        });
        map.setCenter(marker.getPosition())

        var content = "Loan Number: " + loan + '</h3>' + "Address: " + add

        var infowindow = new google.maps.InfoWindow()

        google.maps.AddListener(marker, 'click', function (map, marker) {
            infowindow.setContent(content)
            infowindow.open(map, marker)
        });
    }
}


</script>
</head>
<body onload="initialize()">
<div id="default" style="width:100%; height:100%"></div>
</body>
</html>
stacktraceyo
  • 1,215
  • 3
  • 15
  • 22
  • 2
    Use only ONE infowindow that is created before the markers. Then your click event for each marker will work correctly. The variable `content` inside your event listener is not defined within that function. – js1568 Jun 19 '12 at 18:03
  • 1
    Just as a quick comment, if you format your code well, it's a lot easier to read. – paullb Jul 20 '17 at 13:54
  • 1
    @paullb I will reformat it, I wrote this question like 4 years ago when I was more of a novice :) – stacktraceyo Jul 24 '17 at 19:09
  • Check this tutorial to show multiple marker infoWindow with click and Hover http://www.freakyjolly.com/embed-google-maps-with-multiple-markers-and-infowindows-info-popups-open-on-click-or-mouse-hover/ – Code Spy Feb 19 '19 at 09:33

5 Answers5

206

You could use a closure. Just modify your code like this:

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

Here is the DEMO

Eric Platon
  • 8,821
  • 6
  • 37
  • 45
Engineer
  • 43,887
  • 11
  • 83
  • 90
  • 2
    I got this working but how would I change the code so that when I click on another marker it opens an infowindow which replaces the infowindow that was previously open, instead of continually opening more infowindows every time I click on another marker? – railsy May 10 '13 at 17:41
  • it works! but can somebody pls explain to me why is it working this way? – Lakshay Apr 06 '15 at 08:11
  • 1
    @Lakshay You can read about similar problem [here](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Engineer Apr 06 '15 at 12:21
  • 1
    in this case, how should one close the infowindow when you click outside the map? – Rohit Tigga Mar 02 '16 at 06:54
  • How to close infowindow? `infowindow.close()` don't work. – mokiSRB Mar 03 '16 at 14:10
  • infoWindow **can be closed** simply by using a common variable: http://jsfiddle.net/ZFvDV/177/ – Manoj De Mel Dec 07 '17 at 00:28
10

Here is the code snippet which will work for sure. You can visit below link for working jsFiddle and explainantion in detail. How to locate multiple addresses on google maps with perfect zoom

var infowindow = new google.maps.InfoWindow();  
google.maps.event.addListener(marker, 'mouseover', (function(marker) {  
           return function() {  
               var content = address;  
               infowindow.setContent(content);  
               infowindow.open(map, marker);  
           }  
         })(marker));  
evaipar
  • 151
  • 2
  • 11
7

Source Link

Demo Link

The following code will show Multiple Markers with InfoWindow. You can Uncomment code to show Info on Hover as well

enter image description here

            var map;
            var InforObj = [];
            var centerCords = {
                lat: -25.344,
                lng: 131.036
            };
            var markersOnMap = [{
                    placeName: "Australia (Uluru)",
                    LatLng: [{
                        lat: -25.344,
                        lng: 131.036
                    }]
                },
                {
                    placeName: "Australia (Melbourne)",
                    LatLng: [{
                        lat: -37.852086,
                        lng: 504.985963
                    }]
                },
                {
                    placeName: "Australia (Canberra)",
                    LatLng: [{
                        lat: -35.299085,
                        lng: 509.109615
                    }]
                },
                {
                    placeName: "Australia (Gold Coast)",
                    LatLng: [{
                        lat: -28.013044,
                        lng: 513.425586
                    }]
                },
                {
                    placeName: "Australia (Perth)",
                    LatLng: [{
                        lat: -31.951994,
                        lng: 475.858081
                    }]
                }
            ];

            window.onload = function () {
                initMap();
            };

            function addMarkerInfo() {
                for (var i = 0; i < markersOnMap.length; i++) {
                    var contentString = '<div id="content"><h1>' + markersOnMap[i].placeName +
                        '</h1><p>Lorem ipsum dolor sit amet, vix mutat posse suscipit id, vel ea tantas omittam detraxit.</p></div>';

                    const marker = new google.maps.Marker({
                        position: markersOnMap[i].LatLng[0],
                        map: map
                    });

                    const infowindow = new google.maps.InfoWindow({
                        content: contentString,
                        maxWidth: 200
                    });

                    marker.addListener('click', function () {
                        closeOtherInfo();
                        infowindow.open(marker.get('map'), marker);
                        InforObj[0] = infowindow;
                    });
                    // marker.addListener('mouseover', function () {
                    //     closeOtherInfo();
                    //     infowindow.open(marker.get('map'), marker);
                    //     InforObj[0] = infowindow;
                    // });
                    // marker.addListener('mouseout', function () {
                    //     closeOtherInfo();
                    //     infowindow.close();
                    //     InforObj[0] = infowindow;
                    // });
                }
            }

            function closeOtherInfo() {
                if (InforObj.length > 0) {
                    InforObj[0].set("marker", null);
                    InforObj[0].close();
                    InforObj.length = 0;
                }
            }

            function initMap() {
                map = new google.maps.Map(document.getElementById('map'), {
                    zoom: 4,
                    center: centerCords
                });
                addMarkerInfo();
            }
Code Spy
  • 7,520
  • 3
  • 57
  • 39
2

If you also want to bind closing of infowindow to some event, try something like this

google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){ 
    return function() {
        infowindow.setContent(content);
        infowindow.open(map,marker);
        windows.push(infowindow)
        google.maps.event.addListener(map,'click', function(){ 
            infowindow.close();
        }); 
    };
})(marker,content,infowindow)); 
0
function setMarkers(map,locations){

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

 var loan = locations[i][0];
 var lat = locations[i][1];
 var long = locations[i][2];
 var add =  locations[i][3];

 latlngset = new google.maps.LatLng(lat, long);

 var marker = new google.maps.Marker({  
          map: map, title: loan , position: latlngset  
 });
 map.setCenter(marker.getPosition());


 marker.content = "<h3>Loan Number: " + loan +  '</h3>' + "Address: " + add;


 google.maps.events.addListener(marker,'click', function(map,marker){
          map.infowindow.setContent(marker.content);
          map.infowindow.open(map,marker);

 });

 }
}

Then move var infowindow = new google.maps.InfoWindow() to the initialize() function:

function initialize() {

    var myOptions = {
      center: new google.maps.LatLng(33.890542, 151.274856),
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP

    };
    var map = new google.maps.Map(document.getElementById("default"),
        myOptions);
    map.infowindow = new google.maps.InfoWindow();

    setMarkers(map,locations)

  }
js1568
  • 6,800
  • 2
  • 23
  • 46
  • 1
    `google.maps.events.AddListener` should be `google.maps.event.addListener` – Patrick Yan May 04 '14 at 14:47
  • I get `TypeError: map.infowindow is undefined` if I include `var infowindow = new google.maps.InfoWindow();` inside of my initialize() function – invot Jul 25 '14 at 18:58