创建Shapefile文件并写入数据的例子

yipeiwu_com6年前Python基础

基本思路

使用GDAL创建Shapefile数据的基本步骤如下:

使用osgeo.ogr.Driver的CreateDataSource()方法创建osgeo.ogr.DataSource矢量数据集

使用osgeo.ogr.DataSource的CreateLayer()方法创建一个图层

使用osgeo.ogr.FieldDefn()定义Shapefile文件的属性字段

创建osgeo.ogr.Feature对象,设置每个属性字段的值,使用Feature对象的SetGeometry()定义几何属性

创建Feature对象以后,使用osgeo.ogr.Layer的CreateFeature()添加Feature对象到当前图层

重复步骤4和5依次添加所有的Feature到当前图层即可

代码实现

下面的例子中,我们读取GeoJSON表示的中国省区数据,然后其转为Shapefile格式。

GeoJSON编码片段如下:

可以看到每个Feature都有一个properties字段和geometry字段,我们需要根据properties字段的信息创建Shapefile数据的属性表,根据geometry字段创建Shapefile中的几何数据。

from osgeo import ogr
from osgeo import osr
import json
import os
os.environ['SHAPE_ENCODING'] = "utf-8"


with open('China.json') as f:
 china = json.load(f)

# 创建DataSource
driver = ogr.GetDriverByName('ESRI Shapefile')
ds = driver.CreateDataSource('China.shp')

# 创建WGS84空间参考
srs = osr.SpatialReference()
srs.ImportFromEPSG(4326)

# 创建图层
layer = ds.CreateLayer('province', srs, ogr.wkbPolygon)
# 添加属性定义
fname = ogr.FieldDefn('Name', ogr.OFTString)
fname.SetWidth(24)
layer.CreateField(fname)
fcx = ogr.FieldDefn('CenterX', ogr.OFTReal)
layer.CreateField(fcx)
fcy = ogr.FieldDefn('CenterY', ogr.OFTReal)
layer.CreateField(fcy)

# 变量GeoJSON中的features
for f in china['features']:
 # 新建Feature并且给其属性赋值
 feature = ogr.Feature(layer.GetLayerDefn())
 feature.SetField('Name', f['properties']['name'])
 feature.SetField('CenterX', f['properties']['cp'][0])
 feature.SetField('CenterY', f['properties']['cp'][1])

 # 设置Feature的几何属性Geometry
 polygon = ogr.CreateGeometryFromJson(str(f['geometry']))
 feature.SetGeometry(polygon)
 # 创建Feature
 layer.CreateFeature(feature)
 del feature
ds.FlushCache()

del ds

以上这篇创建Shapefile文件并写入数据的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

基于python plotly交互式图表大全

基于python plotly交互式图表大全

plotly可以制作交互式图表,直接上代码: import plotly.offline as py from plotly.graph_objs import Scatter, L...

Python isinstance判断对象类型

复制代码 代码如下:if (typeof(objA) == typeof(String)) { //TODO } 在Python中只需要使用内置的函数isinstance,使用起来非常简...

Django 接收Post请求数据,并保存到数据库的实现方法

要说基本操作,大家基本都会,但是有时候,有些操作使用小技巧会节省很多时间。 本篇描述的就是使用dict小技巧,保存到数据库,用来节省大家编码的工作量。 主要内容:通过for循环拿到pos...

python 使用装饰器并记录log的示例代码

1.首先定义一个log文件 # -*- coding: utf-8 -*- import os import time import logging import sys log_d...

Python文件操作中进行字符串替换的方法(保存到新文件/当前文件)

题目: 1.首先将文件:/etc/selinux/config 进行备份 文件名为 /etc/selinux/config.bak 2.再文件:/etc/selinux/config 中...