Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Mersh.txt requirements file for pip
Fiona==0.8
Pyproj==1.9.0
Shapely==1.2.14
# Example of using Fiona, pyproj, and Shapely together. Install all of them like this:
#
# $ pip install -r https://gist.github.com/raw/1689767/34dedfd28546d41f8dbd7a08ccf2c8abf9ebdf6a/mersh.txt
import logging
import sys
from fiona import collection
from pyproj import Proj, transform
from shapely.geometry import mapping, shape
logging.basicConfig(stream=sys.stderr, level=logging.INFO)
with collection("docs/data/test_uk.shp", "r") as input:
schema = input.schema.copy()
p_in = Proj(input.crs)
with collection(
"with-pyproj-shapely.shp", "w", "ESRI Shapefile",
schema=schema,
crs={'init': "epsg:27700", 'no_defs': True}
) as output:
p_out = Proj(output.crs)
for f in input:
try:
# Transform the feature geometries.
assert f['geometry']['type'] == "Polygon"
new_coords = []
for ring in f['geometry']['coordinates']:
x2, y2 = transform(p_in, p_out, *zip(*ring))
new_coords.append(zip(x2, y2))
f['geometry']['coordinates'] = new_coords
# Ensure that they are valid and "clean".
geom = shape(f['geometry'])
if not geom.is_valid:
clean = geom.buffer(0.0)
assert clean.is_valid
assert clean.geom_type == 'Polygon'
geom = clean
f['geometry'] = mapping(geom)
output.write(f)
except Exception, e:
# Writing uncleanable features to a different shapefile
# is another option.
logging.exception(
"Error transforming or cleaning feature %s:", f['id'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.