我想以编程方式使用shapefile中的多边形创建GeoJSON文件,但要从我自己的应用程序中添加属性。
对于shapefile来说,这很容易做到:
def create_data_dayer(self,varlist, data):
"""
Creates a new shape to contain data about nodes.
varlist is the list of fields names associated with
the nodes.
data is a list of lists whose first element is the geocode
and the remaining elements are values of the fields, in the
same order as they appear in varlist.
"""
if os.path.exists(os.path.join(self.outdir,'Data.shp')):
os.remove(os.path.join(self.outdir,'Data.shp'))
os.remove(os.path.join(self.outdir,'Data.shx'))
os.remove(os.path.join(self.outdir,'Data.dbf'))
# Creates a new shape file to hold the data
if not self.datasource:
dsd = self.driver.CreateDataSource(os.path.join(self.outdir,'Data.shp'))
self.datasource = dsd
dl = dsd.CreateLayer("sim_results",geom_type=ogr.wkbPolygon)
#Create the fields
fi1 = ogr.FieldDefn("geocode",field_type=ogr.OFTInteger)
dl.CreateField(fi1)
for v in varlist:
#print "creating data fields"
fi = ogr.FieldDefn(v,field_type=ogr.OFTString)
fi.SetPrecision(12)
dl.CreateField(fi)
#Add the features (points)
for n,l in enumerate(data):
#Iterate over the lines of the data matrix.
gc = l[0]
try:
geom = self.geomdict[gc]
if geom.GetGeometryType() != 3: continue
#print geom.GetGeometryCount()
fe = ogr.Feature(dl.GetLayerDefn())
fe.SetField('geocode',gc)
for v,d in zip (varlist,l[1:]):
#print v,d
fe.SetField(v,str(d))
#Add the geometry
#print "cloning geometry"
clone = geom.Clone()
#print geom
#print "setting geometry"
fe.SetGeometry(clone)
#print "creating geom"
dl.CreateFeature(fe)
except: #Geocode not in polygon dictionary
pass
dl.SyncToDisk()
由于我通过geocode(self.geomdict)将所有几何图形保存在字典中,因此我仅创建要素,设置字段并从预先存在的层克隆几何图形(为简化起见,省略了该层的代码加载)。我现在需要的是一种通过字段和几何的组合生成GeoJSON的方法,自然是借助OGR来正确获取文件的其余部分(如源地图中的CRS等)
如何导出如上生成的要素集合?