How to Create InfoWindows for Multiple Markers in a For loop

前端 未结 1 1481

I have the following code and it correctly creates all the markers that I am storing but then when I click on any of them only the last InfoWindow is created and it only app

1条回答
  •  遥遥无期
    2021-01-12 19:08

    You need to create the markers in a separate function:

       // Global var
       var infowindow = new google.maps.InfoWindow();
    

    and then, inside the loop:

        var markerLatlng = new google.maps.LatLng(Lat, Lng);
        var title = {{record.title|json_encode|safe}}
        var iwContent = {{record.description|json_encode|safe}}
        createMarker(markerLatlng ,title,iwContent);
    

    Finally:

        function createMarker(latlon,title,iwContent) {
          var marker = new google.maps.Marker({
              position: latlon,
              title: title,
              map: map
        });
    
    
    google.maps.event.addListener(marker, 'click', function () {
        infowindow.setContent(iwContent);
        infowindow.open(map, marker);
        });
    
        }
    

    Explanation here.

    0 讨论(0)
提交回复
热议问题