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>
markers is an Array object. Can't we do:
$.each(markers, function(index, value) {
// Add listener here?
});
Reference: http://api.jquery.com/jquery.each/
Or in plain JavaScript:
for(var i = 0; i < markers.length; i++)
{
// Add listener here?
}
Edit - to the question - and then inside DeleteMarkers()'s function?
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
.
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). I moved the initMap function so that it doesn't complain. I uncommented the event listener. It worked.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.