I was looking for a good Google Maps solution in Ruby on Rails 3. I got a bit frustrated with solutions like YM4R, which basically require you to dive into javascript.
gmaps4rails favours a more Railsesque approach.
Basically you create a model with lon and lat fields (floats) in your model as the markers on the map.
Then you tell gmaps4rails to create a map out of that by adding this to your model:
acts_as_gmappable :lat=>:lat,:lng=>:lon,:process_geocoding=>false,:check_process=>false
Basically you tell it which columns contain the latitude and longitude values, and since you can also use geocoding to translate address values (which I didn't need for my project) there is a 'process_geocoding' switch. Check_process is also geocoding related.
The interesting bit is that gmaps4rails uses the V3 Api, meaning that you don't need to create a key as you did with Ym4r. Saves some hassle when moving stuff from test environment to production.
This also means that you can use it to add stuff to the map. For instance, I use it to track shipping movements. The position alone is not enough, I also need to see where that ship has been the last few hours. The easiest way is to create 360 icons (one for each bearing) and add a line to the ship.
The ship's bearing (course) is in the database, so I only needed this to create the markers which show the ship directions in the model:
def gmaps4rails_marker_picture
course = self.last_course
{
"picture" => "/images/shipred/meshes" + sprintf("%04d",course.to_i) + ".png",
"width" => "32",
"height" => "32"
}
end
(the marker pictures, one for each direction are in /images/shipred/meshes0000.png where 0000 can go up to 0365).In the controller I have something like this:
@markers << vessel.to_gmaps4rails
for the markers. For the lines that I draw behing the ships I needed to create a JSON structure. Easy enough. Rails can do that. All we need is an empty array, where add one array per line to, with the first element of the array in the array the color of the line that we wish to draw.
@polylines = []
...
for vessel in @vessels #then in a loop we make a new line
@polyline = [{"strokeColor"=>color}]
for position in vessel.todaypositions #todaypositions returns the positions that the vessel had today
@polyline << {"longitude" => postion[:lon],"latitude" => position[:lat] }
end
@polylines << @polyline
end
That sums up our controller.
This is my view:
<%=
gmaps( {
"map_options" => {"map_container_id" => "map_container", "auto_adjust" => "false"},
"markers" => { "data" => @markers },
"polylines" => { "data" => @polylines.to_json }
}) %>
That sums it up. The result: A google map with shipping info and a trail behind every marker on the screen and look ma, I didn't need to use any javascript.




