Open Gabxi opened 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
});
@jasonadkison thanks for answering :)
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 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);
}
);
Hi,
I was wondering if you have a sample code on how to create a callback function when a marker is clicked.