Skip to content

Instantly share code, notes, and snippets.

@dandye
Created June 11, 2012 21:07
Show Gist options
  • Save dandye/2912707 to your computer and use it in GitHub Desktop.
Save dandye/2912707 to your computer and use it in GitHub Desktop.
SHP2GeoJSON
import os,sys
import glob
import json
#
import fiona
shps = glob.glob("./*/*.shp")
for shp in shps:
#head,tail = os.path.split(shp)
base,ext = os.path.splitext(shp)
outfile = "{}.json".format(base)
path = "./TIGER2011/{}".format(base[2:])
c = fiona.collection(shp,"r")
toc = {}
toc["name"] = "NewFeatureType"
toc["type"] = "FeatureCollection"
# "features" is the list that holds all of the features in the GeoJSON
features = []
west, south = c.bounds[0],c.bounds[1]
east, north = c.bounds[2],c.bounds[3]
# create a GeoJSON feature for the file
features.append(
{
"type":"Feature",
"geometry":{"type": "Polygon",
"coordinates":[[
[west,north], #UL X,Y c.bounds
[east,north], #UR X,Y
[east,south], #LR X,Y
[west,south], #LL X,Y
[west,north] #UL X,Y
]]},
"properties":{
"PATH": path,
"EXTS": 'shp;shx;dbf;prj', # be careful when hard-coding: case matters!
"WEO_MISCELLANEOUS_FILE":"No",
"WEO_TYPE":"WEO_FEATURE"
}
})
toc["features"] = features
base,ext = os.path.splitext(shp)
outfile = "{}.json".format(base)
print outfile
out = open(outfile, "w")
# create a JSON object
e = json.JSONEncoder()
out.write(e.encode(toc))
out.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment