70 likes | 222 Views
ABT 182 / HYD 182 Environmental Analysis using GIS Week 4-2. OGR Simple Feature Library. OGR Command line program Library (python, R, QGIS, ….) Supports many different vector formats Shapefiles, personal geodatabases, MapInfo, GRASS, KML
E N D
ABT 182 / HYD 182 Environmental Analysis using GIS Week 4-2 OGR Simple Feature Library
OGR Command line program Library (python, R, QGIS, ….) Supports many different vector formats Shapefiles, personal geodatabases, MapInfo, GRASS, KML Databases such as MySQL, PostgreSQL, Oracle Spatial try: from osgeo import ogr except: import ogr
Reading a file with OGR from osgeo import ogr driver = ogr.GetDriverByName('ESRI Shapefile') dataSource = driver.Open(fn, 0) layer = dataSource.GetLayer(0) print layer.GetFeatureCount() print layer.GetExtent() feature = layer.GetNextFeature() while feature: id = feature.GetField('id') geom = feature.GetGeometryRef() print geom.GetX() feature.Destroy() feature = layer.GetNextFeature() datasource.Destroy() A driver knows a certain data type 0 for read-only, 1 for writeable first layer (shp only has one) very similar to Arc scripts for point objects
Writing a file with OGR os.chdir('c:/abt182/lab8/') fn = 'test.shp' Open an existing file dataSource = driver.Open(fn, 1) layer = dataSource.GetLayer(0) Create a new file driver = ogr.GetDriverByName('ESRI Shapefile') if os.path.exists(fn): driver.DeleteDataSource(fn) dataSource = driver.CreateDataSource(fn) layer = dataSource.CreateLayer('test', geom_type=ogr.wkbPoint)
Defining new fields From an existing feature fieldDefn = feature.GetFieldDefnRef(0) fieldDefn = feature.GetFieldDefnRef('id') From a new feature fieldDefn = ogr.FieldDefn('id', ogr.OFTInteger) fieldDefn = ogr.FieldDefn('id', ogr.OFTString) fieldDefn.SetWidth(4) layer.CreateField(fieldDefn)
Creating new features (after adding the fields) featureDefn = layer.GetLayerDefn() feature = ogr.Feature(featureDefn) feature.SetGeometry(<object>) feature.SetField('id', 23) layer.CreateFeature(feature)