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进行转化。