-
-
Save Hendrikv1990/8a0c529b2967dc1179ff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'csv' | |
require 'httparty' | |
require 'json' | |
header = File.open('input.tsv', &:readline) # get header from input file | |
header = header.to_s.gsub("\n","") # remove newline characters | |
header << "\t\t\tlatitude\t\t\tlongitude\n" # format header | |
File.open("output.tsv", 'w') {|file| file.write(header) } # create output file and append header | |
base_url = "http://maps.googleapis.com/maps/api/geocode/json?address=" | |
CSV.foreach("input.tsv", :headers => true, :col_sep => "\t", :encoding => 'windows-1251:utf-8') do |row| | |
url = base_url | |
# each row contains 5 arrays which contain a column name and the corresponding attribute from the row that is in that column | |
# [street_address, street_address_from_row] [unit, unit_from row] [city, city_from_row] [stat, state_from_row] [zip, zip_from_row] | |
row.each do |address_element_array| | |
address_element = address_element_array[1] # 0th element in array is the header information, 1st element is value of interest | |
if address_element != nil # make sure address element isn't nil (skips header) | |
address_element = address_element.split(' ').join('+') # replace spaces with '+' for URL | |
url += "+" + address_element # build the URL | |
end | |
end | |
url += "&sensor=false" # ending required by Geocode API | |
response = HTTParty.get(url) | |
json = JSON.parse(response.body) | |
if json['results'].length == 0 # define lat and lng if no results | |
lat = "" | |
lng = "" | |
else | |
# the parsed json is a hash that contains an array that contains nested hashes | |
lat = json['results'][0]['geometry']['location']['lat'].to_s | |
lng = json['results'][0]['geometry']['location']['lng'].to_s | |
end | |
row = row.to_s.gsub(",","\t").gsub("\n","") # format output file | |
row << lat + "\t\t\t" + lng + "\n" # append latitude and longitude to row | |
File.open("output.tsv", 'a') do |file| | |
file.write(row) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment