Loint
Loint

Reputation: 3938

How to add an addListener function for an object javascript?

I have add an listen event for a marker such as

var markers = locations.map(function(location, i) {
    return new google.maps.Marker({
        position: location,
        label: labels[i % labels.length]
    });
});

// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers, {
    imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});

markerCluster.addListener('click', function() {
    console.log('click action');
});

When I click into a marker on google map. My click function doesn't work. How to implement this task?

Upvotes: 0

Views: 969

Answers (2)

Miguel Coder
Miguel Coder

Reputation: 1954

You have to add the listener to the marker object.

https://developers.google.com/maps/documentation/javascript/events

marker.addListener('click', function(){
    // do something here.
})

since you are returning it in your function as an array it would be ...

for(id in markers) { 
    markers[id].addListener('click',function(){
        //your code});     
}

That should work.

Check out this JSFiddle

Upvotes: 1

putvande
putvande

Reputation: 15213

You likely need a custom Google click handler like:

google.maps.event.addListener(markerCluster, 'clusterclick', function(cluster) {
  // your code here.
});

Upvotes: 1

Related Questions