Adding an event listener to the markers using gmaps4rails
-
14-11-2019 - |
Вопрос
I am developing an application that uses gmaps4rails (https://github.com/apneadiving/Google-Maps-for-Rails). I want to add an event listener to the marker so that it creates a visualization next to the map (as well as displaying an info window on the map). Is it possible to add an event listener for each marker using gmaps4rails?
Решение
Of course it's possible.
You should write your code in the gmaps4rails_callback
javascript function to be sure it's executed when everything is setup.
And then loop the markers
js variable: Gmaps4Rails.markers
The attributes of each marker in this array are:
longitude
latitude
google_object containing the google marker
That said you can do whatever you want.
As a side note, the map is also available doing Gmaps4Rails.map
.
In general, read the gmaps4rails.js
file, it's well documented (I hope!).
EDIT:
The problem you explain in the comments is weird, it works perfectly for me when I use:
google.maps.event.addListener(Gmaps4Rails.markers[0].google_object, 'click', function(object){ alert("hello"); });
I guess you should try to use a more traditional for
loop like:
<script type="text/javascript">
function gmaps4rails_callback() {
function say_yo(arg) { return function(){alert('yo '+ arg + '!' );};};
for (var i = 0; i < Gmaps4Rails.markers.length; ++i) {
google.maps.event.addListener(Gmaps4Rails.markers[i].google_object, 'click', say_yo(i));
}
}
</script>