Skip to content

Instantly share code, notes, and snippets.

@urschrei
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save urschrei/ccb8365b46a0ea349cab to your computer and use it in GitHub Desktop.
Save urschrei/ccb8365b46a0ea349cab to your computer and use it in GitHub Desktop.
Output a GeoJSON FeatureCollection to file from dict point data input
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
output geojson.py
Created by Stephan Hügel on 2015-02-26
I can *never* remember how to efficiently do this, so I'm making a gist.
This should be easily adaptable to use with LineStrings, Polygons etc by
altering the 'geometry' dict accordingly
"""
import json
def make_feature(lon, lat, **kwargs):
"""Create a Point and convert it into a dict suitable for GeoJSON output"""
return {
'type': 'feature',
'properties': {
'name': kwargs.get('location_name') or ""},
'geometry': {
'coordinates': (float(lon), float(lat)), 'type': 'Point'},
'description': kwargs.get('description') or ""
}
def make_collection(features):
"""Return a FeatureCollection dict"""
return {
"type": "FeatureCollection",
"features": [
make_feature(
f['lon'],
f['lat'],
)
for f in features],
"crs": {
"type": "name",
"properties": {
"name": "urn:ogc:def:crs:OGC:1.3:CRS84" }
}
}
def write_geojson(fname, coll):
"""Dump GeoJSON FeatureCollection to file"""
with open(fname, 'w') as f:
f.write(json.dumps(coll, indent=4, separators=(',', ': ')))
# totally made up example collection of point dicts from somewhere
things = [{'lon': '0.0', 'lat': '0.1'}, {'lon': '0.1', 'lat': '0.2'}]
write_geojson('test.geojson', make_collection(things))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment