Python?shapefile轉GeoJson的2種方式實例
GeoJson的簡要介紹
GeoJson是用json的語法表達和存儲地理數(shù)據(jù),可以說是json的子集。
GeoJson以鍵值對的形式保存原有對象的信息,具有輕量化、易解析等優(yōu)點。
GeoJson包括的地理要素有Point(點)、 MultiPoint(多點)、 LineString(線)、MultiLineString(多線)、 Polygon(面)、 MultiPolygon(多面)、 GeometryCollection(幾何集合)
這些地理要素包括在geometry的type屬性中,并且不同的type具有不同的coordinates值。更多的GeoJson相關內(nèi)容可參考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轉換的時候兩行核心代碼即可搞定,簡單粗暴。但是在實踐過程中發(fā)現(xiàn),采用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)
# 創(chuàng)建結果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內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python中tkinter+MySQL實現(xiàn)增刪改查
這篇文章主要介紹了Python中tkinter+MySQL實現(xiàn)增刪改查,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-04-04
用python的turtle模塊實現(xiàn)給女票畫個小心心
今天小編就為大家分享一篇用python的turtle模塊實現(xiàn)給女票畫個小心心,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
深入探討Python中的內(nèi)置類屬性`__repr__`
在Python中,__repr__是一個特殊的內(nèi)置類屬性,用于定義類的字符串表示形式,本文將深入探討__repr__的作用、用法以及一些實際應用場景,希望對大家有所幫助2023-12-12

