在Google Maps v3中的循环中标记侦听器

Marker listener in a loop in Google Maps v3

本文关键字:侦听器 循环 Maps v3 Google      更新时间:2023-09-26

我在index page中创建了一堆标记,并在循环中向它们注册侦听器。我点击其中一个标记,它会将我带到next page,在那里我有一个anchor button,它需要知道是哪个标记启动了操作。我有一个下面的场景逐步:

  • 单击标记1 //outputs a correct id 1 in console
  • 带我进入下一页//outputs a correct id 1 in console on clicking anchor
  • 返回索引页面并单击标记2 //outputs a correct id 2 in console
  • 带我进入下一页//outputs both ids 1 and 2 in console on clicking anchor

最后一步是问题所在,我只想要id 2。事实上,如果我第三次重复这个过程,我会得到所有的id 1、2和3,而在这种情况下我只想要id 3

我的代码:

$.each(otherLocations, function(index, value){
  var markerOtherLocations = new MarkerWithLabel({
    position: new google.maps.LatLng(value.latitude, value.longitude),
    map: map,
    title: value.name+" "+value.distance,
    icon: iconImage,
    labelContent: value.name+" "+value.distance,
    labelAnchor: new google.maps.Point(50, 0),
    labelClass: "labels", // the CSS class for the label
    labelStyle: {opacity: 0.60}
  });

  google.maps.event.addListener(markerOtherLocations, 'click', function() {
    $.mobile.changePage("#detail-page", { transition: "flip"} );
    console.log(value.localurl);//Outputs correct url
    $("#ref").on("click", function(){  //The problem is in this anchor click
      console.log(value.localurl);//Outputs the current as well as all the previous urls
    });
  });
});

每次单击标记OtherLocations时,它都会为导致问题的#ref注册一个全新的onclick事件回调。请记住,一个事件可以通过多次回调进行注册。考虑以下代码:

$("#ref").on("click", function(){  
  console.log('do function A');//register A first
});
$("#ref").on("click", function(){ 
  console.log('do function B');//register B later, which won't be overridden.
});
//If you click #ref then, it'll output A and B, following the registered sequence before.

所以在我看来,你的代码可能是:

google.maps.event.addListener(markerOtherLocations, 'click', function() {
  $.mobile.changePage("#detail-page", { transition: "flip"} );
  console.log(value.localurl);//Outputs correct url
  $("#ref").data('origin',value.localurl);
});
$("#ref").on("click", function(){ // register once 
  console.log($(this).data('origin'));
});