from osgeo import ogr, gdal
import os
import argparse

def shp_to_geojson(shp_path, geojson_path):
    # 设置编码选项
    gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
    gdal.SetConfigOption("SHAPE_ENCODING", "GBK")

    # 打开Shapefile
    src_ds = ogr.Open(shp_path)
    src_layer = src_ds.GetLayer(0)

    # 创建输出GeoJSON
    driver = ogr.GetDriverByName('GeoJSON')
    if os.path.exists(geojson_path):
        driver.DeleteDataSource(geojson_path)
    dst_ds = driver.CreateDataSource(geojson_path)
    dst_layer = dst_ds.CreateLayer('output', src_layer.GetSpatialRef())

    # 复制字段定义
    dst_layer.CreateFields(src_layer.schema)

    # 复制要素
    for feature in src_layer:
        dst_feature = ogr.Feature(dst_layer.GetLayerDefn())
        dst_feature.SetGeometry(feature.GetGeometryRef())
        for j in range(feature.GetFieldCount()):
            dst_feature.SetField(j, feature.GetField(j))
        dst_layer.CreateFeature(dst_feature)

    # 清理
    dst_ds = None
    src_ds = None
    print("转换完成")


# 使用示例
shp_to_geojson('input.shp', 'output.geojson')