def compute_polygon_area(polygon_points): """ :param geometry: :return: area of polygon """ wkt = "LINESTRING (" for point in polygon_points: wkt += str(point[0]) + " " + str(point[1]) + "," wkt = wkt[:-1] + ")" geometry = ogr.CreateGeometryFromWkt(wkt) return ogr.Geometry.Area(ogr.ForceToPolygon(geometry))
def ogr_factory_2(): src_wkt = 'MULTIPOLYGON (((0 0,100 0,100 100,0 0)))' exp_wkt = 'POLYGON((0 0,100 0,100 100,0 0))' src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom = ogr.ForceToPolygon(src_geom) if ogrtest.check_feature_geometry(dst_geom, exp_wkt): print(dst_geom.ExportToWkt()) return 'fail' return 'success'
def ogr_factory_6(): src_wkt_list = [ None, 'POINT EMPTY', 'LINESTRING EMPTY', 'POLYGON EMPTY', 'MULTIPOINT EMPTY', 'MULTILINESTRING EMPTY', 'MULTIPOLYGON EMPTY', 'GEOMETRYCOLLECTION EMPTY', 'POINT(0 0)', 'LINESTRING(0 0)', 'POLYGON((0 0))', 'POLYGON(EMPTY,(0 0),EMPTY,(1 1))', 'MULTIPOINT(EMPTY,(0 0),EMPTY,(1 1))', 'MULTILINESTRING(EMPTY,(0 0),EMPTY,(1 1))', 'MULTIPOLYGON(((0 0),EMPTY,(1 1)),EMPTY,((2 2)))', 'GEOMETRYCOLLECTION(POINT EMPTY)', 'GEOMETRYCOLLECTION(LINESTRING EMPTY)', 'GEOMETRYCOLLECTION(POLYGON EMPTY)', 'GEOMETRYCOLLECTION(MULTIPOINT EMPTY)', 'GEOMETRYCOLLECTION(MULTILINESTRING EMPTY)', 'GEOMETRYCOLLECTION(MULTIPOLYGON EMPTY)', 'GEOMETRYCOLLECTION(GEOMETRYCOLLECTION EMPTY)', 'GEOMETRYCOLLECTION(POINT(0 0))', 'GEOMETRYCOLLECTION(LINESTRING(0 0),LINESTRING(1 1))', 'GEOMETRYCOLLECTION(POLYGON((0 0),EMPTY,(2 2)), POLYGON((1 1)))', ] for src_wkt in src_wkt_list: if src_wkt is None: src_geom = None else: src_geom = ogr.CreateGeometryFromWkt(src_wkt) dst_geom1 = ogr.ForceToPolygon(src_geom) dst_geom2 = ogr.ForceToMultiPolygon(src_geom) dst_geom3 = ogr.ForceToMultiPoint(src_geom) dst_geom4 = ogr.ForceToMultiLineString(src_geom) dst_geom5 = ogr.ForceToLineString(src_geom) #print(src_geom.ExportToWkt(), dst_geom1.ExportToWkt(), dst_geom2.ExportToWkt(), dst_geom3.ExportToWkt(), dst_geom4.ExportToWkt()) return 'success'
wgs_geojson_moved = { 'coordinates': [corner_points_moved], 'type': 'Polygon' } wgs_geojson_moved = json.dumps(wgs_geojson_moved) # wgs to utm utm_geojson_moved = { 'coordinates': [wgs2utm.transform_points(corner_points_moved)], 'type': 'Polygon' } utm_geojson_moved = json.dumps(utm_geojson_moved) # 6 create polygon geometry wgs_geom = ogr.CreateGeometryFromJson(wgs_geojson_moved) wgs_geom_polygon = ogr.ForceToPolygon(wgs_geom) utm_geom = ogr.CreateGeometryFromJson(utm_geojson_moved) # 7 create feature wgs_feat = ogr.Feature(wgs_layerDefn) wgs_feat.SetGeometry(wgs_geom) wgs_feat.SetField('GridID', '%s_%s' % (zone, id)) # wgs_feat.SetGeomField('the_geom', wgs_geom) utm_feat = ogr.Feature(utm_layerDefn) utm_feat.SetGeometry(utm_geom) utm_feat.SetField('GridID', '%s_%s' % (zone, id)) # 8 save feature wgs_lyr.CreateFeature(wgs_feat) utm_lyr.CreateFeature(utm_feat)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Atribui casos de dengue a APS usando a OGR """ import ogr import sys # Criando a Shapefile com as CAPs drv = ogr.GetDriverByName('ESRI Shapefile') ds_in = drv.Open("../cap_sms_4326.shp") lyr_in = ds_in.GetLayer(0) geometries = { ogr.ForceToPolygon(feat.GetGeometryRef()): feat.GetFieldAsDouble(feat.GetFieldIndex("COD_AP_SMS")) for feat in lyr_in } def get_AP(ind, lon, lat): """ Returns the AP corresponding to the point """ # create point geometry pt = ogr.Geometry(ogr.wkbPoint) pt.SetPoint_2D(0, lon, lat) # go over all the polygons in the layer see if one include the point
def getCatchmentFeaturesForReaches(config, outputDir, catchmentFilename, reaches, format=OGR_SHAPEFILE_DRIVER_NAME): """ Get features (in WGS 84) for the drainage area associated with a set of NHD (National Hydrography Dataset) stream reaches. @param config A Python ConfigParser containing the following sections and options: 'PATH_OF_NHDPLUS2_CATCHMENT' (absolute path to NHD catchment shapefile) @param outputDir String representing the absolute/relative path of the directory into which output rasters should be written @param catchmentFilename String representing name of file to save catchment features to. The appropriate extension will be added to the file name @param reaches List representing catchment features to be output @param format String representing OGR driver to use @return String representing the name of the dataset in outputDir created to hold the features @raise ConfigParser.NoSectionError @raise ConfigParser.NoOptionError @raise IOError(errno.ENOTDIR) if outputDir is not a directory @raise IOError(errno.EACCESS) if outputDir is not writable @raise Exception if output format is not known @todo Detect and fix non-closed geometries, e.g. kalisti:archive miles$ ./GetCatchmentsForComidsSP.py -p test -c 10462287 Traceback (most recent call last): File "./GetCatchmentsForComidsSP.py", line 29, in <module> catchmentFilename, comid) File "/Users/miles/Dropbox/EarthCube-Multilayered/RHESSys-workflow/eclipse/EcohydroWorkflowLib/ecohydrolib/nhdplus2/networkanalysis.py", line 506, in getCatchmentFeaturesForComid outGeom = outGeom.Union( inGeom ) File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/osgeo/ogr.py", line 4065, in Union return _ogr.Geometry_Union(self, *args) RuntimeError: TopologyException: found non-noded intersection between LINESTRING (-77.9145 37.0768, -77.9147 37.0768) and LINESTRING (-77.9147 37.0768, -77.9145 37.0768) at -77.914621661942761 37.076822779115943 """ catchmentFeatureDBPath = config.get('NHDPLUS2', 'PATH_OF_NHDPLUS2_CATCHMENT') if not os.access(catchmentFeatureDBPath, os.R_OK): raise IOError( errno.EACCES, "The catchment feature DB at %s is not readable" % catchmentFeatureDBPath) catchmentFeatureDBPath = os.path.abspath(catchmentFeatureDBPath) if not os.path.isdir(outputDir): raise IOError(errno.ENOTDIR, "Output directory %s is not a directory" % (outputDir, )) if not os.access(outputDir, os.W_OK): raise IOError( errno.EACCES, "Not allowed to write to output directory %s" % (outputDir, )) outputDir = os.path.abspath(outputDir) if not format in list(OGR_DRIVERS.keys()): raise Exception("Output format '%s' is not known" % (format, )) catchmentFilename = "%s%s%s" % (catchmentFilename, os.extsep, OGR_DRIVERS[format]) catchmentFilepath = os.path.join(outputDir, catchmentFilename) # Open input layer ogr.UseExceptions() poDS = ogr.Open(catchmentFeatureDBPath, OGR_UPDATE_MODE) if not poDS: raise Exception("Unable to open catchment feature database %s" ( catchmentFeatureDBPath, )) assert (poDS.GetLayerCount() > 0) poLayer = poDS.GetLayer(0) assert (poLayer) # Create output data source poDriver = ogr.GetDriverByName(format) assert (poDriver) poODS = poDriver.CreateDataSource(catchmentFilepath) assert (poODS != None) # poOLayer = poODS.CreateLayer("catchment", poLayer.GetSpatialRef(), poLayer.GetGeomType()) poOLayer = poODS.CreateLayer("catchment", poLayer.GetSpatialRef(), ogr.wkbMultiPolygon) # poOLayer = poODS.CreateLayer("catchment", poLayer.GetSpatialRef(), ogr.wkbPolygon ) # Create fields in output layer layerDefn = poLayer.GetLayerDefn() i = 0 fieldCount = layerDefn.GetFieldCount() while i < fieldCount: fieldDefn = layerDefn.GetFieldDefn(i) poOLayer.CreateField(fieldDefn) i = i + 1 # Create single geometry to hold catchment polygon in output shapefile outGeom = ogr.Geometry(poOLayer.GetGeomType()) # polygon = Polygon() # Copy features, unioning them as we go numReaches = len(reaches) # Copy features in batches of UPSTREAM_SEARCH_THRESHOLD to overcome limit in # OGR driver for input layer start = 0 end = UPSTREAM_SEARCH_THRESHOLD while end < numReaches: whereFilter = "featureid=%s" % (reaches[start], ) for reach in reaches[start + 1:end]: whereFilter = whereFilter + " OR featureid=%s" % (reach, ) # Copy features assert (poLayer.SetAttributeFilter(whereFilter) == 0) inFeature = poLayer.GetNextFeature() # Union geometry of input feature to output feature while inFeature: # inGeom = inFeature.GetGeometryRef().SimplifyPreserveTopology(0.0001) inGeom = inFeature.GetGeometryRef() outGeom = outGeom.Union(inGeom) # polygon = polygon.union( loads( inGeom.ExportToWkb() ) ) # polygon = cascaded_union( [polygon, loads( inGeom.ExportToWkb() )] ) inFeature.Destroy() inFeature = poLayer.GetNextFeature() start = end end = end + UPSTREAM_SEARCH_THRESHOLD # Copy remaining features whereFilter = "featureid=%s" % (reaches[start], ) for reach in reaches[start + 1:end]: whereFilter = whereFilter + " OR featureid=%s" % (reach, ) # Copy features poLayer.SetAttributeFilter(whereFilter) assert (poLayer.SetAttributeFilter(whereFilter) == 0) inFeature = poLayer.GetNextFeature() while inFeature: # inGeom = inFeature.GetGeometryRef().SimplifyPreserveTopology(0.0001) inGeom = inFeature.GetGeometryRef() outGeom = outGeom.Union(inGeom) # polygon = polygon.union( loads( inGeom.ExportToWkb() ) ) # polygon = cascaded_union( [polygon, loads( inGeom.ExportToWkb() )] ) inFeature.Destroy() inFeature = poLayer.GetNextFeature() # Create a new polygon that only contains exterior points outGeom = ogr.ForceToPolygon(outGeom) polygon = loads(outGeom.ExportToWkb()) if polygon.exterior: coords = polygon.exterior.coords newPolygon = Polygon(coords) else: newPolygon = Polygon() # Write new feature to output feature data source outFeat = ogr.Feature(poOLayer.GetLayerDefn()) outFeat.SetGeometry(ogr.CreateGeometryFromWkb(dumps(newPolygon))) poOLayer.CreateFeature(outFeat) return catchmentFilename