效果好的徐州网站开发,域名查询入口,重庆网站建设公司模板,wordpress头像class前言 本次所利用的geojson数据来自https://geo.datav.aliyun.com/areas_v3/bound/410000_full.json
#xff0c;如果觉得下方代码看起来不方便#xff0c;可以来GitHub上来看#xff0c;在这上面还有一些辅助内容便于理解
GISpjd/GIS-union-Python (github.com)https://gi… 前言 本次所利用的geojson数据来自https://geo.datav.aliyun.com/areas_v3/bound/410000_full.json
如果觉得下方代码看起来不方便可以来GitHub上来看在这上面还有一些辅助内容便于理解
GISpjd/GIS-union-Python (github.com)https://github.com/GISpjd/GIS-union-Python 一.展示 二.环境 我是在Anaconda下的jupyter notebook完成代码的编写下面是我对应的版本号我建议大家在这个环境下编写因为在下载gdal等包的时候会更方便。 三.参考网站
osgeo.osr module — GDAL documentation
osgeo.ogr module — GDAL documentation 不过对应API像字典一样对新手不太友好可以结合网上博客和AI来学习而且随着时间的变化相应API可能也会变化发现实现不了的时候及时查阅。
对于ogr的矢量结构可以阅读OGR矢量结构 — headfirst gdal 0.1 documentation (headfirst-gdal.readthedocs.io) 四. 代码 from osgeo import ogr, osr, gdal
import requests
import json# 设置Shapefile的编码为UTF-8这有助于确保中文或其他非ASCII字符能够正确保存和显示。
gdal.SetConfigOption(SHAPE_ENCODING, UTF-8)# 获取geojson
url https://geo.datav.aliyun.com/areas_v3/bound/410000_full.json
geojson requests.get(url)
data json.loads(geojson.content)# 准备shp数据源
driver ogr.GetDriverByName(ESRI Shapefile)
shp_path rC:\python爬虫\henan.shp #换成自己想保存的位置
data_source driver.CreateDataSource(shp_path)# 定义坐标系
srs osr.SpatialReference()
srs.ImportFromEPSG(4326)# 创建坐标系
layer data_source.CreateLayer(province,srs,ogr.wkbMultiPolygon)feature_def layer.GetLayerDefn() #获取图层定义
properties data[features][0][properties]# 字段名重命名映射表
rename_map {adcode: adcode,name: name,center:center,childrenNum: childNum, # 将childrenNum简化为childNumlevel: level,parent: parent,subFeatureIndex: subIdx, # 将subFeatureIndex简化为subIdxacroutes:acroutes,geometry: geometry
}# 为图层创建字段基于GeoJSON数据的属性。
for prop_name in properties.keys():#dict.get(key,default)short_name rename_map.get(prop_name, prop_name[:10]) # 使用重命名映射表或截断过长的字段名。field ogr.FieldDefn(short_name,ogr.OFTString)# 创建新的字段定义。layer.CreateField(field)# 在图层中添加该字段。# 遍历GeoJSON数据中的每一个特征Feature将它们转换为Shapefile格式并添加到图层中。
for feature in data[features]:geom ogr.CreateGeometryFromJson(json.dumps(feature[geometry])) #创建几何对象shp_feature ogr.Feature(feature_def) #生成新的特征Feature以便将其添加到layer中#为特征设置属性值for prop_name,prop_value in feature[properties].items():# 根据rename_map获取映射后的字段名short_name rename_map.get(prop_name, prop_name[:10])prop_value str(prop_value) if prop_value is not None else shp_feature.SetField(short_name, prop_value)# 设置特征的属性。shp_feature.SetGeometry(geom) # 将几何对象与特征关联。layer.CreateFeature(shp_feature)# 将特征添加到图层中。# 销毁要素释放内存shp_feature None
# 关闭数据源
data_source None