简体   繁体   English

单击时如何获取 id 并删除它? 谷歌地图 V3

[英]How to get the id when is clicked and remove that? Google Maps V3

Here is my code...I try to put event listener but the console says:这是我的代码......我尝试放置事件侦听器,但控制台说:

markers.addListener is not a function marker.addListener 不是函数

Here is my code..... https://jsfiddle.net/1LwLczgr/1/这是我的代码..... https://jsfiddle.net/1LwLczgr/1/

//The problem :(
markers.addListener('click', function() {
      var marker = this;
      alert(this.id+"alasddsasdkasdl");
});



<!--My API-->
<script async defer type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBZiX9quA0AJiAFuoxrogRYObImmbCa-6g&signed_in=true&libraries=geometry,places&callback=initMap"></script>

markers is an Array object.标记是一个数组对象。 Can't we do:我们不能这样做:

$.each(markers, function(index, value) {
// Add listener here? 
});

Reference: http://api.jquery.com/jquery.each/参考: http : //api.jquery.com/jquery.each/

Or in plain JavaScript:或者在纯 JavaScript 中:

for(var i = 0; i < markers.length; i++)
{
// Add listener here? 
}

Edit - to the question - and then inside DeleteMarkers()'s function?编辑 - 到问题 - 然后在 DeleteMarkers() 的函数中?

  • Remove listener via looping通过循环删除侦听器
  • Clear the array清除数组

Wouldn't that help?那不会有帮助吗? Please give it a try and let us know the result.请试一试,让我们知道结果。

You can only add Google Maps click listeners to a Google Maps objects that support click events (like a google.maps.Marker . markers is not a google.maps.Marker , it is an Array . Array s don't have the method .addListener .您只能将 Google Maps 单击侦听器添加到支持单击事件的 Google Maps 对象(例如google.maps.Markermarkers不是google.maps.Marker ,它是Array Array没有方法.addListener

One option would be to add the click listener to the marker when you create it:一种选择是在创建标记时将点击侦听器添加到标记中:

// Adds a marker to the map and push to the array.
function addMarker(location) {
  var marker = new google.maps.Marker({
    id:count,
    position: location,
    map: map
  });
  marker.addListener('click', function() {
    var marker = this;
    alert(this.id+"alasddsasdkasdl");
  });
  markers.push(marker);
  countmarkers ++;
  count ++;
}

而不是addListener()类型addEventListener()

It is working for me after fixing few things.在解决了一些问题后,它对我有用。 The script tag needs to be closed.脚本标签需要关闭。 The addListener was required on markers[0] (not on the markers array itself).标记 [0] 上需要 addListener(而不是标记数组本身)。 I moved the initMap function so that it doesn't complain.我移动了 initMap 函数,这样它就不会抱怨了。 I uncommented the event listener.我取消了事件侦听器的注释。 It worked.有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM