hub/crs_conversion.py

40 lines
1.2 KiB
Python

import geopandas as gpd
from shapely.geometry import Polygon, MultiPolygon
from shapely.geometry.polygon import orient
# Path to the input GeoJSON file
input_file = 'data/cmm_test.geojson'
# Path to the output GeoJSON file
output_file = 'data/cmm_test_corrected.geojson'
# Read the GeoJSON file
gdf = gpd.read_file(input_file)
# Set the CRS to EPSG:3857 if not already set
if gdf.crs is None:
gdf.set_crs(epsg=3857, inplace=True)
# Convert the CRS to EPSG:4326 (longitude and latitude)
gdf = gdf.to_crs(epsg=4326)
# Function to reorient geometries to follow the right-hand rule
def reorient_geometry(geom):
if geom.is_empty:
return geom
elif geom.geom_type == 'Polygon':
return orient(geom, sign=1.0)
elif geom.geom_type == 'MultiPolygon':
reoriented_polygons = [orient(polygon, sign=1.0) for polygon in geom.geoms]
return MultiPolygon(reoriented_polygons)
else:
return geom
# Apply the reorientation to the geometry column
gdf['geometry'] = gdf['geometry'].apply(reorient_geometry)
# Save the transformed GeoDataFrame to a new GeoJSON file
gdf.to_file(output_file, driver='GeoJSON')
print(f"Converted GeoJSON with right-hand rule orientation has been saved to {output_file}")