tomtaylor.co.uk

Blog

UK Geocoding with Graticule & Google Maps

Tuesday, May 15th, 2007 at 5:02 pm in Life.

Tagged with: , , , , , .

I’ve been saving this post for a couple of days, until the bug fixes to the LocalSearchMaps geocoder that I’d submitted had made it into the latest release. 0.2.4 is now ready to download.

Graticule is a Ruby (and Rails) based geocoding API for looking up address coordinates and performing distance calculations. It supports a number of geocoders, including LocalSearchMaps, which can do full UK postcode lookups by bouncing off the Google Maps API.

require 'rubygems'
require 'graticule'
geocoder = Graticule.service(:local_search_maps).new
location = geocoder.locate :postal_code => 'W1A 1AA', :country => 'UK'
location.coordinates
=> [51.518692, -0.144003]

With the longitude and latitude sorted, you could generate a Google Map with the google4r-maps plugin. Make sure you don’t install the ‘google4r’ gem, you need the ‘google4r-maps’ gem or it’ll get very confused.

require 'rubygems'
require 'google4r/maps'
map = Google4R::Maps::GMap2.new("map", "map-div")
map.center = location.coordinates
map.create_marker = location.coordinates
map.to_html

Or perhaps you want to out find how far two postcodes are away from each other?

bbc_broadcasting_house = geocoder.locate :postal_code => 'W1A 1AA', :country => 'UK'
buckingham_palace = geocoder.locate :postal_code => 'SW1A 1AA', :country => 'UK'
buckingham_palace.distance_to(bbc_broadcasting_house, options = { :formula => :haversine, :units => :miles } )
=> 1.23139851951363
buckingham_palace.distance_to(bbc_broadcasting_house, options = { :formula => :haversine, :units => :kilometers } )
=> 1.98175469446664

Thanks go to Brandon (and others?) at Collective Idea for making Graticule.

Comments

  1. Daniel Morrison on May 16th, 2007 at 2:48 am

    Thanks for the great write-up, and we’re glad you’re enjoying Graticule!

  2. Moyeen on May 30th, 2007 at 7:27 pm

    Hi,

    Can u please explain on how to use google4R api from gem installation to getting sample view

    or mail me

  3. Tom on June 3rd, 2007 at 9:50 am

    Hi Moyeen,

    You basically just install the gem, get a Google Map API key, put the Google Maps javascript in the header of the page, and then generate a map using google4r-maps, which should all be documented on their API page.