How to use Google Reverse Geocoding from Ruby
Last week, Google announced that they opened up their reverse geocoding API to the public. For anyone that started playing around with the new mobile platforms (IPhone & Android) this is good news as you can finally pinpoint where your users are.
The API documentation can be found here, but hasn’t been updated yet. To query the reverse geocoding API, one only need to request:
http://maps.google.com/maps/geo?ll=latitude,longitude&output=json
The ouput can be either JSON, XML or KML. For some reason it seems to work without any API key, bug? Here is a sample JSON output:
{"name":"-73.600000,45.500000","Status":{"code":200,"request":"geocode"},"Placemark":[{"id":"p1","address":"1405-1511 Chemin Remembrance, Montréal, QC, Canada","AddressDetails":{"Country":{"CountryNameCode":"CA","CountryName":"Canada","AdministrativeArea":{"AdministrativeAreaName":"QC","Locality":{"LocalityName":"Montréal","Thoroughfare":{"ThoroughfareName":"1405-1511 Chemin Remembrance"},"PostalCode":{"PostalCodeNumber":"H3V"}}}},"Accuracy": 8},"Point":{"coordinates":[-73.599958,45.499975,0]}}]}Finally, here is a little ruby snippet I wrote to query the API:
require 'rubygems'
require 'net/http'
require 'xmlsimple'
def reverse_geocode(lat, lng)
url = "http://maps.google.com/maps/geo?ll=#{lat.to_s},#{lng.to_s}&output=xml"
uri = URI.parse(url)
req = Net::HTTP::Get.new(uri.path + '?' + uri.query)
res = Net::HTTP.start(uri.host, uri.port) { |http| http.request(req) }
doc = XmlSimple.xml_in(res.body)
response = doc['Response'].first
if response['Status'].first['code'].first.to_i == 200
placemark = response['Placemark'].first
address = placemark['address']
end
end
puts reverse_geocode(45.50, -73.60)It only displays the address but other paramters can be parsed. If I find some time, I’ll try to make a gem for this.