Saturday, 12 October 2013

Simple Python script to write a list of coordinates to a .geojson file

This has probably been done better elsewhere, but here's a really simple way to write a geojson file programmatically to display a set of coordinates, without having to bother learning the syntax of yet another python library. Geojson is a cool little format, open source and really easy.

Below, arrays x and y are decimal longitude and latitude respectively. The code would have to be modified to include a description for each coordinate, which could be included easily on line 15 if in the form of an iterable list.


f = open('points.geojson', 'w')
f.write('\n')
f.write('{\n')
f.write(' "type": "FeatureCollection",\n')
f.write(' "features": [\n')
for k in range(len(x)):
f.write('\n')
f.write(' {\n')
f.write(' "type": "Feature",\n')
f.write(' "geometry": {\n')
f.write(' "type": "Point",\n')
f.write(' "coordinates": ['+str(y[k])+', '+str(x[k])+']\n')
f.write(' },\n')
f.write(' "properties": {\n')
f.write(' "'+str(k)+'": "description here"\n')
f.write(' }\n')
if k==len(x)-1:
f.write(' }\n')
else:
f.write(' },\n')
f.write('\n')
f.write('\n')
f.write(' ]\n')
f.write('}\n')
f.close()
view raw xy2geojson.py hosted with ❤ by GitHub

No comments: