Adding event listeners to hundreds of google maps markers

扶醉桌前 提交于 2020-06-28 06:28:11

问题


I'm using google maps javascript api v3. I have approx 500 markers set on the map. When I'm using the map on a mobile device there is significant lag when moving the map around and clicking on markers. I believe this lag is caused by having 500 event listeners for the 500 markers.

I'd like to bind 1 event listener to the map container that can handle all map marker clicks, like this(using jquery):

$('#map').on('click', 'marker', function(event) {

    alert('marker clicked: ' + marker.uniqueInfo);
});

Is there any way to accomplish this?


回答1:


The way the event handler is attached is only binding one listener to one element (#map). See the jQuery documentation for more on how .on() works: http://api.jquery.com/on/. Basically any and all clicks to the markers bubble up to the element with ID of map.

To accomplish the .on() technique, try utilizing the event object argument to find the targeted marker: event.target.

$('#map').on('click', 'marker', function(event) {
    var marker = getMarker(event.target);
    alert('marker clicked: ' + marker.uniqueInfo);
});

Here, I'm assuming there is some utility getMarker that will return a Google Maps marker instance for the given HTML element.

Be aware that there may be some performance gains from binding the event this way, but it still may not be as fast as you would like simply due to the sheer volume of markers on the map.




回答2:


This is only 1 event listener (so I believe) and acts on bubbled or propagated events, using jQuery.on in delegated mode, no idea what the performance difference would be like on your device.

HTML

<div id="map">
    <div class="marker">1</div>
    <div class="marker">2</div>
    <div class="marker">3</div>
    <div class="marker">4</div>
    <div class="marker">5</div>
    <div class="marker">6</div>
    <div class="marker">7</div>
    <div class="marker">8</div>
    <div class="marker">9</div>
</div>

Javascipt

$(document).on('click', '#map .marker', function (event) {
    alert('marker clicked: ' + event.target.textContent);
});

On jsfiddle



来源:https://stackoverflow.com/questions/16288525/adding-event-listeners-to-hundreds-of-google-maps-markers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!