Skip to content

Instantly share code, notes, and snippets.

@jkrumbiegel
Created January 31, 2020 17:34
Show Gist options
  • Save jkrumbiegel/e9d2898c378b11a883995caf53248241 to your computer and use it in GitHub Desktop.
Save jkrumbiegel/e9d2898c378b11a883995caf53248241 to your computer and use it in GitHub Desktop.
get a grid of distances and durations between one location and a grid of locations
using HTTP
using Dates
using Printf
using JSON
using DataFrames
using CSV
hbf_location = "53.5527704,10.0065856"
function url_string(options)
join(
(string(key) * "=" * string(value) for (key, value) in zip(keys(options), options)),
"&"
)
end
base_url = "https://maps.googleapis.com/maps/api/distancematrix/json?"
function build_query_url(origins)
origins_string = join((@sprintf("%.5f", o[1]) * "," * @sprintf("%.5f", o[2]) for o in origins), "|")
options = (
origins = origins_string,
destinations = hbf_location,
units = "metric",
mode = "transit",
departure_time = string(Int(datetime2unix(DateTime("2020-01-31T08:00:00")))),
key = "YOUR API KEY HERE",
)
options_string = url_string(options)
base_url * options_string
end
function extract_result(json)
rows = json["rows"]
addresses = String.(json["origin_addresses"])
distances = [try r["elements"][1]["distance"]["value"]; catch err; NaN end for r in rows]
durations = [try r["elements"][1]["duration"]["value"]; catch err; NaN end for r in rows]
(address = addresses, distance = distances, duration = durations)
end
function run_coordinates(coordinates)
query_url = build_query_url(coordinates)
response = HTTP.get(query_url)
response_json = JSON.parse(String(response.body))
data = extract_result(response_json)
merged_data = merge((lat = first.(coordinates), long = last.(coordinates)), data)
end
function get_grid(coordinates)
data = []
nrows = size(coordinates, 1)
for irow in 1:nrows
println("Row $irow of $nrows")
subset_data = run_coordinates(coordinates[irow, :])
push!(data, subset_data)
end
data
end
topleft = (53.595626, 9.912976)
bottomright = (53.538850, 10.059478)
sidelength = 100
coordinates = [(x, y)
for x in LinRange(topleft[1], bottomright[1], sidelength),
y in LinRange(topleft[2], bottomright[2], sidelength)]
data_named_tuples = get_grid(coordinates)
data_df = vcat(DataFrame.(data_named_tuples)...)
CSV.write("/Users/juliuskrumbiegel/dev/julia/HamburgDistanceGrid/53.595626_9.912976-53.538850_10.059478_100x100.csv", data_df)
using Makie
using MakieLayout
using CSV
using DataFrames
using FileIO
data = CSV.read("/Users/juliuskrumbiegel/dev/julia/HamburgDistanceGrid/53.595626_9.912976-53.538850_10.059478_100x100.csv")
googlemap = load("/Users/juliuskrumbiegel/dev/julia/HamburgDistanceGrid/googlemap.png")
lat_range = [53.595626, 53.538850]
long_range = [9.912976, 10.059478]
minutesgrid = reshape(data.duration ./ 60, 100, 100)
minutesgrid[minutesgrid .> 45] .= NaN
latitudes = reshape(data.lat, 100, 100)
longitudes = reshape(data.long, 100, 100)
function rect2rect(r1, r2, p)
frac = (p .- r1.origin) ./ r1.widths
frac .* r2.widths .+ r2.origin
end
##
scene, layout = layoutscene()
ax1 = layout[1, 1] = LAxis(scene, aspect = DataAspect())
ax2 = layout[2, 1] = LAxis(scene, aspect = DataAspect())
hidexdecorations!.([ax1, ax2])
hideydecorations!.([ax1, ax2])
linkaxes!(ax1, ax2)
tightlimits!(ax1)
tightlimits!(ax2)
hm = heatmap!(ax1, long_range, lat_range, reverse(minutesgrid, dims=2), colormap = :rainbow)
im = image!(ax2, long_range, lat_range, rotr90(googlemap))
contour!(ax1, LinRange(long_range..., 100), LinRange(lat_range..., 100), minutesgrid, linewidth = 4, colormap = :rainbow)
contour!(ax2, LinRange(long_range..., 100), LinRange(lat_range..., 100), minutesgrid, linewidth = 4, colormap = :rainbow)
scatpos = Node([Point2f0(0, 0)])
scatter!(ax1, scatpos, xautolimits = false, yautolimits = false, color = :red, markersize = 10px)
scatter!(ax2, scatpos, xautolimits = false, yautolimits = false, color = :red, markersize = 10px)
on(events(ax2.scene).mouseposition) do pos
scatpos[] = [rect2rect(ax2.scene.px_area[], ax2.limits[], pos)]
end
cb = layout[1:2, 2] = LColorbar(scene, hm, width = 30, label = "Minutes")
layout[0, :] = LText(scene, "Transit time to Hamburg main station", textsize = 50)
nothing
##
scene
##
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment