the-villages-import/shp-to-geojson.py

75 lines
2.0 KiB
Python

import geopandas
import sys
import os
from pathlib import Path
def convert_shapefile_to_geojson(
input_shapefile,
output_geojson,
target_crs=4326 # Convert to WGS 84
):
"""
Main conversion function
Args:
input_shapefile: Path to input shapefile
output_geojson: Path to output GeoJSON file
target_crs: Target coordinate reference system
"""
try:
# Read shapefile
print(f"Reading shapefile: {input_shapefile}")
df = geopandas.read_file(input_shapefile)
print(f"Converting to CRS {target_crs}")
df = df.to_crs(target_crs)
exploded = df.explode()
exploded.to_file(output_geojson, driver='GeoJSON')
except Exception as e:
print(f"Error during conversion: {str(e)}")
sys.exit(1)
def main():
"""
Main function to handle command line arguments
"""
import argparse
parser = argparse.ArgumentParser(
description='Convert shapefile to GeoJSON'
)
parser.add_argument(
'input_shapefile',
help='Path to input shapefile'
)
parser.add_argument(
'output_geojson',
help='Path to output GeoJSON file'
)
parser.add_argument(
'--target-crs',
default='4326',
help='Target coordinate reference system (default: 4326)'
)
args = parser.parse_args()
# Validate input file
if not os.path.exists(args.input_shapefile):
print(f"Error: Input shapefile '{args.input_shapefile}' not found")
sys.exit(1)
# Create output directory if it doesn't exist
output_dir = Path(args.output_geojson).parent
output_dir.mkdir(parents=True, exist_ok=True)
# Run conversion
convert_shapefile_to_geojson(
args.input_shapefile,
args.output_geojson,
args.target_crs
)
if __name__ == "__main__":
import pandas as pd
main()