apneadiving / Google-Maps-for-Rails

Enables easy Google map + overlays creation in Ruby apps
https://apneadiving.github.io/
MIT License
2.27k stars 382 forks source link

Create callback function when marker is clicked #474

Open Gabxi opened 9 years ago

Gabxi commented 9 years ago

Hi,

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

jasonadkison commented 9 years ago

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
});
apneadiving commented 9 years ago

@jasonadkison thanks for answering :)

mightyGaby commented 9 years ago

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.

wonderer007 commented 8 years ago

@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);

    }
  );