OGR1.6 above python2.4 above 只需要定义fields,roads数据调用serial_shpdata_road()即可一次输出到shp文件 不适合大批量坐标一次生成shp ogr的问题在于python代码中初始化layer之后传递到其他函数使用将会导致莫名错误,应该是个bug 1 #bin.zhang@sw2us.com 2 fields=[ 3 {'name':'roadname','type':FIELD_STRING,'width':30} 4 ] 5 roads=[ 6 { 7 'geom':[(121.1,31.1),(121.101,31.102),(121.101,31.2)], 8 'attrs':('xscott.test',) 9 } 10 ] 11 serial_shpdata_road('d:/temp3/aa.shp',fields,roads) 12 ''' 13 def serial_shpdata_road(file,fields,roads): 14 ''' 15 fields: [{name,type,width},] 16 roads - [{'geom':[(x,y),..],'wkt':'','attrs':[name,type,len,]},..] 17 ''' 18 layer = None 19 20 if os.path.exists(file): 21 os.remove(file) 22 23 makePrjFile(file) 24 ds = driver.CreateDataSource(file) 25 layer = ds.CreateLayer("road",geom_type=ogr.wkbMultiLineString) 26 for f in fields: 27 fld = ogr.FieldDefn(f['name'],f['type']) 28 29 if f['type'] == FIELD_STRING : 30 w = 30 31 if f.has_key('width'): 32 w = f['width'] 33 fld.SetWidth(w) 34 layer.CreateField(fld) 35 ftrdfn = layer.GetLayerDefn() 36 37 for r in roads: 38 g = None 39 if r.has_key('wkt'): 40 g = ogr.CreateGeometryFromWkt(r['wkt']) 41 if r.has_key('geom'): 42 pts = r['geom'] 43 pts = map(lambda pt: '%s %s'%(pt[0],pt[1]),pts) 44 txt = string.join(pts,',') 45 wkt = "MULTILINESTRING((%s))"%txt 46 g = ogr.CreateGeometryFromWkt(wkt) 47 48 ftr = ogr.Feature(ftrdfn) 49 ftr.SetGeometry(g) 50 for n in range(len(r['attrs'])): 51 at = r['attrs'][n] 52 ftr.SetField(n,at) 53 layer.CreateFeature(ftr) 54 layer.SyncToDisk() 55
|