A script that takes the path to a shapefile as a command line argument. This shapefile is then converted to a shapefile that has latitude and longitude as the projection.
- fiona
- shapely
- pyproj
| #!/usr/bin/env python | |
| import os | |
| import fiona | |
| import pyproj | |
| import argparse | |
| from functools import partial | |
| from shapely.ops import transform | |
| from shapely.geometry import shape, mapping | |
| if __name__ == "__main__": | |
| parser = argparse.ArgumentParser(description="Convert Projected Shapefile to Latitude/Longitude Shapefile.") | |
| parser.add_argument(dest='file', help="Path to shapefile to convert") | |
| parser.add_argument('-o', '--outfile', dest='outfile', help="Output Name") | |
| args = parser.parse_args() | |
| infile = args.file | |
| if args.outfile: | |
| outfile = args.outfile | |
| name, ext = os.path.splitext(outfile) | |
| if ext not in [".shp"]: | |
| outfile = "{:s}.{:s}".format(name, ext) | |
| else: | |
| name, ext = os.path.splitext(infile) | |
| outfile = "{:s}-{:s}.shp".format(name, "latlon") | |
| # with fiona.open() | |
| with fiona.open(infile, "r") as SHP: | |
| # Read Shapfile Information | |
| source_driver = SHP.driver | |
| source_crs = SHP.crs | |
| source_schema = SHP.schema | |
| # Set Up Projection Information | |
| latlon = pyproj.Proj(init="epsg:4326") | |
| shpproj = pyproj.Proj(source_crs) | |
| reproject = partial(pyproj.transform, shpproj, latlon) | |
| with fiona.open(outfile, "w", driver=source_driver, crs=latlon.srs, schema=source_schema) as W: | |
| for shp in SHP: | |
| geom = transform(reproject, shape(shp["geometry"])) | |
| W.write({"geometry": mapping(geom), "properties": shp["properties"]}) |