Python shapefile转GeoJson的2种方式实例

geojson是地图可视化系统中最常用的地理数据格式,几乎所有主流地图可视化库或框架都支持geojson数据的加载,下面这篇文章主要给大家介绍了关于Python shapefile转GeoJson的2种方式的相关资料,需要的朋友可以参考下

GeoJson的简要介绍

GeoJson是用json的语法表达和存储地理数据,可以说是json的子集。

GeoJson以键值对的形式保存原有对象的信息,具有轻量化、易解析等优点。

GeoJson包括的地理要素有Point(点)、 MultiPoint(多点)、 LineString(线)、MultiLineString(多线)、 Polygon(面)、 MultiPolygon(多面)、 GeometryCollection(几何集合)

这些地理要素包括在geometry的type属性中,并且不同的type具有不同的coordinates值。更多的GeoJson相关内容可参考RFC7946标准。

     { "type": "MultiPoint", "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] } { "type": "MultiPolygon", "coordinates": [ [ [ [102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0] ] ], [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ], [ [100.2, 0.2], [100.2, 0.8], [100.8, 0.8], [100.8, 0.2], [100.2, 0.2] ] ] ] }

两种将shapefile文件转换为GeoJson的方式

1. 使用geopandas

核心代码:geopandas.GeoSeries 和out_data.to_file

import geopandas as gpd 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 out_data = gpd.GeoSeries(out_data.geometry, crs=crs) out_data.to_file(geojson_file, driver='GeoJSON', encoding="utf-8") print("successfully convert shapefile to geojson")

使用geopandas转换的时候两行核心代码即可搞定,简单粗暴。但是在实践过程中发现,采用geopandas转换后的GeoJson文件并没有保留shapefile中的属性properities信息,如area, name等,如下图所示:

2. 使用gdal

import gdal import ogr import os def shp2geojson_gdal(shp_file, geojson_file): gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES") gdal.SetConfigOption("SHAPE_ENCODING", "GBK") src_ds = ogr.Open(shp_file) src_layer = src_ds.GetLayer(0) # 创建结果Geojson baseName = os.path.basename(geojson_file) dst_driver = ogr.GetDriverByName('GeoJSON') dst_ds = dst_driver.CreateDataSource(geojson_file) if dst_ds.GetLayer(baseName): dst_ds.DeleteLayer(baseName) dst_layer = dst_ds.CreateLayer(baseName, src_layer.GetSpatialRef()) dst_layer.CreateFields(src_layer.schema) dst_feat = ogr.Feature(dst_layer.GetLayerDefn()) # 生成结果文件 for feature in src_layer: dst_feat.SetGeometry(feature.geometry()) for j in range(feature.GetFieldCount()): dst_feat.SetField(j, feature.GetField(j)) dst_layer.CreateFeature(dst_feat) del dst_ds del src_ds print("successfully convert shapefile to geojson")

结果包含原始shapefile文件中的属性信息:

总结

到此这篇关于Python shapefile转GeoJson的2种方式的文章就介绍到这了,更多相关Python shapefile转GeoJson内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!

以上就是Python shapefile转GeoJson的2种方式实例的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » python