Skip to content

Instantly share code, notes, and snippets.

@crccheck
Created December 10, 2014 04:00
Show Gist options
  • Save crccheck/cdd007a7374310d3ba9d to your computer and use it in GitHub Desktop.
Save crccheck/cdd007a7374310d3ba9d to your computer and use it in GitHub Desktop.
geocode and geojson
#!/usr/bin/env python3
"""
Usage: ./2geojson.py [<yaml_file> | <address>]
Requirements:
pip3 install PyYAML geopy
"""
import json
import os
import sys
from geopy import geocoders
import yaml
def format_geojson_from_docs(docs):
out = {
'type': 'FeatureCollections',
'features': []
}
for doc in docs:
data = doc.copy() # don't modify original for some reason
coordinates = data.pop('coordinates')
out['features'].append({
'type': 'Feature',
'properties': data,
'geometry': {
'type': 'Point',
'coordinates': coordinates.split(', ')[::-1],
},
})
return out
def geojsonize(path):
with open(path) as fp:
docs = yaml.load_all(fp)
# filter and load into memory so the file can be closed
docs = [x for x in docs if 'coordinates' in x]
data = format_geojson_from_docs(docs)
print(json.dumps(data))
def geocode(address):
geolocator = geocoders.Nominatim()
location = geolocator.geocode(address)
print(location.address)
print('{}, {}'.format(location.latitude, location.longitude))
if __name__ == '__main__':
if len(sys.argv) < 2:
print(__doc__)
sys.exit(1)
path = sys.argv[1]
if os.path.exists(path):
geojsonize(path)
else:
geocode(path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment