-
-
Save ashnair1/538fb09feae23a253989ce4f13fb945d to your computer and use it in GitHub Desktop.
Merge two or more geojson files.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from json import load, dump | |
from argparse import ArgumentParser | |
from re import compile | |
import sys | |
import os | |
parser = ArgumentParser(description="Group (merge) multiple GeoJSON files.") | |
defaults = dict(outfile=sys.stdout) | |
parser.set_defaults(**defaults) | |
parser.add_argument('-i', '--files', help='Files to be merged') | |
parser.add_argument('-o', '--outfile', dest='outfile', help='Outfile') | |
if __name__ == '__main__': | |
args = parser.parse_args() | |
infiles = os.listdir(args.files) | |
outfile = args.outfile | |
outjson = dict(type='FeatureCollection', features=[]) | |
for infile in infiles: | |
jfile = os.path.join(args.files, infile) | |
with open(jfile) as f: | |
injson = load(f) | |
if injson.get('type', None) != 'FeatureCollection': | |
raise Exception('Sorry, "%s" does not look like GeoJSON' % infile) | |
if type(injson.get('features', None)) != list: | |
raise Exception('Sorry, "%s" does not look like GeoJSON' % infile) | |
try: | |
outjson['features'] += injson['features'] | |
if 'crs' in injson.keys(): | |
outjson['crs'] = injson['crs'] | |
except: | |
outjson['features'] += injson | |
with open(outfile, 'w') as wj: | |
dump(outjson, wj) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment