Created
October 16, 2016 20:53
-
-
Save ityonemo/91be91d7559038e07e2c96cae41898e3 to your computer and use it in GitHub Desktop.
queries google maps to tabulate driving distances.
This file contains hidden or 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
| #drivingtaxes.jl | |
| using JSON | |
| #make sure we have what we're looking for. | |
| (length(ARGS) == 0) && throw(ErrorException("needs a file name")) | |
| ################################### | |
| #rows iterator | |
| type rows; tgt::Matrix; end | |
| Base.start(r::rows) = 1 | |
| Base.next(r::rows, idx) = (r.tgt[idx, :], idx + 1) | |
| Base.done(r::rows, idx) = idx > size(r.tgt, 1) | |
| Base.length(r::rows) = size(r.tgt,1) | |
| ################################### | |
| api_key = #insert API KEY HERE | |
| #set up a dictionary of locations. | |
| location_dict = Dict{Symbol, String}() | |
| known_distances = Dict{Tuple{Symbol, Symbol}, Float64}() | |
| addresses = readcsv("Addresses.csv") | |
| for row in rows(addresses) | |
| location_dict[Symbol(row[1])] = row[2] | |
| end | |
| function api_lookup(strt_loc, dest_loc) | |
| strt_addr = replace(location_dict[strt_loc],r"\s","+") | |
| dest_addr = replace(location_dict[dest_loc],r"\s","+") | |
| query = string("https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=",strt_addr,"&destinations=",dest_addr,"&key=",api_key) | |
| cr = readstring(`curl $query`) | |
| j = JSON.parse(cr) | |
| try | |
| Float64(parse(split(j["rows"][1]["elements"][1]["distance"]["text"])[1])) | |
| catch | |
| return -1.0 | |
| end | |
| end | |
| function lookup_distance(strt_loc, dest_loc) | |
| if haskey(known_distances, (strt_loc, dest_loc)) | |
| known_distances[(strt_loc, dest_loc)] | |
| else | |
| #actually do API stuff here. | |
| distance = api_lookup(strt_loc, dest_loc) | |
| #distance = 1.0 | |
| known_distances[(strt_loc, dest_loc)] = distance | |
| end | |
| end | |
| list_filename = ARGS[1] | |
| listtbl = readcsv(list_filename) | |
| output_tbl = Array{Any, 2}() | |
| for row in rows(listtbl[:,1:3]) | |
| if row[1] == "Date" | |
| output_tbl = hcat(row', "") | |
| else | |
| strt_loc = Symbol(row[2]) | |
| dest_loc = Symbol(row[3]) | |
| haskey(location_dict, strt_loc) || throw(ErrorException("key for $strt_loc not found")) | |
| haskey(location_dict, dest_loc) || throw(ErrorException("key for $dest_loc not found")) | |
| #first check to see if the distance exists. | |
| output_tbl = vcat(output_tbl, hcat(row', lookup_distance(strt_loc, dest_loc))) | |
| end | |
| end | |
| writecsv(string("final_", list_filename), output_tbl) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment