Python 两行代码实现shapefile和geojson的相互转化

geopandas是建立在geos, gdal, proj等开源地理空间计算相关框架之上的,旨在简化地理空间数据处理的高效工具包。

使用geopandas可快速实现shapefile和geojson的相互转化:

import os
import geopandas as gpd


def geojson2shp(geojson_file, shp_file):
    """
    将geojson格式的文件转化为shapefile
    :param geojson_file: 需要转换的geojson文件名
    :param shp_file: 转换输出的shapefile文件名
    """

    if os.path.exists(shp_file):
        os.remove(shp_file)

    out_data = gpd.read_file(geojson_file)
    # if out_data.crs is None:
    #     out_data.crs = 'EPSG:4326'              # 无坐标的文件需要指定空间参考为4326(WGS84坐标)
    out_data.to_file(shp_file, driver='ESRI Shapefile', encoding='utf-8')
    # add_area_field(shp_file, area_thre=50)
    print("successfully convert geojson to shapefile")


def shp2geojson_gpd(shp_file, geojson_file):
    """
    将shapefile格式的文件转化为geojson
    :param shp_file: 需要转换的shapefile文件名,投影信息可以缺失,也可以指定
    :param geojson_file: 转换输出的geojson文件名
    """

    if os.path.exists(geojson_file):
        os.remove(geojson_file)

    out_data = gpd.read_file(shp_file)
    crs = out_data.crs
    # if crs is None:
    #     crs = 'EPSG:4326'      # 没有坐标的数据则赋坐标WGS 1984
    out_data = gpd.GeoSeries(out_data.geometry, crs=crs).simplify(tolerance=0.0002)
    out_data.to_file(geojson_file, driver='GeoJSON', encoding="utf-8")
    print("successfully convert shapefile to geojson")


if __name__ == "__main__":
    in_shp = '../confidence.shp'
    out_json = '../shp2json.geojson'
    # in_json = '../test/json.geojson'
    # out_shp = '../test/json2shp.shp'
    #
    shp2geojson_gpd(in_shp, out_json)
    # geojson2shp(in_json, out_shp)

实践表明:使用geopandas将shapefile转化为geojson时,只能保留数据的地理和坐标信息,不能保存属性信息,如需保存属性信息,可使用gdal进行转化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小李AI飞刀^_^

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值