Geo-comments: Gmaps on Rails

I’ve spent the last week messing with google maps for various projects. Finally got everything working great.

I’ve modified Typo to have a Geo-comment feature. (when you add a comment you can enter your zip code and it will put your comment on the map!)

Using Google Maps on Rails Model

  • Add lat & lng as a double to your model. * Add a snippet of code to your model to grab the lat,lng from google
  require 'open-uri'
  require 'cgi'

  # ... rest of model ...

  def before_save
    begin
      pattern = /<point lat="([^"]*)" lng="([^"]*)"\/>/
      url = 'http://maps.google.com/?q='+CGI::escape( self.address + ... + ' US' )
      loc = open(url).read.scan(pattern)
      self.lat = loc[0][0]
      self.lng = loc[0][1]
    rescue
      # google says "did you mean . . . ?" if there 
  # were multiple places the address matched.
      # I've been sending them back to the user 
      # asking them to choose
    end
  end

Controllers

You will need a controller to control what the user sees and what google sees. (read the Views section if this doesn’t make sense.)

You will need a controller to process the data for the html page you serve. This controller (probably) doesn’t generate the xml data (see end of post for more discussion), as google will request that later.

Then you need a controller that does a find on your data – nothing new here – passing it to a data view.

Views

What the user sees: (here be magic)

There are two ways to embed google maps, either as a small view or a application view – the map app has keys capture working for easier movement.

What google sees: (the xml view for data)

In the above view, it references a XML file to poll data from, contrary to what you think, you probably DO NOT want to use a .rxml file, as it takes longer than just typing the xml out yourself.

Warning: if your xml isn’t valid google will not process it!

This file looks just like the xml files from the above demos.

XSL (another cool technology) is used to create the views for the maps… Nothing ruby specific here, just take the examples, read some faqs, and make yours do what you want.


Ok, you don’t have to have two seperate views, instead of doing a xmlhttprequest, you can just send the xml (created via a partial) with the main view, and be done with it… To keep things simple, I recommend keeping two seperate views until you are done, then combining them (as checking validity of xml is easier if you don’t have to copy and paste, ...)


Share/Save/Bookmark

Published

Thu, 09 Jun 2005

View Comments


Want more like this?

Subscribe via RSS
or by email:

New Relic