Creating direction from source to destination in Google Map using Rails

Google map in Rails application is implemented by YM4R  gem/ ym4r_gm plugin. Suppose anyone one to see direction in Google Map From his address to destination address by clicking his city point in Map. The following code in Ruby on Rails do that with a bit of JavaScript function...........
def initiate_map fromadd , toadd
@map = GMap.new("map_div");
@map.control_init(:large_map  => true,:map_type => true)
@map.center_zoom_init([38.957101, -95.251469],4)
@map.overlay_init(GMarker.new(fromadd))
@map.event_init(@map, :dblclick,"function(marker,address){ if (marker)
{map.removeOverlay(marker); } else {
var gdir;
gdir  = new GDirections(map, document.getElementById('directions'));
gdir.load('from: ' + '#{fromadd}' + ' to: ' + '#{toadd}');
}}" )
end
Now for dynamically updating the direction do the following code….

def initiate_map1 fromadd , toadd
@map=GMap.new('map_div')
@js_str = "var geocoder = new GClientGeocoder(); \n"+
"geocoder.getLatLng( '#{MappingObject.javascriptify_variable(fromadd)}',function(point) {
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
marker.openInfoWindowHtml('#{MappingObject.javascriptify_variable(fromadd)}');
}) ; \n" +
"GEvent.addListener(map, \"click\", function(address) { var gdir  = new GDirections(map, document.getElementById('directions'));
gdir.load('from: ' + '#{MappingObject.javascriptify_variable(fromadd)}' + ' to: ' + '#{MappingObject.javascriptify_variable(toadd)}');});"
end

After that you have to write  page << @js_str in a js tempalte. In the view write this code

=GMap.header
=@map.to_html
=@map.div(:width => 600, :height => 400)
.directions

All is done. 

Advertisements