icleversoft
9/2/2013 - 7:30 AM

Get Map Location for a given address by making use of Ggl's geocoding web service

Get Map Location for a given address by making use of Ggl's geocoding web service

require 'open-uri'
require 'json'
require 'ostruct'

def get_lat_lon( address, times = 0 )
  url = "http://maps.google.com/maps/api/geocode/json?address=#{URI.escape(address)}&sensor=false"
  #puts "Requesting: #{url}"
	page = open(url).readlines.to_s
	document = JSON.parse( page )
	results = document["results"]
  o = nil
  if results && results.size > 0
    o = []
    results.each do |a|
      o << OpenStruct.new(a)
    end
    if o.size > 1 && times == 0
      puts "Found #{o.size} addresses!"
      puts "Requesting again address #{o[0].formatted_address}..."
      o = get_lat_lon(o[0].formatted_address, 1)
    end
  end
  o
end

w = File.open('out.csv', 'a+')
f = File.open('LibInfo1.csv').readlines.collect{|i| i.strip}
f.each_with_index do |x, i|
	next if i == 0
	parts = x.split(';')
	p "Getting address for :#{parts[0]}"
	address = [parts[1], parts[2]].join(' ')
	o = get_lat_lon( address )
	if o && o.size > 0
	  puts "Found #{o.size} addresses!"
    puts "LAT:#{o[0].geometry["location"]["lat"].to_f}"
    puts "LON:#{o[0].geometry["location"]["lng"].to_f}"
    parts << o[0].geometry["location"]["lat"]
    parts << o[0].geometry["location"]["lng"]
    parts = parts.join(';')
	  sleep 1
  end
  w.write("#{parts}\n")
end

#o = get_lat_lon( modified_address )
#puts "Found #{o.size} addresses!"
#puts "LAT:#{o[0].geometry["location"]["lat"].to_f}"
#puts "LON:#{o[0].geometry["location"]["lng"].to_f}"