Geocoding with Ruby On Rails and Google Maps

As GoogleMaps now offers geocoding services (which works really fine for European streets !), you can use it in any web application to get coordinates from a given address. The services use REST to send queries, and you can get results in XML or JSON.

I’m currently hacking with RoR, so I first tested geocoding with a short ruby snippet:

 require 'open-uri'  require 'rubygems'  require 'hpricot'  key = 'xxx'  address = "105+avenue+de+la+Republique,+Paris,+France"  url = "http://maps.google.com/maps/geo?q=#{address}&output=xml&key=#{key}"  open(url) do |file|    @body = file.read    doc = Hpricot(@body)    (doc/:point/:coordinates).each do |link|      long, lat = link.inner_html.split(',')    end  end

I used hpricot to parse XML results, and even if it’s designed for HTML it works fine in this use case.

Yet, my initial goal was to automatically get coordinates from any address in a RoR application. I decided to add longitude and latitude properties to the class I wanted to geolocate, and add a before_save method in the model.

 # Get lat, long from address before save  def before_save    require 'open-uri'    address = CGI::escape("#{self.address},#{self.city},#{self.state},#{self.country}")    url = "http://maps.google.com/maps/geo?q=#{address}&output=xml&key=#{key}"    open(url) do |file|      @body = file.read      doc = Hpricot(@body)      (doc/:point/:coordinates).each do |link|        self.longitude, self.latitude = link.inner_html.split(',')      end    end  end

That’s it, every time a user create or edit an instance, its coordinates will be added. Well, I certainly should do more tests, but as my knowledge of ruby and rails is limited at the moment, I’ll start with this. If you think something should be changed, feel free to comment this post :) (btw, can someone tell me why I must use require 'open-uri' here, even if that’s already included in my environment.rb ?)

Comments

One Response to “Geocoding with Ruby On Rails and Google Maps”

  1. stw on November 4th, 2006 1:52 pm

    Thanks for the post, it helped me a lot. If your goal is just to have the location infos in a ruby array, then you can also consider using json (Javascript Object Notation - more lightweight than xml).

    First, ask Google Maps to send json instead of xml by replacing output=xml in your url with output=json.

    Then, parse the result json with the json gem (do a "install gem json" first). Here is the sample code:

    require ‘json’

    require ‘open-uri’

    ….

    key = ‘xxx’

    address = "Paris, France"

    url = "http://maps.google.com/maps/geo?q=#…" …

    open(url) do |file|

    result = JSON.parse(file.read)

    end

    After that, you have all the result infos in a nice little ruby array named result - no xml parsing necessary.

    More about json parsing in ruby:

    http://developer.yahoo.com/ruby/rub…

    Take care, stw

Leave a Reply

You must be logged in to post a comment.