Skip to content

Commit

Permalink
Adding native parsers between geojson and shapefiles
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel-M committed Feb 20, 2018
1 parent ebc4d08 commit 4244251
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
2 changes: 2 additions & 0 deletions gis_utils/in_parsers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from .geojson_to_shp import geojson_to_shp
from .shp_to_geojson import shp_to_geojson
30 changes: 30 additions & 0 deletions gis_utils/in_parsers/geojson_to_shp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import os
import geojson
import shapefile
import multiprocessing as mp

def geojson_to_shp(geojson_file_name,shp_file_name=None):
"""
Converts a geojson file into a shapefile. This is a serial process
"""
if shp_file_name == None:
shp_file_name = geojson_file_name.split(os.path.sep)[-1].split(".")[0]

# Open the GeoJSON and load it to memory
geoj = geojson.load(open(geojson_file_name,"r"))

w = shapefile.Writer()

# Get the number of features
features = len(geoj["features"])

i = 0
while i < features:
# Paranoid to prevent exceptions u
try:
w.shape(geoj[i]["geometry"])
except:
break
i += 1

w.save('test.shp')
39 changes: 39 additions & 0 deletions gis_utils/in_parsers/shp_to_geojson.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import os
import json
import shapefile
import multiprocessing as mp

def FeatureCollection(features):
"""
FeatureCollection creates a `FeatureCollection` with the
features in `features`
"""
return {"type": "FeatureCollection","features": features}
# return {"type": "FeatureCollection","properties":{"features": len(features)},"features": features}


def Feature(iterator):
"""
Generates a feature provided the iterator `iterator` that
implements the __geo__interface__
"""
return {"type":"Feature", "geometry":iterator.__geo_interface__}


def shp_to_geojson(shp_file_name,geojson_file_name=None):
"""
Converts a shp file into a geojson file. This
uses multiprocessing to critically accelerate the process.
"""
# If no geojson_file_name is passed, use the shp_file_name without extension
if geojson_file_name == None:
geojson_file_name = shp_file_name.split(os.path.sep)[-1].split(".")[0]

shpfile = shapefile.Reader(shp_file_name)

pool = mp.Pool()
features = pool.map(Feature,shpfile.iterShapes())

f = open(geojson_file_name,"w")
f.write(json.dumps(FeatureCollection(features),indent=2))
f.close()

0 comments on commit 4244251

Please sign in to comment.