jbdemonte / gmap3

jQuery plugin to create Google maps
http://gmap3.net
668 stars 198 forks source link

How to add events to previous added items #85

Closed storeman closed 8 years ago

storeman commented 8 years ago

Great, a nice update of Gmap3. We are currently experiencing some issues/unclarity with the new V7. See my code sample below.

var map = $('#selector').gmap3({...});

map.marker([{position: pos1}, {position: pos2}]);
map.on('click', function () { console.log('marker clicked'); });
map.infowindow({content: 'Hello world'});
map.then(function () {
    // How to add the infowindow to all markers? This can be done with looping
    // through the this.get(1) set of markers, but the .on would be much nicer.
});

// How to add a click event to the map in a later stadium?
// or is only the usage of addListener supported?
map.on('click', function () {});
jbdemonte commented 8 years ago

1) Infowindow / marker From: https://github.com/jbdemonte/gmap3/blob/master/dist/examples/infowindow-marker.html

  .then(function (infowindow) {
    var map = this.get(0);
    var marker = this.get(1);
    marker.addListener('click', function() {
      infowindow.open(map, marker);
    });
  })

2) event later on map Later, you can't re-use (for now, but may be a nice feature to add) a previous object to continue the chaining & use the on / once gmap3 feature, so, you need to use the native ones:

map.then(function () {
  var map = this.get(0); // see get doc, 0 here is the "map" indice
  map.addListener('click', function () {
    console.log('click');
  })
})

Notice: you should rename your main variable, because "map" is not the google maps and may be misunderstood

var handler = $("selector").gmap3({....});
storeman commented 8 years ago

Thanks for your answer.

1) Here I added two markers with different positions. Is there an easy way to add the infowindow to all markers at once? It is possible to loop through all the markers

2) Also clear. But when I would do:

var markerArray = handler.get(1);
markerArray.on('click', function () {});

This last line is not possible, but when working with 1000 or so markers, it would be a lot easier.

jbdemonte commented 8 years ago

You can do a simple:

markerArray.forEach(function (marker) { 
    marker.on('click', function () {}); 
})
berarma commented 7 years ago
markerArray.forEach(function (marker) { 
    marker.on('click', function () {}); 
})

Wouldn't this have to be:

markerArray.forEach(function (marker) { 
    marker.addListener('click', function () {}); 
})

Since the marker object doesn't have a on method.