Create a gist now

Instantly share code, notes, and snippets.

Gets the walking distance between two points and logs to file
# this script gets the addresses pairs from a csv file and queries the google maps api for walking directions
#
# require csv
require 'uri'
require 'csv'
require 'nokogiri'
require 'net/https'
require 'open-uri'
# initialize arrays
pairs = Array.new
urls = Array.new
data = Array.new
# api keys
# insert your google developer api key here
googleKey = ''
CSV.foreach('files/pairs.txt', { :col_sep => "\t" }) do |row|
pairs.push(row)
end
pairs.each {
|x|
urls.push(x.to_s.sub('", "','&destination=').sub('["','?origin=').sub('"]',""))
}
urls.each do |x|
url = URI.encode("https://maps.googleapis.com/maps/api/directions/xml#{x}&sensor=false&mode=walking&key=#{googleKey}")
puts "Querying #{url} \n"
xml = open(url).read
doc = Nokogiri::XML(xml)
durationTotal = doc.css("DirectionsResponse route leg duration value").last.content
durationMinutes = durationTotal.to_i / 60
puts "Walk duration is #{durationTotal} seconds (#{durationMinutes} minutes). \n.....\n\n"
data.push(durationTotal.to_i)
end
puts "\n\n===== WRITING DATA =====\n\n"
File.open("gotTimes.txt", 'w') { |f| f.write(data) }
puts "Done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment