Skip to content

Instantly share code, notes, and snippets.

@ms8r
Last active February 4, 2017 22:21
Show Gist options
  • Save ms8r/80b5a24665cd3ce11c08cef57b67a0cc to your computer and use it in GitHub Desktop.
Save ms8r/80b5a24665cd3ce11c08cef57b67a0cc to your computer and use it in GitHub Desktop.
Uses Google Distance Matric API to get distances (in meters) between an airport and a list of lat/lon values. Writes to stdout.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import fileinput
from itertools import groupby
import json
from tablib import Dataset
import googlemaps
import begin
def chunks(data, chunk_size):
"""Generator that yields ``chunk_size`` long lists from ``data``, an
iterable"""
for _, item in groupby(enumerate(data), lambda k: k[0] // chunk_size):
yield [x for _, x in item]
def dm_to_dist(out):
"""Generator extracting distances from result returned by Distance Matrix
API"""
for item in out['rows'][0]['elements']:
try:
dist = item['distance']['value']
except KeyError:
dist = item['status']
yield dist
@begin.start(auto_convert=True, short_args=False)
def main(apikey: """Google API key""",
airport: """3 letter airport code""",
keycol: """heading label for key column in `infile`""",
infile: """tabular input data that includes key, lat and lon as
signed decimals""" = '-',
latcol: """heading label of latitude column in `infile`""" =
'latitude',
loncol: """heading label of longitude column in `infile`""" =
'longitude',
reqsize: """number of lat/lon pairs to be submitted per request (max.
25)""" = 25,
delay: """optional delay in seconds between api requests""" = 0.0):
"""
Uses Google Distance Matrix API to get distances (in meters) between an
airport and a list of lat/lon values. Writes to stdout.
"""
gmaps = googlemaps.Client(key=apikey)
with fileinput.input((infile)) as fp:
locations = Dataset(headers=next(fp).split())
for line in fp:
locations.append(line.split())
keys = locations[keycol]
latlons = ((float(lat), float(lon)) for lat, lon in
zip(locations[latcol], locations[loncol]))
print('{0}\t{1}'.format(keycol, airport))
for key_chunk, ll_chunk in zip(chunks(keys, reqsize), chunks(latlons,
reqsize)):
out = gmaps.distance_matrix(['{0} airport'.format(airport)], ll_chunk,
mode='driving', units='metric')
for key, dist in zip(key_chunk, dm_to_dist(out)):
print('{0}\t{1}'.format(key, dist))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment