Search code examples
javascriptgoogle-mapsinfowindow

Open info windows separately on an embedded Google Map


I am trying to embed Google Maps on a website, and include info windows to open on separate markers on the map. Currently I have been able to get the info windows to open , but unfortunately both windows open when the first marker is clicked on.

Need to find a way to isolate the info windows, and link them to the correct marker.

Can anyone help? Code so far attached below.

<!-- map - -->

                <div id="map"></div>
                <script>
                function initMap() {
                var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 4,
                 center: {lat: 47.852163, lng: 16.526384}

                 });



                 var contentString1= '<div id="content">'+
               '<div id="siteNotice">'+
                  '</div>'+
                 '<h1>Caravan Salon</h1>'+
                    '<div>'+
                  '<p>Messe Düsseldorf, Arena-Straße, GERMANY, 40474 </p>'+
                  '</div>'+
                  '</div>';

                 var infowindow1 = new google.maps.InfoWindow({
                 content: contentString1
                });
                    // Caravan Salon
                 var marker = new google.maps.Marker({
                position: {lat: 51.263620, lng:  6.735830},
                 map: map
                  });

                  marker.addListener('click', function() {
                 infowindow1.open(map, marker);
                    });






            var contentString= '<div id="content">'+
              '<div id="siteNotice">'+
                 '</div>'+
              '<h1 id="firstHeading" class="firstHeading">Thomas Gieger Pop up Caravans</h1>'+
              '<div id="bodyContent">'+
              '<p>Hummelbühel, 569 7000, Eisenstadt, Austria </p>'+       '</div>'+
              '</div>';


               var infowindow2 = new google.maps.InfoWindow({
                 content: contentString
                });
                 // Thomas Gieger 
                var marker2 = new google.maps.Marker({
                  position: {lat: 47.852163, lng: 16.526384},
                  map: map     

                     });
                    marker.addListener('click', function() {
                     infowindow2.open(map, marker2);
                     });
                    }
                 </script>







             <script async defer
                  src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCbKJArdmwTF9-_qQa10SovlgJO2kNRo9c&callback=initMap">
             </script>

Solution

  • You have a typo:

    marker.addListener('click', function() {
      infowindow2.open(map, marker2);
    });
    

    should be:

    marker2.addListener('click', function() {
      infowindow2.open(map, marker2);
    });
    

    proof of concept fiddle