Thursday, December 31, 2009

Been playing with Googlemaps

Been playing with googlemaps and rails. The first step is geo-coding the address to Lat long coordinates.

Here is my first play code

require 'net/http'
require 'uri'
require 'rubygems'
require 'builder'

addrs = [ "1600+Amphitheatre+Parkway,+Mountain+View,+CA",
"1159 Gympie Rd Aspley QLD 4034 ",
"14 Morayfield Rd Caboolture QLD 4510 ",
"521 Ipswich Rd Annerley QLD 4103 "
]

placemarkbase = 'List'
placemarks = Hash.new

xml = Builder::XmlMarkup.new(:target => $stdout, :indent => 4)

geocoder = "http://maps.google.com/maps/geo?q="
output = "&output=csv"
apikey = "&key=### insert your googlemaps token here ###"

counter = 0
addrs.each do |addr|
request = geocoder + addr + output + apikey
sleep 2.0
url = URI.escape(request)
resp = Net::HTTP.get_response(URI.parse(url))
fields = resp.body.split(',')
placemarks[placemarkbase + counter.to_s] = [addr,fields[3],fields[2]]
counter += 1
end

kml = { 'xmlns' => 'http://earth.google.com/kml/2.2'}
xml.instruct! :xml, :version => "1.1", :encoding => "US-ASCII"
kml.each do |key,value|
xml.kml(:xmlns => value) do
xml.Document do
placemarks.each do |key, array|
xml.Placemark do
xml.name(array[0])
xml.address(array[0])
xml.description(placemarkbase)
xml.Point do
str = array[1].to_s + "," + array[2].to_s + "," + 0.to_s
xml.coordinates(str)
end
end
end
end
end
end

No comments: