pyshp创建面shp文件并设置投影

  • 使用pyshp创建shapefile,方便快捷
  • 参考官方文档
  • 首先安装pip install pyshp==1.2.3
  • 创建示例
"""
using pyshp create shpfile
(1) type:You can reference shape types by the numbers or by constants defined by PyShp:
shapefile.NULL = 0 shapefile.POINT = 1 shapefile.POLYLINE = 3 shapefile.POLYGON = 5
shapefile.MULTIPOINT = 8 shapefile.POINTZ = 11 shapefile.POLYLINEZ = 13 shapefile.POLYGONZ = 15
shapefile.MULTIPOINTZ = 18 shapefile.POINTM = 21 shapefile.POLYLINEM = 23 shapefile.POLYGONM = 25
shapefile.MULTIPOINTM = 28 shapefile.MULTIPATCH = 31'''
(2) field setting
Field name: the name describing the data at this column index.
Field type: the type of data at this column index. Types can be: Character, Numbers, Longs, Dates, or Memo. The “Memo” type has no meaning within a GIS and is part of the xbase spec instead.
Field length: the length of the data found at this column index. Older GIS software may truncate this length to 8 or 11 characters for “Character” fields.
Decimal length: the number of decimal places found in “Number” fields.

"""

import shapefile
import osr

outshp = r'D:\za\testshp\a.shp'

w = shapefile.Writer(shapeType=5)

#设置字段,最大长度为254,C为字符串
w.field('FIRST_FLD')
w.field('SECOND_FLD','C','40')
#添加几何和添加字段信息,添加两个示例,字段顺序区分先后
w.poly([[[122,37], [117,36], [115,32],[118,20], [123,24],[122,37]]])
w.record('First','Point')
w.poly([[[123,37], [118,36], [116,32],[119,20], [124,24],[123,37]]])
w.record('Second','Point')
#保存
w.save(outshp)

# 设置投影,通过.prj文件设置,需要写入一个wkt字符串
##gdal的GetProjection()返回的是wkt字符串,需要ImportFromWkt
#projstr="""PROJCS["WGS_1984_UTM_zone_50N",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",117],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32650"]]'"""
proj = osr.SpatialReference()
proj.ImportFromEPSG(4326)
#或 proj.ImportFromProj4(proj4str)等其他的来源
wkt = proj.ExportToWkt()
#写出prj文件
f = open(outshp.replace(".shp",".prj"), 'w')
f.write(wkt)
f.close()
发布了57 篇原创文章 · 获赞 73 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/weixin_40450867/article/details/103800529