Maps are integral part of any application with spatial data. In the past, I’ve utilized Google Maps interface with the YM4R plugin. It was always a little cumbersome in spots but did the trick. There was also the restriction of having to register a key for use in each API call.
But what if you wanted to take advantage of great version 3 features like Street View or Driving Directions? You’d be a little wanting as the YM4R plugin only supported V2 of the API.
Enter the cartographer plugin (https://github.com/joshuamiller/cartographer). This plugin provides both v2 and v3 API support, as well as clean Rails 3 integration. I feel the code is a little cleaner too. Here’s a brief tutorial of how to add it to your application.
Either install the plugin for via:
rails plugin install git://github.com/joshuamiller/cartographer.git
git clone git://github.com/joshuamiller/cartographer.git vendor/plugins/cartographer
Next, you will need to add some basic code to your controller to create the map object. I prefer to create a helper to do this as it will be used frequently.
module GoogleMapsHelper def map_init @map=Cartographer::Gmap.new('map') @map.zoom=:bound @map.icons << Cartographer::Gicon.new end end
I typically add code to the model to be mapped to create the geomarker and info window.
class Site < ActiveRecord::Base def geomarker Cartographer::Gmarker.new(:name=> 'site', :marker_type => "Building", :position => ll) end def ll Array.( location.y, location.x ) end end
From within the controller, call the initialization method and add a marker.
class HousesController < ApplicationController include GoogleMapsHelper def index if @site map_init @map.markers << @site.geomarker end # and more code... end end
Finally to your view, add the necessary code to render the map to a div with the specified id.
<div id='map'> <%= raw Cartographer::Header.new.to_s %> <%= raw @map.to_html %> </div>
And that’s it! Pretty simple and very clean in my estimation. I’m now not dreading the upgrade of my mappable applications to Google Maps v3.