In my actual RoR project I have a heavy usage of Google Maps. For gecoding I use the well known geokit plugin. But for rendering the maps I stepped across YM4R/GM.
It is so damn easy to render maps by writing Ruby code - and much more DRY than manually building your Javascript code!
From my point of view it is nearly a 1:1 Ruby mapping of what you can do with the GMap2 API.
While writing my first lines of YM4R/GM code I got a little bit nevous - what I wanted to do was just not working. YM4R/GM is quite well documented, but left out the hint for my actual problem. Finally I managed it, so I want to share my Heureka! with you:
The Situation:
I just wanted to create a map, initially add a Marker to it and add an event listener to this Marker …
My first code was:
@map = GMap.new(”map”)
@map.control_init(:map_type => false, :small_zoom => true)
@map.center_zoom_init(@shot.lat_lng, 15)
@marker = GMarker.new(@shot.lat_lng)
@map.overlay_init(@marker)
@map.event_init(@marker,:click, “function(){window.location.href =’#{shot_url(@shot)}’;}”)
and the output was:
map = new GMap2(document.getElementById(”map”));
map.setCenter(new GLatLng(48.221131,16.371907),15);
map.addOverlay(new GMarker( new GLatLng(48.221131,16.371907)));
GEvent.addListener(new GMarker( new GLatLng(48.221131,16.371907)) ,click”,
function(){window.location.href = ‘http://localhost:3002/shots/2-Peter’;});
map.addControl(new GSmallZoomControl());
So, as you can see, this code produced a Marker for adding to the map but a different Marker for assigning the event.
This code works:
@map = GMap.new(”map”)
@map.control_init(:map_type => false, :small_zoom => true)
@map.center_zoom_init(@shot.lat_lng, 15)
@marker = GMarker.new(@shot.lat_lng)
@map.declare_init(@marker, “marker_var_name”)
@map.overlay_init(@marker)
@map.event_init(@marker, :click,
“function(){window.location.href = ‘#{shot_url(@shot)}’;}”)
The bold line says YM4R to handle the variable @marker as a javascript variable further on!
the correct output:
map = new GMap2(document.getElementById(”map”));
map.setCenter(new GLatLng(48.221131,16.371907),15);
var marker_var_name = new GMarker(new GLatLng(48.221131,16.371907));
map.addOverlay(marker_var_name);
GEvent.addListener(marker_var_name,”click”,
function(){window.location.href = ‘http://localhost:3002/shots/2-Peter’;});
map.addControl(new GSmallZoomControl());
In the next couple of days I will try out the built in RJS magic to update Markers after changing the view of the map. Will get back to you with some new experiences.