Jquery谷歌地图插件,添加事件监听器

有人可以解释在google jquery.ui.map插件中找到的以下代码片段( jQuery.fn[name] )的含义 :

 jQuery.each(('click mousedown rightclick dblclick mouseover mouseout drag dragend').split(' '), function(i, name) { jQuery.fn[name] = function(a, b) { return this.addEventListener(name, a, b); }; }); 

以及我们如何将回调函数绑定到地图对象上的click事件,我尝试了以下但event没有latLng属性:

 $('#map_canvas').gmap().click(function(event) { alert(event.latLng); }); 

提前致谢。

这段代码会覆盖一些jQuery方法,以便可以在某些 Google Maps对象上使用。 例如

  var map = $('#map_canvas').gmap('get', 'map') $(map).click(function() { var self = this; // this is the map object }); $('#map_canvas').gmap('addMarker', { ... }).click(function() { var self = this; // this refers to the marker object }).hover(function() { var self = this; // this refers to the marker object }); 

如果你需要绑定其他事件,比如zoom_changed那么

 var map = $('#map_canvas').gmap('get', 'map'); $(map).addEventListener('zoom_changed', function() { }); 

您已经回答了自己的问题:)如果您想将事件绑定到Google地图,则必须使用this.addEventListener(name, a, b); (这实际上是允许您在某些事件上执行函数的代码。见下文)

例:

  google.maps.event.addListener(my_map_object, 'click', function() { my_map_object.setZoom(8); alert("I've just zoomed by clicking the map!"); }); 

您可以向地图对象或您在地图上放置的任何标记添加事件。

有关完整说明,请参阅https://developers.google.com/maps/documentation/javascript/events 。 谷歌地图API有很好的使用范例,你可以从中学到很多:)

 google.maps.event.addListener(marker, 'mouseover', function() { $('.hover_div').html(''+marker.hover + marker.title +'').show(); }); 

要么

  google.maps.event.addListener(marker, 'click', function() { window.open( marker.url, '_blank' // <- This is what makes it open in a new window. ); 

我不会使用插件,因为它限制了你的工作。 尝试阅读如何自己创建地图。

我发现从页面中窃取所有事件并将它们重新分配到地图会导致委托事件不再起作用。 例如,如果您尝试trigger()单击另一个元素,则它不起作用。 例如 – 在on("click")设置事件监听器仍然有效,它将不再监听以编程方式触发的点击。

我在我自己的文件副本上修改了代码。 在这里,万一有人感兴趣。 它更改函数的“名称”以在前面添加“map”,并将原始方法的第一个字母大写:

click()更改为mapClickdragend更改为mapDragend等。

 jQuery.each(('click rightclick dblclick mouseover mouseout drag dragend').split(' '), function (i, name) { jQuery.fn["map" + name[0].toUpperCase() + name.substr(1)] = function (a, b) { return this.addEventListener(name, a, b); } });