shp2geojson.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # -*- coding: utf-8 -*-
  2. import sys
  3. import os
  4. import json
  5. try:
  6. import geopandas as gpd
  7. except ImportError:
  8. print("ERROR: geopandas not installed")
  9. sys.exit(1)
  10. def shp_to_geojson(shp_path, output_path):
  11. """
  12. SHP 转 GeoJSON(自动转换坐标系为 WGS84)
  13. """
  14. try:
  15. gdf = gpd.read_file(shp_path)
  16. if gdf.crs is None:
  17. print("WARNING: No CRS found in SHP file, assuming WGS84")
  18. gdf = gdf.set_crs("EPSG:4326", allow_override=True)
  19. elif gdf.crs != "EPSG:4326":
  20. gdf = gdf.to_crs(epsg=4326)
  21. gdf.to_file(output_path, driver="GeoJSON", encoding="utf-8")
  22. print(f"SUCCESS: Converted {shp_path} to {output_path}")
  23. return True
  24. except Exception as e:
  25. print(f"ERROR: {str(e)}")
  26. return False
  27. if __name__ == "__main__":
  28. if len(sys.argv) < 3:
  29. print("Usage: python shp2geojson.py <input.shp> <output.geojson>")
  30. sys.exit(1)
  31. shp_path = sys.argv[1]
  32. output_path = sys.argv[2]
  33. if not os.path.exists(shp_path):
  34. print(f"ERROR: SHP file not found: {shp_path}")
  35. sys.exit(1)
  36. success = shp_to_geojson(shp_path, output_path)
  37. sys.exit(0 if success else 1)