简体   繁体   中英

Google Maps Marker iterating over infowindow

Okay, so with the code below I cannot figure out why when the map and the markers are generated I can only click and see the last marker generated? Any ideas on implementing this? Thanks

    <script>
    function initMap() {
        var uluru = {lat: -25.363, lng: 131.044};
        var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 5,
        center: uluru
    });

        {% for i in locations %}
        {
        var stuff = "{{ i.Name }}"
        var marker = new google.maps.Marker({
            position: { {{ i.Loc }} },
            clickable: true,
            label: "{{ i.Name }}",
            animation: google.maps.Animation.DROP,
            map: map
        });
        }
        {% endfor %}
        var infowindow = new google.maps.InfoWindow({
            content: stuff
        });
        marker.addListener('click', function() {
            infowindow.open(map, marker);
        });

    }
    </script>

So the code you're looking for is marker.setMap(null) .

To implement this you need to create a global markers array when the page loads.

window.markers = []

Then (inside the init function) push your marker into that array so you can reference it later.

var marker = new google.maps.Marker({
    ...your code...
});
markers.push(marker);

Then in your click listener you'll want to loop over it and tell Google Maps to remove each one:

for (var i = 0, marker; (marker = markers[i]); i++) marker.setMap(null);

Then ofcourse you'll want to make a new google.maps.Marker from inside your click listener.

If you throw your code into a CodePen, I could help you implement this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM