def __init__(self, geom_input, srs=None): """Initialize Geometry on either WKT or an OGR pointer as input.""" str_instance = isinstance(geom_input, str) # If HEX, unpack input to a binary buffer. if str_instance and hex_regex.match(geom_input): geom_input = memoryview(bytes.fromhex(geom_input)) str_instance = False # Constructing the geometry, if str_instance: wkt_m = wkt_regex.match(geom_input) json_m = json_regex.match(geom_input) if wkt_m: if wkt_m['srid']: # If there's EWKT, set the SRS w/value of the SRID. srs = int(wkt_m['srid']) if wkt_m['type'].upper() == 'LINEARRING': # OGR_G_CreateFromWkt doesn't work with LINEARRING WKT. # See https://trac.osgeo.org/gdal/ticket/1992. g = capi.create_geom(OGRGeomType(wkt_m['type']).num) capi.import_wkt(g, byref(c_char_p(wkt_m['wkt'].encode()))) else: g = capi.from_wkt(byref(c_char_p(wkt_m['wkt'].encode())), None, byref(c_void_p())) elif json_m: g = self._from_json(geom_input.encode()) else: # Seeing if the input is a valid short-hand string # (e.g., 'Point', 'POLYGON'). OGRGeomType(geom_input) g = capi.create_geom(OGRGeomType(geom_input).num) elif isinstance(geom_input, memoryview): # WKB was passed in g = self._from_wkb(geom_input) elif isinstance(geom_input, OGRGeomType): # OGRGeomType was passed in, an empty geometry will be created. g = capi.create_geom(geom_input.num) elif isinstance(geom_input, self.ptr_type): # OGR pointer (c_void_p) was the input. g = geom_input else: raise GDALException( 'Invalid input type for OGR Geometry construction: %s' % type(geom_input)) # Now checking the Geometry pointer before finishing initialization # by setting the pointer for the object. if not g: raise GDALException('Cannot create OGR Geometry from input: %s' % geom_input) self.ptr = g # Assigning the SpatialReference object to the geometry, if valid. if srs: self.srs = srs # Setting the class depending upon the OGR Geometry Type self.__class__ = GEO_CLASSES[self.geom_type.num]
def geom_type(self): "Returns the Type for this Geometry." try: return OGRGeomType(get_geom_type(self._ptr)) except OGRException: # VRT datasources return an invalid geometry type # number, but a valid name -- we'll try that instead. # See: http://trac.osgeo.org/gdal/ticket/2491 return OGRGeomType(get_geom_name(self._ptr))
The OGRGeometry is a wrapper for using the OGR Geometry class (see https://www.gdal.org/classOGRGeometry.html). OGRGeometry may be instantiated when reading geometries from OGR Data Sources (e.g. SHP files), or when given OGC WKT (a string). While the 'full' API is not present yet, the API is "pythonic" unlike the traditional and "next-generation" OGR Python bindings. One major advantage OGR Geometries have over their GEOS counterparts is support for spatial reference systems and their transformation. Example: >>> from django.contrib.gis.gdal import OGRGeometry, OGRGeomType, SpatialReference >>> wkt1, wkt2 = 'POINT(-90 30)', 'POLYGON((0 0, 5 0, 5 5, 0 5)' >>> pnt = OGRGeometry(wkt1) >>> print(pnt) POINT (-90 30) >>> mpnt = OGRGeometry(OGRGeomType('MultiPoint'), SpatialReference('WGS84')) >>> mpnt.add(wkt1) >>> mpnt.add(wkt1) >>> print(mpnt) MULTIPOINT (-90 30,-90 30) >>> print(mpnt.srs.name) WGS 84 >>> print(mpnt.srs.proj) +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs >>> mpnt.transform(SpatialReference('NAD27')) >>> print(mpnt.proj) +proj=longlat +ellps=clrk66 +datum=NAD27 +no_defs >>> print(mpnt) MULTIPOINT (-89.999930378602485 29.999797886557641,-89.999930378602485 29.999797886557641) The OGRGeomType class is to make it easy to specify an OGR geometry type: >>> from django.contrib.gis.gdal import OGRGeomType >>> gt1 = OGRGeomType(3) # Using an integer for the type >>> gt2 = OGRGeomType('Polygon') # Using a string >>> gt3 = OGRGeomType('POLYGON') # It's case-insensitive >>> print(gt1 == 3, gt1 == 'Polygon') # Equivalence works w/non-OGRGeomType objects True True
def __init__(self, path, attrs, geom='geometry', layer='lyr', id='id', srid=4326): self.path = path self.filename = os.path.split(path)[1] self.attrs = attrs self.geom = geom self.layer = layer self.id = id self.srid = srid ## CREATE SHAPEFILE BASE ATTRS ----------------------------------------- ## manages field names in the shapefile self.fcache = FieldCache() ## need the first row to assess data types template = self.attrs[0] ## the OGR fields # tr() self.ogr_fields = [OgrField(self.fcache, id, template[id])] self.ogr_fields += [ OgrField(self.fcache, key, value) for key, value in template['properties'].iteritems() ] # self.ogr_fields = [OgrField(self.fcache,key,value) # for key,value in template.iteritems() # if key != self.geom] ## create the geometry type bgeom = template[self.geom] # tr() # self.ogr_geom = OGRGeomType(bgeom.ogr.geom_type).num self.ogr_geom = OGRGeomType(bgeom.geometryType()).num # tr() ## the spatial reference system # try: # try: # self.srs = osr.SpatialReference(bgeom.srid) self.srs = osr.SpatialReference() self.srs.ImportFromEPSG(srid)
def extract_polygons(shapefile_path): ''' Given an (existing, saved to disk) shapefile, retrieve all polygons as one MultiPolygon. ''' polygons = GDALMultiPolygon(OGRGeomType('MultiPolygon')) # empty GDAL geom try: data_source = DataSource(shapefile_path) for layer in data_source: if layer.geom_type.name in ('Polygon', 'MultiPolygon'): for feature in layer: geometry = feature.geom.transform(4326, clone=True) polygons.add(geometry) except GDALException as err: message = str(err) # Make sure we don't expose the confusing file path message = message.replace('at "{}"'.format(shapefile_path), '') raise ValueError(message) return polygons.geos
def geom_type(self): "Returns the geometry type (OGRGeomType) of the Layer." return OGRGeomType(capi.get_fd_geom_type(self._ldefn))
def __init__(self, geom_input, srs=None): "Initializes Geometry on either WKT or an OGR pointer as input." str_instance = isinstance(geom_input, basestring) # If HEX, unpack input to to a binary buffer. if str_instance and hex_regex.match(geom_input): geom_input = buffer(a2b_hex(geom_input.upper())) str_instance = False # Constructing the geometry, if str_instance: # Checking if unicode if isinstance(geom_input, unicode): # Encoding to ASCII, WKT or HEX doesn't need any more. geom_input = geom_input.encode('ascii') wkt_m = wkt_regex.match(geom_input) json_m = json_regex.match(geom_input) if wkt_m: if wkt_m.group('type').upper() == 'LINEARRING': # OGR_G_CreateFromWkt doesn't work with LINEARRING WKT. # See http://trac.osgeo.org/gdal/ticket/1992. g = capi.create_geom(OGRGeomType(wkt_m.group('type')).num) capi.import_wkt(g, byref(c_char_p(geom_input))) else: g = capi.from_wkt(byref(c_char_p(geom_input)), None, byref(c_void_p())) elif json_m: if GEOJSON: g = capi.from_json(geom_input) else: raise NotImplementedError( 'GeoJSON input only supported on GDAL 1.5+.') else: # Seeing if the input is a valid short-hand string # (e.g., 'Point', 'POLYGON'). ogr_t = OGRGeomType(geom_input) g = capi.create_geom(OGRGeomType(geom_input).num) elif isinstance(geom_input, buffer): # WKB was passed in g = capi.from_wkb(str(geom_input), None, byref(c_void_p()), len(geom_input)) elif isinstance(geom_input, OGRGeomType): # OGRGeomType was passed in, an empty geometry will be created. g = capi.create_geom(geom_input.num) elif isinstance(geom_input, self.ptr_type): # OGR pointer (c_void_p) was the input. g = geom_input else: raise OGRException( 'Invalid input type for OGR Geometry construction: %s' % type(geom_input)) # Now checking the Geometry pointer before finishing initialization # by setting the pointer for the object. if not g: raise OGRException('Cannot create OGR Geometry from input: %s' % str(geom_input)) self.ptr = g # Assigning the SpatialReference object to the geometry, if valid. if bool(srs): self.srs = srs # Setting the class depending upon the OGR Geometry Type self.__class__ = GEO_CLASSES[self.geom_type.num]
def centroid(self): "Returns the centroid (a Point) of this Polygon." # The centroid is a Point, create a geometry for this. p = OGRGeometry(OGRGeomType('Point')) capi.get_centroid(self.ptr, p.ptr) return p
def geom_type(self): "Returns the Type for this Geometry." return OGRGeomType(capi.get_geom_type(self.ptr))
def _create_empty(cls): return capi.create_geom(OGRGeomType('point').num)
geom_input = memoryview(a2b_hex(geom_input.upper().encode())) >>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435 str_instance = False # Constructing the geometry, if str_instance: wkt_m = wkt_regex.match(geom_input) json_m = json_regex.match(geom_input) if wkt_m: if wkt_m.group('srid'): # If there's EWKT, set the SRS w/value of the SRID. srs = int(wkt_m.group('srid')) if wkt_m.group('type').upper() == 'LINEARRING': # OGR_G_CreateFromWkt doesn't work with LINEARRING WKT. # See http://trac.osgeo.org/gdal/ticket/1992. g = capi.create_geom(OGRGeomType(wkt_m.group('type')).num) capi.import_wkt(g, byref(c_char_p(wkt_m.group('wkt').encode()))) else: g = capi.from_wkt(byref(c_char_p(wkt_m.group('wkt').encode())), None, byref(c_void_p())) elif json_m: <<<<<<< HEAD g = capi.from_json(geom_input.encode()) ======= g = self._from_json(geom_input.encode()) >>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435 else: # Seeing if the input is a valid short-hand string # (e.g., 'Point', 'POLYGON'). OGRGeomType(geom_input) g = capi.create_geom(OGRGeomType(geom_input).num) <<<<<<< HEAD
def num_fields(self): <<<<<<< HEAD "Returns the number of fields in the Layer." ======= "Return the number of fields in the Layer." >>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435 return capi.get_field_count(self._ldefn) @property def geom_type(self): <<<<<<< HEAD "Returns the geometry type (OGRGeomType) of the Layer." ======= "Return the geometry type (OGRGeomType) of the Layer." >>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435 return OGRGeomType(capi.get_fd_geom_type(self._ldefn)) @property def srs(self): <<<<<<< HEAD "Returns the Spatial Reference used in this Layer." ======= "Return the Spatial Reference used in this Layer." >>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435 try: ptr = capi.get_layer_srs(self.ptr) return SpatialReference(srs_api.clone_srs(ptr)) except SRSException: return None @property