| 123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- # -*- coding: utf-8 -*-
- import sys
- import os
- import json
- try:
- import geopandas as gpd
- except ImportError:
- print("ERROR: geopandas not installed")
- sys.exit(1)
- def shp_to_geojson(shp_path, output_path):
- """
- SHP 转 GeoJSON(自动转换坐标系为 WGS84)
- """
- try:
- gdf = gpd.read_file(shp_path)
-
- if gdf.crs is None:
- print("WARNING: No CRS found in SHP file, assuming WGS84")
- gdf = gdf.set_crs("EPSG:4326", allow_override=True)
- elif gdf.crs != "EPSG:4326":
- gdf = gdf.to_crs(epsg=4326)
-
- gdf.to_file(output_path, driver="GeoJSON", encoding="utf-8")
- print(f"SUCCESS: Converted {shp_path} to {output_path}")
- return True
- except Exception as e:
- print(f"ERROR: {str(e)}")
- return False
- if __name__ == "__main__":
- if len(sys.argv) < 3:
- print("Usage: python shp2geojson.py <input.shp> <output.geojson>")
- sys.exit(1)
-
- shp_path = sys.argv[1]
- output_path = sys.argv[2]
-
- if not os.path.exists(shp_path):
- print(f"ERROR: SHP file not found: {shp_path}")
- sys.exit(1)
-
- success = shp_to_geojson(shp_path, output_path)
- sys.exit(0 if success else 1)
|