Google-Maps-for-Rails icon indicating copy to clipboard operation
Google-Maps-for-Rails copied to clipboard

Create callback function when marker is clicked

Open Gabxi opened this issue 10 years ago • 4 comments

Hi,

I was wondering if you have a sample code on how to create a callback function when a marker is clicked.

Gabxi avatar Feb 01 '15 08:02 Gabxi

I had to figure this out recently. You can try doing something like this.

var marker = handler.addMarker({
  lat: location.latitude,
  lng: location.longitude
});

google.maps.event.addListener(marker.serviceObject, 'click', function(e) {
  console.log(this); // the marker instance
});

jasonadkison avatar Feb 12 '15 05:02 jasonadkison

@jasonadkison thanks for answering :)

apneadiving avatar Feb 13 '15 08:02 apneadiving

This might be a slightly overkill way of doing it for this gem, but in a completely client-side application using an ajax call to get an array of objects, I did the following in the success function:

//generates a marker for each data point returned in the ajax call

for (var i = 0; i < data.length; i++) {
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(data[i].latitude, data[i].longitude),
    map: map,
    title: data[i].address
  });

//creates a click-event for each marker

google.maps.event.addListener(marker, 'click', (function(marker, i) {
    var markerAddress = marker.title;
    return function() {
      console.log(markerAddress)
      $("#saved").append("<li>"+ markerAddress + "</li>");
    }
  })(marker, i));
};

In this case, the listener callback also renders the address associated with the marker to "saved" element on the DOM.

mightyGaby avatar Jun 01 '15 19:06 mightyGaby

@mightyGaby Is it possible to open info window as well as zoom to the marker when clicked ? I tried with your code but its not working it instead open the info window, here is what I am doing

  var data = <%=raw @hash.to_json %>;
  var markers = [];

  for (var i = 0; i < data.length; i++) {
    marker = new google.maps.Marker(data[i]);

    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        var markerAddress = marker.title;
        return function() {
          console.log(markerAddress);
        }
      })(marker, i));

    markers.push(marker);
  };

  var handler = Gmaps.build('Google');
  handler.buildMap({
      provider: {
        panControl: true,
        zoomControl: true,
        mapTypeControl: true,
        scaleControl: true,
        streetViewControl: true,
        overviewMapControl: true
      },
      internal: {
        id: 'map'
      }
    },
    function() {
      handler.bounds.extendWith(handler.addMarkers(markers));
      handler.fitMapToBounds();
      handler.getMap().setZoom(6);

    }
  );

wonderer007 avatar Jun 22 '16 09:06 wonderer007