将事件监听器添加到数百个Google Maps标记中 [英] Adding event listeners to hundreds of google maps markers

查看:59
本文介绍了将事件监听器添加到数百个Google Maps标记中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google Maps JavaScript API v3.我在地图上设置了大约500个标记.当我在移动设备上使用地图时,在四处移动地图并单击标记时会有很大的滞后.我认为,这种滞后是由500个标记的500个事件侦听器引起的.

我想将1个事件侦听器绑定到可以处理所有地图标记单击的地图容器,如下所示(使用jquery):

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

有什么办法可以做到这一点?

解决方案

事件处理程序的附加方式是仅将一个侦听器绑定到一个元素(#map).有关.on()的工作原理的更多信息,请参见jQuery文档: http://api.jquery.com/on/.基本上,对标记的所有单击都会冒泡直到ID为map的元素.

要完成.on()技术,请尝试利用event对象参数来找到目标标记:event.target.

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

在这里,我假设有一些实用程序getMarker,它将为给定的HTML元素返回一个Google Maps标记实例.

请注意,通过这种方式绑定事件可能会带来一些性能提升,但是由于地图上标记的数量庞大,它可能仍未达到您想要的速度.

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?

解决方案

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.

这篇关于将事件监听器添加到数百个Google Maps标记中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆