Skip to content

Instantly share code, notes, and snippets.

@mittenchops
Last active April 9, 2019 06:13
Show Gist options
  • Save mittenchops/6450712 to your computer and use it in GitHub Desktop.
Save mittenchops/6450712 to your computer and use it in GitHub Desktop.
Loading shapefiles into mongodb. This all actually comes from here: http://geospatialpython.com/ But this is wrapped up a little nicer.
# http://geospatialpython.com/
import json, pymongo, shapefile
from json import dumps
database = 'geo'
connection = pymongo.MongoClient()
db = getattr(connection,database)
def renamesh2json(x):
d = x.split(".")
d.pop(-1)
y = ''.join(d)+".json"
return(y)
def sh2json(filename):
reader = shapefile.Reader(filename)
fields = reader.fields[1:]
field_names = [field[0] for field in fields]
buffer = []
for sr in reader.shapeRecords():
atr = dict(zip(field_names, sr.record))
geom = sr.shape.__geo_interface__
buffer.append(dict(type="Feature", geometry=geom, properties=atr))
newfilename = renamesh2json(filename)
geojson = open(newfilename, "w")
geojson.write(dumps({"type": "FeatureCollection",\
"features": buffer}, indent=2) + "\n")
geojson.close()
print("write of {} successful".format(newfilename))
return(newfilename)
def loader(shapefile, collection):
jf = open(shapefile)
data = json.load(jf)
for d in data['features']:
db[collection].insert(d)
print("Upload of shapefile: {} into collection: {} successful".format(shapefile, collection))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment