stimmenfryslan/stimmen/shapefile.py

44 lines
1.3 KiB
Python

from osgeo.osr import SpatialReference, CoordinateTransformation
import shapefile
epsg28992 = SpatialReference()
epsg28992.ImportFromEPSG(28992)
epsg28992.SetTOWGS84(565.237 ,50.0087 ,465.658 ,-0.406857 ,0.350733 ,-1.87035 ,4.0812)
epsg4326 = SpatialReference()
epsg4326.ImportFromEPSG(4326)
rd2latlon = CoordinateTransformation(epsg28992, epsg4326)
def rd_to_longlat(rd_multipolygon):
if len(rd_multipolygon) == 2 and tuple(map(type, rd_multipolygon)) == (float, float):
return list(rd2latlon.TransformPoint(*rd_multipolygon)[:2])
return [
rd_to_longlat(element)
for element in rd_multipolygon
]
def shapefiles_to_geojson(filename):
shape_file = shapefile.Reader(filename)
fields = shape_file.fields[1:]
field_names = [field[0] for field in fields]
buffer = []
for shape_record in shape_file.shapeRecords():
properties = dict(zip(field_names, shape_record.record))
geometry = shape_record.shape.__geo_interface__
geometry['coordinates'] = rd_to_longlat(geometry['coordinates'])
buffer.append({
'type': "Feature",
'geometry': geometry,
'properties': properties
})
return {
"type": "FeatureCollection",
"features": buffer
}