Skip to content

Instantly share code, notes, and snippets.

Last active September 19, 2015 02:09
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
find all "coordinates" field in a geojson file, and output x,y coordinates as csv
# -*- coding: utf-8 -*-
# 「臺灣各級行政區域(縣市/鄉鎮/村里)邊界座標檔, 自選解析度、 存成 csv、 畫成 svg 」
import json, argparse, sys, math, warnings
def ispoint(coords):
return isinstance(coords, list) and isinstance(coords[0], (int, long, float)) and len(coords)==2
def coords2csv(coords):
if ispoint(coords[0]):
for p in coords:
print '{0:f}{1:s}{2:f}'.format(p[0], args.delimiter, p[1])
map(coords2csv, coords)
def geojson2csv(gjdata):
if isinstance(gjdata, dict):
if gjdata['type'] == 'FeatureCollection':
map(geojson2csv, gjdata['features'])
elif gjdata['type'] == 'Feature':
if 'geometry' in gjdata and isinstance(gjdata['geometry'],dict) and 'coordinates' in gjdata['geometry'] and isinstance(gjdata['geometry']['coordinates'],list) and len(gjdata['geometry']['coordinates'])>0:
warnings.warn('ignoring "' + gjdata['type'] + '"')
return gjdata
elif isinstance(gjdata, list):
return map(geojson2csv, gjdata)
parser = argparse.ArgumentParser(description='find all "coordinates" field in a geojson file, and output x,y coordinates as csv',formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-d', '--delimiter', type=str,
default=',', help='delimiter character between fields')
parser.add_argument('gjf', nargs='*', default='-', help='path to geojson files')
args = parser.parse_args()
for fn in args.gjf:
gjfile = sys.stdin if fn == '-' else open(fn)
gjdata = json.load(gjfile)
if gjfile is not sys.stdin:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment