Trying to bind multiple InfoWindows to multiple Markers on a Google Map and failing

前端 未结 3 412
暗喜
暗喜 2020-12-03 00:14

My project uses a JSON feed to grab info about earthquakes within a specified latitude and longitude boundary, essentially making a box. I take this info and turn all the r

3条回答
  •  时光取名叫无心
    2020-12-03 00:43

    This is a very common question in the google-maps tag and an easy mistake to make :).

    What is happening is that your click event is being called asynchronously and it is picking up the current value in the marker variable in the getJSON callback (the last one in the list).

    You need to wrap your addListener call in a function so that a closure is created around the marker variable that is being used in the click callback:

    function listenMarker (marker)
    {
        // so marker is associated with the closure created for the listenMarker function call
        google.maps.event.addListener(marker, 'click', function() {
                            tooltip.open(map, marker);
                        });
    }
    

    Then call listenMarker from your main getJSON callback (where you are currently calling addListener).

提交回复
热议问题