Conrad Lewis
Conrad Lewis

Reputation: 55

Adding event listeners to hundreds of google maps markers

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?

Upvotes: 1

Views: 2493

Answers (2)

Xotic750
Xotic750

Reputation: 23472

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

Upvotes: 0

Rick Viscomi
Rick Viscomi

Reputation: 8852

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.

Upvotes: 3

Related Questions