Pablo Malynovytch Pablo Malynovytch - 1 year ago 38
Javascript Question

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

Here is my code.....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>

Answer Source

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. Arrays don't have the method .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 ++;
}