def ogr_basic_9(): geom_type_tuples = [[ogr.wkbUnknown, "Unknown (any)"], [ogr.wkbPoint, "Point"], [ogr.wkbLineString, "Line String"], [ogr.wkbPolygon, "Polygon"], [ogr.wkbMultiPoint, "Multi Point"], [ogr.wkbMultiLineString, "Multi Line String"], [ogr.wkbMultiPolygon, "Multi Polygon"], [ogr.wkbGeometryCollection, "Geometry Collection"], [ogr.wkbNone, "None"], [ogr.wkbUnknown | ogr.wkb25DBit, "3D Unknown (any)"], [ogr.wkbPoint25D, "3D Point"], [ogr.wkbLineString25D, "3D Line String"], [ogr.wkbPolygon25D, "3D Polygon"], [ogr.wkbMultiPoint25D, "3D Multi Point"], [ogr.wkbMultiLineString25D, "3D Multi Line String"], [ogr.wkbMultiPolygon25D, "3D Multi Polygon"], [ ogr.wkbGeometryCollection25D, "3D Geometry Collection" ], [123456, "Unrecognized: 123456"]] for geom_type_tuple in geom_type_tuples: if ogr.GeometryTypeToName(geom_type_tuple[0]) != geom_type_tuple[1]: gdaltest.post_reason('fail') print('Got %s, expected %s' % (ogr.GeometryTypeToName( geom_type_tuple[0]), geom_type_tuple[1])) return 'fail' return 'success'
def get_geometry_type(self, layer: ogr.Layer) -> str: """Get geometry type human readable.""" try: logger.debug(ogr.GeometryTypeToName(layer.GetGeomType())) # if layer.GetGeomType(): # geom_type = layer.GetGeomType() # layer.ResetReading() # logger.error(geom_type) # return geom_type feat = layer.GetNextFeature() if not hasattr(feat, "GetGeometryRef"): logger.error("Unable to determine GeoMetryRef") return None layer_geom = feat.GetGeometryRef() if hasattr(layer_geom, "GetGeometryName"): return layer_geom.GetGeometryName() except Exception as err: logger.error( "Unable to retrieve geometry type for layer: {}. Trace: {}".format( layer.GetName(), err ) ) return None
def test_ogr_basic_9(): geom_type_tuples = [[ogr.wkbUnknown, "Unknown (any)"], [ogr.wkbPoint, "Point"], [ogr.wkbLineString, "Line String"], [ogr.wkbPolygon, "Polygon"], [ogr.wkbMultiPoint, "Multi Point"], [ogr.wkbMultiLineString, "Multi Line String"], [ogr.wkbMultiPolygon, "Multi Polygon"], [ogr.wkbGeometryCollection, "Geometry Collection"], [ogr.wkbNone, "None"], [ogr.wkbUnknown | ogr.wkb25DBit, "3D Unknown (any)"], [ogr.wkbPoint25D, "3D Point"], [ogr.wkbLineString25D, "3D Line String"], [ogr.wkbPolygon25D, "3D Polygon"], [ogr.wkbMultiPoint25D, "3D Multi Point"], [ogr.wkbMultiLineString25D, "3D Multi Line String"], [ogr.wkbMultiPolygon25D, "3D Multi Polygon"], [ ogr.wkbGeometryCollection25D, "3D Geometry Collection" ], [123456, "Unrecognized: 123456"]] for geom_type_tuple in geom_type_tuples: assert ogr.GeometryTypeToName(geom_type_tuple[0]) == geom_type_tuple[1]
def create_vector_resources(self, path, driver_name): """Create vector data resources""" path_to_dir = get_directory(path) dir_name = os.path.basename(path_to_dir) file_path_source = path source = os.path.normpath(file_path_source) layer_scr = self.get_source(source, driver_name) da_layer = layer_scr.GetLayer() if not self.name: self.name = dir_name self.set_globals(da_layer) layer = collections.OrderedDict() layer["name"] = clean_table_name(da_layer.GetName()) layer["url"] = str(da_layer.GetName()) + "path_to_be_filled" layer["geom_type"] = ogr.GeometryTypeToName( da_layer.GetLayerDefn().GetGeomType()) layer["schema"] = {} layer["schema"]["fields"] = [] layer_definition = da_layer.GetLayerDefn() for i in range(layer_definition.GetFieldCount()): col_obj = collections.OrderedDict() col_obj["name"] = layer_definition.GetFieldDefn(i).GetName() col_obj["precision"] = layer_definition.GetFieldDefn( i).GetPrecision() col_obj["type"] = layer_definition.GetFieldDefn(i).GetTypeName() col_obj["size"] = layer_definition.GetFieldDefn(i).GetWidth() layer["schema"]["fields"].append(col_obj) return layer
def get_shp_layer_type(layer_file): try: geom_type_index = layer_file.GetLayerDefn().GetGeomType() layer_type = ogr.GeometryTypeToName(geom_type_index) return layer_type except: return None
def set_globals(self, da_layer): """Set vector values""" self.title = "The {} dataset".format(da_layer.GetName()) self.description = da_layer.GetDescription() self.extent = OrderedDict( zip(["xMin", "xMax", "yMin", "yMax"], da_layer.GetExtent())) self.geom_type = ogr.GeometryTypeToName(da_layer.GetLayerDefn().GetGeomType()) sp_ref = da_layer.GetSpatialRef() if sp_ref: self.spatial_ref = "{}".format(str(sp_ref.ExportToWkt()))
def ReportOnLayer(self, poLayer, pszWHERE=None, poSpatialFilter=None): bVerbose = True poDefn = poLayer.GetLayerDefn() #/* -------------------------------------------------------------------- */ #/* Set filters if provided. */ #/* -------------------------------------------------------------------- */ if pszWHERE is not None: if poLayer.SetAttributeFilter(pszWHERE) != 0: self.out("FAILURE: SetAttributeFilter(%s) failed." % pszWHERE) return if poSpatialFilter is not None: poLayer.SetSpatialFilter(poSpatialFilter) #/* -------------------------------------------------------------------- */ #/* Report various overall information. */ #/* -------------------------------------------------------------------- */ self.out("") self.out("Layer name: %s" % poDefn.GetName()) if bVerbose: self.out("Geometry: %s" % ogr.GeometryTypeToName(poDefn.GetGeomType())) self.out("Feature Count: %d" % poLayer.GetFeatureCount()) oExt = poLayer.GetExtent(True, can_return_null=True) if oExt is not None: self.out("Extent: (%f, %f) - (%f, %f)" % (oExt[0], oExt[1], oExt[2], oExt[3])) if poLayer.GetSpatialRef() is None: pszWKT = "(unknown)" else: pszWKT = poLayer.GetSpatialRef().ExportToPrettyWkt() self.out("Layer SRS WKT:\n%s" % pszWKT) if len(poLayer.GetFIDColumn()) > 0: self.out("FID Column = %s" % poLayer.GetFIDColumn()) if len(poLayer.GetGeometryColumn()) > 0: self.out("Geometry Column = %s" % poLayer.GetGeometryColumn()) for iAttr in range(poDefn.GetFieldCount()): poField = poDefn.GetFieldDefn(iAttr) self.out( "%s: %s (%d.%d)" % ( \ poField.GetNameRef(), \ poField.GetFieldTypeName( poField.GetType() ), \ poField.GetWidth(), \ poField.GetPrecision() ))
def load_zonal_layer(self, zonal_layer_path): self.added_zonal_layer = zonal_layer = None zonal_layer_basename, zonal_layer_ext = os.path.splitext( os.path.basename(zonal_layer_path)) if zonal_layer_ext == '.gpkg': dlg = QgsSublayersDialog(QgsSublayersDialog.Ogr, 'Select zonal layer') conn = ogr.Open(zonal_layer_path) layer_defs = [] for idx, c in enumerate(conn): ld = QgsSublayersDialog.LayerDefinition() ld.layerId = idx ld.layerName = c.GetDescription() ld.count = c.GetFeatureCount() ld.type = ogr.GeometryTypeToName(c.GetGeomType()) layer_defs.append(ld) dlg.populateLayerTable(layer_defs) dlg.exec_() if not dlg.selection(): return None for sel in dlg.selection(): # NOTE: the last one will be chosen as zonal layer zonal_layer = QgsVectorLayer( zonal_layer_path + "|layername=" + sel.layerName, sel.layerName, 'ogr') if zonal_layer.isValid(): root = QgsProject.instance().layerTreeRoot() QgsProject.instance().addMapLayer(zonal_layer, False) root.insertLayer(0, zonal_layer) else: msg = 'Invalid layer' log_msg(msg, level='C', message_bar=self.iface.messageBar()) return None else: zonal_layer = QgsVectorLayer(zonal_layer_path, zonal_layer_basename, 'ogr') if not zonal_layer.geometryType() == QgsWkbTypes.PolygonGeometry: msg = 'Zonal layer must contain zone polygons' log_msg(msg, level='C', message_bar=self.iface.messageBar()) return None if zonal_layer_ext != '.gpkg': # Add zonal layer to registry if zonal_layer.isValid(): root = QgsProject.instance().layerTreeRoot() QgsProject.instance().addMapLayer(zonal_layer, False) root.insertLayer(0, zonal_layer) else: msg = 'Invalid zonal layer' log_msg(msg, level='C', message_bar=self.iface.messageBar()) return None self.added_zonal_layer = zonal_layer self.pre_populate_zonal_layer_cbx() return zonal_layer
def getVectorTables(self, schema=None): items = [] for i in range(self.gdal_ds.GetLayerCount()): lyr = self.gdal_ds.GetLayer(i) geomtype = lyr.GetGeomType() if hasattr(ogr, 'GT_Flatten'): geomtype_flatten = ogr.GT_Flatten(geomtype) else: geomtype_flatten = geomtype geomname = ogr.GeometryTypeToName(geomtype_flatten).upper() geomdim = 'XY' if hasattr(ogr, 'GT_HasZ') and ogr.GT_HasZ(lyr.GetGeomType()): geomdim += 'Z' if hasattr(ogr, 'GT_HasM') and ogr.GT_HasM(lyr.GetGeomType()): geomdim += 'M' srs = lyr.GetSpatialRef() srid = None if srs is not None: if srs.IsProjected(): name = srs.GetAttrValue('PROJCS', 0) elif srs.IsGeographic(): name = srs.GetAttrValue('GEOGCS', 0) else: name = None srid = srs.GetAuthorityCode(None) if srid is not None: srid = int(srid) else: srid = self._fetchOne( 'SELECT srid FROM gpkg_spatial_ref_sys WHERE table_name = %s' % self.quoteString(lyr.GetName())) if srid is not None: srid = int(srid) self.mapSridToName[srid] = name if geomtype == ogr.wkbNone: item = list([ Table.TableType, lyr.GetName(), False, # is_view ]) else: item = list([ Table.VectorType, lyr.GetName(), False, # is_view lyr.GetName(), lyr.GetGeometryColumn(), geomname, geomdim, srid ]) items.append(item) return items
def general_info(dataset): print(''' ################################ General info about the shapefile ################################ ''') ### Let's get the driver from this file driver = dataset.GetDriver() print('Dataset driver is: {n}\n'.format(n=driver.name)) ### How many layers are contained in this Shapefile? layer_count = dataset.GetLayerCount() print('The shapefile has {n} layer(s)\n'.format(n=layer_count)) ### What is the name of the 1 layer? layer = dataset.GetLayerByIndex(0) print('The layer is named: {n}\n'.format(n=layer.GetName())) ### What is the layer's geometry? is it a point? a polyline? a polygon? # First read in the geometry - but this is the enumerated type's value geometry = layer.GetGeomType() # So we need to translate it to the name of the enum geometry_name = ogr.GeometryTypeToName(geometry) print("The layer's geometry is: {geom}\n".format(geom=geometry_name)) ### What is the layer's projection? # Get the spatial reference spatial_ref = layer.GetSpatialRef() # Export this spatial reference to something we can read... like the Proj4 proj4 = spatial_ref.ExportToProj4() print('Layer projection is: {proj4}\n'.format(proj4=proj4)) ### How many features are in the layer? feature_count = layer.GetFeatureCount() print('Layer has {n} features\n'.format(n=feature_count)) ### How many fields are in the shapefile, and what are their names? # First we need to capture the layer definition defn = layer.GetLayerDefn() # How many fields field_count = defn.GetFieldCount() print('Layer has {n} fields'.format(n=field_count)) # What are their names? print('Their names are: ') for i in range(field_count): field_defn = defn.GetFieldDefn(i) print('\t{name} - {datatype}'.format(name=field_defn.GetName(), datatype=field_defn.GetTypeName()))
def _GetGeomType(src_geom_type_name): if EQUAL(src_geom_type_name, "GEOMETRY"): return ogr.wkbUnknown try: max_geom_type = ogr.wkbTriangle except: # GDAL 2.1 compat max_geom_type = ogr.wkbSurface for i in range(max_geom_type + 1): if EQUAL(src_geom_type_name, ogr.GeometryTypeToName(i).replace(' ', '')): return i return None
def _get_meta_geometry_type(self): # remove Z/M components ogr_geom_type = ogr.GT_Flatten(self.ogrlayer.GetGeomType()) if ogr_geom_type == ogr.wkbUnknown: return "GEOMETRY" return ( # normalise the geometry type names the way the GPKG spec likes it: # http://www.geopackage.org/spec/#geometry_types ogr.GeometryTypeToName(ogr_geom_type) # 'Line String' --> 'LineString' .replace(" ", "") # --> 'LINESTRING' .upper())
def collect_feature_class(feature_class_path: str, attribute_filter: str = None, clip_shape: BaseGeometry = None, clip_rect: List[float] = None ) -> ogr.Geometry: """Collect simple types into Multi types. Does not use Shapely Args: feature_class_path (str): [description] attribute_filter (str, optional): Attribute Query like "HUC = 17060104". Defaults to None. clip_shape (BaseGeometry, optional): Iterate over a subset by clipping to a Shapely-ish geometry. Defaults to None. clip_rect (List[double minx, double miny, double maxx, double maxy)]): Iterate over a subset by clipping to a Shapely-ish geometry. Defaults to None. Raises: Exception: [description] Returns: ogr.Geometry: [description] """ log = Logger('collect_feature_class') log.info('Collecting {} feature class.'.format(len(feature_class_path))) with get_shp_or_gpkg(feature_class_path) as in_lyr: in_geom_type = in_lyr.ogr_layer.GetGeomType() output_geom_type = None for tp, varr in VectorBase.MULTI_TYPES.items(): if in_geom_type in varr: output_geom_type = tp break if output_geom_type is None: raise Exception('collect_feature_class: Type "{}" not supported'.format(ogr.GeometryTypeToName(in_geom_type))) new_geom = ogr.Geometry(output_geom_type) for feat, _counter, _progbar in in_lyr.iterate_features('Collecting Geometry', attribute_filter=attribute_filter, clip_rect=clip_rect, clip_shape=clip_shape): geom = feat.GetGeometryRef() if geom.IsValid() and not geom.IsEmpty(): if geom.IsMeasured() > 0 or geom.Is3D() > 0: geom.FlattenTo2D() # Do the flatten first to speed up the potential transform if geom.GetGeometryType() in VectorBase.MULTI_TYPES.keys(): sub_geoms = list(geom) else: sub_geoms = [geom] for subg in sub_geoms: new_geom.AddGeometry(subg) log.info('Collect complete.') return new_geom
def geometry_type(self): """ Just return whether it's a type of point, line, or polygon. """ type_name = ogr.GeometryTypeToName( self.ds.GetLayer().GetGeomType()).lower() if type_name.find('point') != -1: return 'point' elif type_name.find('line') != -1: return 'line' elif type_name.find('polygon') != -1: return 'polygon' else: return None
def get_shapefile_geometry_types(shape_file): shapes = ogr.Open(shape_file) layer = shapes.GetLayer(0) types = set() type_ = None limit = 20000 count = layer.GetFeatureCount() if count > limit: skip = layer.GetFeatureCount() / limit else: skip = 1 checked = 0 for i in range(0, layer.GetFeatureCount(), skip): feature = layer.GetFeature(i) geometry = feature.geometry() if geometry: types.add(geo_type_map[ogr.GeometryTypeToName( geometry.GetGeometryType())]) checked += 1 else: # This happens rarely, seems to be a problem with the source # shapefiles. pass if len(types) == 1: type_ = list(types).pop() elif len(types) == 2: if set(('POLYGON', 'MULTIPOLYGON')) & types == set( ('POLYGON', 'MULTIPOLYGON')): type_ = 'MULTIPOLYGON' elif set(('POINT', 'MULTIPOINT')) & types == set( ('POINT', 'MULTIPOINT')): type_ = 'MULTIPOINT' elif set(('LINESTRING', 'MULTILINESTRING')) & types == set( ('LINESTRING', 'MULTILINESTRING')): type_ = 'MULTILINESTRING' else: raise Exception("Didn't get valid combination of types: " + str(types)) else: raise Exception( "Can't deal with files that have three more type_ different geometry types, or less than one: " + str(types)) return types, type_
def get_layer_info(layer): metadata = {} extent = layer.GetExtent() crs = layer.GetSpatialRef().ExportToProj4() bounds = {'left': extent[0], 'right': extent[1], 'bottom': extent[2], 'top': extent[3]} metadata['crs'] = crs metadata['nativeBounds'] = bounds metadata['type_'] = 'vector' metadata['bounds'] = from_bounds_to_geojson(bounds, crs) metadata['featureCount'] = layer.GetFeatureCount() definition = layer.GetLayerDefn() count = definition.GetFieldCount() metadata['geomType'] = ogr.GeometryTypeToName(definition.GetGeomType()) metadata['layerFields'] = [get_field_info(definition.GetFieldDefn(i)) for i in range(count)] return metadata
def extractDataFromFile(daKmlfile): lineOfFile, dateOfFile = extractLineDate(os.path.basename(daKmlfile)) driver = ogr.GetDriverByName('KML') try: dataSource = driver.Open(daKmlfile) except Exception as e: logging.error(e) if dataSource is None: logging.error('Could not open %s' % (daKmlfile)) return False, False else: logging.debug('Opened %s' % (daKmlfile)) data_records_lines = [] data_records_stop = [] for kml_lyr in dataSource: layerName = kml_lyr.GetName() lyr_def = kml_lyr.GetGeomType() # logging.info("For the file %s and the layer %s , the geometry is %s" % (daKmlfile,layerName,ogr.GeometryTypeToName(lyr_def))) layerTypeGeom = ogr.GeometryTypeToName(kml_lyr.GetGeomType()) featureCount = kml_lyr.GetFeatureCount() logging.debug("Number of features in %s: %d" % (layerName, featureCount)) for feat in kml_lyr: data_values = {} record = feat.items() data_values['geom'] = feat.GetGeometryRef().ExportToWkt() data_values['name'] = record['Name'] data_values['description'] = record['Description'] data_values['layer'] = layerName data_values['line'] = lineOfFile data_values['date'] = dateOfFile if lyr_def == ogr.wkbLineString or lyr_def == ogr.wkbMultiLineString: data_records_lines.append(data_values) elif lyr_def == ogr.wkbPoint or lyr_def == ogr.wkbPoint25D: data_records_stop.append(data_values) return data_records_lines, data_records_stop
def setter(self, srlzr, value): datafile, metafile = env.file_upload.get_filename(value['id']) encoding = value.get('encoding', 'utf-8') iszip = zipfile.is_zipfile(datafile) try: if iszip: ogrfn = tempfile.mkdtemp() zipfile.ZipFile(datafile, 'r').extractall(path=ogrfn) else: ogrfn = datafile if six.PY2: with _set_encoding(encoding) as sdecode: ogrds = ogr.Open(ogrfn) recode = sdecode else: # Ignore encoding option in Python 3 ogrds = ogr.Open(ogrfn) def recode(x): return x if ogrds is None: raise VE(_("GDAL library failed to open file.")) drivername = ogrds.GetDriver().GetName() if drivername not in ('ESRI Shapefile', 'GeoJSON', 'KML'): raise VE(_("Unsupport OGR driver: %s.") % drivername) ogrlayer = self._ogrds(ogrds) geomtype = ogrlayer.GetGeomType() if geomtype not in _GEOM_OGR_2_TYPE: raise VE(_("Unsupported geometry type: '%s'. Probable reason: data contain mixed geometries.") % ( # NOQA: E501 ogr.GeometryTypeToName(geomtype) if geomtype is not None else None)) self._ogrlayer(srlzr.obj, ogrlayer, recode) finally: if iszip: shutil.rmtree(ogrfn)
def retrieve_thematic_information(self, roi_link_field, attributes = []): self.roi_id = roi_link_field self.thematic_info = dict() roi_ds = ogr.Open(self.roi_src) roi_ly = roi_ds.GetLayer(0) link_idx = roi_ly.GetLayerDefn().GetFieldIndex(self.roi_id) attrs = ogr_utils.retrieve_attribute_properties(roi_ly, attributes) for ft in roi_ly: gm = ft.GetGeometryRef() fid = ft.GetFID() self.thematic_info[fid] = dict() self.thematic_info[fid][self.roi_id] = ft.GetField(link_idx) if ogr.GeometryTypeToName(gm.GetGeometryType()).lower() == 'point': self.thematic_info[fid]['x'] = gm.GetX() self.thematic_info[fid]['y'] = gm.GetY() else: #if ogr.GeometryTypeToName(gm.GetGeometryType()).lower() == 'polygon': self.thematic_info[fid]['x'] = gm.Centroid().GetX() self.thematic_info[fid]['y'] = gm.Centroid().GetY() added_attr_values = dict() for attr_name, attr_idx, attr_type in attrs: # finding suitable data type for current attribute if attr_type.lower() == 'integer': val = ft.GetFieldAsInteger(attr_idx) elif attr_type.lower() == 'real': val = ft.GetFieldAsDouble(attr_idx) elif attr_type.lower() == 'date': val = ft.GetFieldAsDateTime(attr_idx) else: val = ft.GetFieldAsString(attr_idx) added_attr_values[attr_name] = val if self.thematic_info[fid].has_key(attr_name): continue else: self.thematic_info[fid][attr_name] = val self.thematic_info[fid]['attributes'] = added_attr_values
def setter(self, srlzr, value): if srlzr.obj.id is not None: raise ValidationError( "Source parameter does not apply to update vector layer.") datafile, metafile = env.file_upload.get_filename(value['id']) encoding = value.get('encoding', 'utf-8') iszip = zipfile.is_zipfile(datafile) ogrfn = ('/vsizip/{%s}' % datafile) if iszip else datafile if six.PY2: with _set_encoding(encoding) as sdecode: ogrds = ogr.Open(ogrfn, 0) recode = sdecode else: # Ignore encoding option in Python 3 ogrds = ogr.Open(ogrfn, 0) def recode(x): return x if ogrds is None: raise VE(_("GDAL library failed to open file.")) drivername = ogrds.GetDriver().GetName() if drivername not in ('ESRI Shapefile', 'GeoJSON', 'KML', 'GML'): raise VE(_("Unsupport OGR driver: %s.") % drivername) ogrlayer = self._ogrds(ogrds) geomtype = ogrlayer.GetGeomType() if geomtype not in _GEOM_OGR_2_TYPE: raise VE( _("Unsupported geometry type: '%s'. Probable reason: data contain mixed geometries." ) % ( # NOQA: E501 ogr.GeometryTypeToName(geomtype) if geomtype is not None else None)) self._ogrlayer(srlzr.obj, ogrlayer, recode)
def ogr_add_feature(ds, src, name=None): """ Creates OGR.Feature objects in OGR.Layer object. .. versionadded:: 0.7.0 OGR.Features are built from numpy src points or polygons. OGR.Features 'FID' and 'index' corresponds to source data element Parameters ---------- ds : OGR.DataSource object src : :func:`numpy:numpy.array` source data name : string name of wanted Layer """ if name is not None: lyr = ds.GetLayerByName(name) else: lyr = ds.GetLayer() defn = lyr.GetLayerDefn() geom_name = ogr.GeometryTypeToName(lyr.GetGeomType()) fields = [ defn.GetFieldDefn(i).GetName() for i in range(defn.GetFieldCount()) ] feat = ogr.Feature(defn) for index, src_item in enumerate(src): geom = numpy_to_ogr(src_item, geom_name) if 'index' in fields: feat.SetField('index', index) feat.SetGeometry(geom) lyr.CreateFeature(feat)
def ogrinfo(readonly=False, verbose=True, summaryonly=False, fetch_fid=ogr.NullFID, where=None, datasource_name=None, layers=None, spatial_filter=None, repeat_count=1, all_layers=False, sql_statement=None, dialect=None, options={}, geomfield=None): global bVerbose global bSummaryOnly global nFetchFID bReadOnly = readonly bVerbose = verbose bSummaryOnly = summaryonly nFetchFID = fetch_fid pszWHERE = where pszDataSource = datasource_name bReadOnly = readonly papszLayers = layers poSpatialFilter = spatial_filter nRepeatCount = repeat_count bAllLayers = all_layers pszSQLStatement = sql_statement pszDialect = dialect pszGeomField = geomfield #/* -------------------------------------------------------------------- */ #/* Open data source. */ #/* -------------------------------------------------------------------- */ poDS = None poDriver = None poDS = ogr.Open(pszDataSource, not bReadOnly) if poDS is None and not bReadOnly: poDS = ogr.Open(pszDataSource, False) if poDS is not None and bVerbose: print("Had to open data source read-only.") bReadOnly = True #/* -------------------------------------------------------------------- */ #/* Report failure */ #/* -------------------------------------------------------------------- */ if poDS is None: print("FAILURE:\n" "Unable to open datasource `%s' with the following drivers." % pszDataSource) for iDriver in range(ogr.GetDriverCount()): print(" -> %s" % ogr.GetDriver(iDriver).GetName()) return 1 poDriver = poDS.GetDriver() #/* -------------------------------------------------------------------- */ #/* Some information messages. */ #/* -------------------------------------------------------------------- */ if bVerbose: print("INFO: Open of `%s'\n" " using driver `%s' successful." % (pszDataSource, poDriver.GetName())) poDS_Name = poDS.GetName() if str(type(pszDataSource)) == "<type 'unicode'>" and str( type(poDS_Name)) == "<type 'str'>": poDS_Name = str(poDS_Name, "utf8") if bVerbose and pszDataSource != poDS_Name: print("INFO: Internal data source name `%s'\n" " different from user name `%s'." % (poDS_Name, pszDataSource)) #/* -------------------------------------------------------------------- */ #/* Special case for -sql clause. No source layers required. */ #/* -------------------------------------------------------------------- */ if pszSQLStatement is not None: poResultSet = None nRepeatCount = 0 #// skip layer reporting. if papszLayers is not None: print("layer names ignored in combination with -sql.") if pszGeomField is None: poResultSet = poDS.ExecuteSQL(pszSQLStatement, poSpatialFilter, pszDialect) else: poResultSet = poDS.ExecuteSQL(pszSQLStatement, None, pszDialect) if poResultSet is not None: if pszWHERE is not None: if poResultSet.SetAttributeFilter(pszWHERE) != 0: print("FAILURE: SetAttributeFilter(%s) failed." % pszWHERE) return 1 if pszGeomField is not None: ReportOnLayer(poResultSet, None, pszGeomField, poSpatialFilter, options) else: ReportOnLayer(poResultSet, None, None, None, options) poDS.ReleaseResultSet(poResultSet) #gdal.Debug( "OGR", "GetLayerCount() = %d\n", poDS.GetLayerCount() ) for iRepeat in range(nRepeatCount): if papszLayers is None: #/* -------------------------------------------------------------------- */ #/* Process each data source layer. */ #/* -------------------------------------------------------------------- */ for iLayer in range(poDS.GetLayerCount()): poLayer = poDS.GetLayer(iLayer) if poLayer is None: print("FAILURE: Couldn't fetch advertised layer %d!" % iLayer) return 1 if not bAllLayers: line = "%d: %s" % (iLayer + 1, poLayer.GetLayerDefn().GetName()) nGeomFieldCount = poLayer.GetLayerDefn().GetGeomFieldCount( ) if nGeomFieldCount > 1: line = line + " (" for iGeom in range(nGeomFieldCount): if iGeom > 0: line = line + ", " poGFldDefn = poLayer.GetLayerDefn( ).GetGeomFieldDefn(iGeom) line = line + "%s" % ogr.GeometryTypeToName( poGFldDefn.GetType()) line = line + ")" if poLayer.GetLayerDefn().GetGeomType() != ogr.wkbUnknown: line = line + " (%s)" % ogr.GeometryTypeToName( poLayer.GetLayerDefn().GetGeomType()) print(line) else: if iRepeat != 0: poLayer.ResetReading() ReportOnLayer(poLayer, pszWHERE, pszGeomField, poSpatialFilter, options) else: #/* -------------------------------------------------------------------- */ #/* Process specified data source layers. */ #/* -------------------------------------------------------------------- */ for papszIter in papszLayers: poLayer = poDS.GetLayerByName(papszIter) if poLayer is None: print("FAILURE: Couldn't fetch requested layer %s!" % papszIter) return 1 if iRepeat != 0: poLayer.ResetReading() ReportOnLayer(poLayer, pszWHERE, pszGeomField, poSpatialFilter, options) #/* -------------------------------------------------------------------- */ #/* Close down. */ #/* -------------------------------------------------------------------- */ poDS.Destroy() return 0
# 若存在先前的结果文件,删除 if ds.GetLayer('pl_buffer'): ds.DeleteLayer('pl_buffer') if ds.GetLayer('intersect_buffer'): ds.DeleteLayer('intersect_buffer') # 构建缓冲区与相交宗地图层,设置其为与宗地图层相同的投影信息,图层类型为面图层 pl_buffer = ds.CreateLayer('pl_buffer', parcels.GetSpatialRef(), ogr.wkbPolygon) intersect_buffer = ds.CreateLayer('intersect_buffer', parcels.GetSpatialRef(), ogr.wkbPolygon) # 采用与宗地图层相同的图层描述 pl_buffer_defn = parcels.GetLayerDefn() intersect_defn = parcels.GetLayerDefn pl_buffer_feat = ogr.Feature(pl_buffer_defn) intersect_feat = ogr.Feature(pl_buffer_defn) print(ogr.GeometryTypeToName(pl_buffer.GetGeomType())) # 生成电力线的250缓冲区 for pl_feat in powerLine: buff_geom = pl_feat.geometry().Buffer(250) pl_buffer_feat.SetGeometry(buff_geom) # 将生成缓冲区字段与电力线保持一致,确保其对应性 for i in range(pl_feat.GetFieldCount()): value = pl_feat.GetField(i) pl_buffer_feat.SetField(i, value) pl_buffer.CreateFeature(pl_buffer_feat) # 将生成缓冲区与宗地相交 for parcels_feat in parcels: pl_buffer_geom = pl_buffer_feat.geometry() buff_geom2 = parcels_feat.geometry().Intersection(pl_buffer_geom)
#check if layers the picked geometry type (ignore 3D flag) if pOgrLayer.GetGeomType() != intGeometryTypeRef: if ((pOgrLayer.GetGeomType() == ogr.wkbPolygon) or (pOgrLayer.GetGeomType() == ogr.wkbPolygon25D)) and ((intGeometryTypeRef == ogr.wkbPolygon) or (intGeometryTypeRef == ogr.wkbPolygon25D)) \ or ((pOgrLayer.GetGeomType() == ogr.wkbLineString) or (pOgrLayer.GetGeomType() == ogr.wkbLineString25D)) and ((intGeometryTypeRef == ogr.wkbLineString) or (intGeometryTypeRef == ogr.wkbLineString25D)) \ or ((pOgrLayer.GetGeomType() == ogr.wkbPoint) or (pOgrLayer.GetGeomType() == ogr.wkbPoint25D)) and ((intGeometryTypeRef == ogr.wkbPoint) or (intGeometryTypeRef == ogr.wkbPoint25D)) : pass else: if (not bFlagGeomTFilter): #print 'Error: shapefiles must have the same geometry type.' #print '\t' + os.path.basename(lsFilenames[0]) + ': ' + ogr.GeometryTypeToName(intGeometryTypeRef).upper() #print '\t' + os.path.basename(lsFilenames[i]) + ': ' + ogr.GeometryTypeToName(pOgrLayer.GetGeomType()).upper() #sys.exit(1) print 'Warning: ' + os.path.basename( strFile ) + ' type ' + ogr.GeometryTypeToName( pOgrLayer.GetGeomType() ).upper( ) + ' unfits first file type ' + ogr.GeometryTypeToName( intGeometryTypeRef).upper() + ' (' + os.path.basename( lsFilenames[bGeomTypeRefIsSet]) + '), skipping.' continue if ((not bFlagUseExistingSfields) and bFlagAddSourcefields): # check for "source fields" in current shapefile to eventually rename them while ((pOgrLayerSchema.GetFieldIndex(strFilenameFieldname) != -1) or (pOgrLayerSchema.GetFieldIndex(strFidFieldname) != -1)): j = j + 1 strSuffix = '_' + str(j) strFilenameFieldname = strFilenameFieldname[:( 10 - len(strSuffix))] + strSuffix strFidFieldname = strFidFieldname[:( 10 - len(strSuffix))] + strSuffix
def ReportOnLayer(poLayer, pszWHERE, pszGeomField, poSpatialFilter, options): poDefn = poLayer.GetLayerDefn() # -------------------------------------------------------------------- # Set filters if provided. # -------------------------------------------------------------------- if pszWHERE is not None: if poLayer.SetAttributeFilter(pszWHERE) != 0: print("FAILURE: SetAttributeFilter(%s) failed." % pszWHERE) return if poSpatialFilter is not None: if pszGeomField is not None: iGeomField = poLayer.GetLayerDefn().GetGeomFieldIndex(pszGeomField) if iGeomField >= 0: poLayer.SetSpatialFilter(iGeomField, poSpatialFilter) else: print("WARNING: Cannot find geometry field %s." % pszGeomField) else: poLayer.SetSpatialFilter(poSpatialFilter) # -------------------------------------------------------------------- # Report various overall information. # -------------------------------------------------------------------- print("") print("Layer name: %s" % poDefn.GetName()) if bVerbose: nGeomFieldCount = poLayer.GetLayerDefn().GetGeomFieldCount() if nGeomFieldCount > 1: for iGeom in range(nGeomFieldCount): poGFldDefn = poLayer.GetLayerDefn().GetGeomFieldDefn(iGeom) print("Geometry (%s): %s" % (poGFldDefn.GetNameRef(), ogr.GeometryTypeToName(poGFldDefn.GetType()))) else: print("Geometry: %s" % ogr.GeometryTypeToName(poDefn.GetGeomType())) print("Feature Count: %d" % poLayer.GetFeatureCount()) if nGeomFieldCount > 1: for iGeom in range(nGeomFieldCount): poGFldDefn = poLayer.GetLayerDefn().GetGeomFieldDefn(iGeom) oExt = poLayer.GetExtent(True, geom_field=iGeom, can_return_null=True) if oExt is not None: print("Extent (%s): (%f, %f) - (%f, %f)" % (poGFldDefn.GetNameRef(), oExt[0], oExt[2], oExt[1], oExt[3])) else: oExt = poLayer.GetExtent(True, can_return_null=True) if oExt is not None: print("Extent: (%f, %f) - (%f, %f)" % (oExt[0], oExt[2], oExt[1], oExt[3])) if nGeomFieldCount > 1: for iGeom in range(nGeomFieldCount): poGFldDefn = poLayer.GetLayerDefn().GetGeomFieldDefn(iGeom) if poGFldDefn.GetSpatialRef() is None: pszWKT = "(unknown)" else: pszWKT = poGFldDefn.GetSpatialRef().ExportToPrettyWkt() print("SRS WKT (%s):\n%s" % (poGFldDefn.GetNameRef(), pszWKT)) else: if poLayer.GetSpatialRef() is None: pszWKT = "(unknown)" else: pszWKT = poLayer.GetSpatialRef().ExportToPrettyWkt() print("Layer SRS WKT:\n%s" % pszWKT) if len(poLayer.GetFIDColumn()) > 0: print("FID Column = %s" % poLayer.GetFIDColumn()) if nGeomFieldCount > 1: for iGeom in range(nGeomFieldCount): poGFldDefn = poLayer.GetLayerDefn().GetGeomFieldDefn(iGeom) print("Geometry Column %d = %s" % (iGeom + 1, poGFldDefn.GetNameRef())) else: if len(poLayer.GetGeometryColumn()) > 0: print("Geometry Column = %s" % poLayer.GetGeometryColumn()) for iAttr in range(poDefn.GetFieldCount()): poField = poDefn.GetFieldDefn(iAttr) print( "%s: %s (%d.%d)" % ( \ poField.GetNameRef(), \ poField.GetFieldTypeName( poField.GetType() ), \ poField.GetWidth(), \ poField.GetPrecision() )) # -------------------------------------------------------------------- # Read, and dump features. # -------------------------------------------------------------------- poFeature = None if nFetchFID == ogr.NullFID and not bSummaryOnly: poFeature = poLayer.GetNextFeature() while poFeature is not None: DumpReadableFeature(poFeature, options) poFeature = poLayer.GetNextFeature() elif nFetchFID != ogr.NullFID: poFeature = poLayer.GetFeature(nFetchFID) if poFeature is None: print("Unable to locate feature id %d on this layer." % nFetchFID) else: DumpReadableFeature(poFeature, options) return
print('Dataset driver is: {n}\n'.format(n=driver.name)) ### How many layers are contained in this Shapefile? layer_count = dataset.GetLayerCount() print('The shapefile has {n} layer(s)\n'.format(n=layer_count)) ### What is the name of the 1 layer? layer = dataset.GetLayerByIndex(0) print('The layer is named: {n}\n'.format(n=layer.GetName())) ### What is the layer's geometry? is it a point? a polyline? a polygon? # First read in the geometry - but this is the enumerated type's value geometry = layer.GetGeomType() # So we need to translate it to the name of the enum geometry_name = ogr.GeometryTypeToName(geometry) print("The layer's geometry is: {geom}\n".format(geom=geometry_name)) ### What is the layer's projection? # Get the spatial reference spatial_ref = layer.GetSpatialRef() # Export this spatial reference to something we can read... like the Proj4 proj4 = spatial_ref.ExportToProj4() print('Layer projection is: {proj4}\n'.format(proj4=proj4)) ### How many features are in the layer? feature_count = layer.GetFeatureCount() print('Layer has {n} features\n'.format(n=feature_count)) ### How many fields are in the shapefile, and what are their names?
def main(argv=None): global bReadOnly global bVerbose global bSummaryOnly global nFetchFID global papszOptions pszWHERE = None pszDataSource = None papszLayers = None poSpatialFilter = None nRepeatCount = 1 bAllLayers = False pszSQLStatement = None pszDialect = None options = {} pszGeomField = None if argv is None: argv = sys.argv argv = ogr.GeneralCmdLineProcessor(argv) # -------------------------------------------------------------------- # Processing command line arguments. # -------------------------------------------------------------------- if argv is None: return 1 nArgc = len(argv) iArg = 1 while iArg < nArgc: if EQUAL(argv[iArg], "--utility_version"): print("%s is running against GDAL %s" % (argv[0], gdal.VersionInfo("RELEASE_NAME"))) return 0 elif EQUAL(argv[iArg], "-ro"): bReadOnly = True elif EQUAL(argv[iArg], "-q") or EQUAL(argv[iArg], "-quiet"): bVerbose = False elif EQUAL(argv[iArg], "-fid") and iArg < nArgc - 1: iArg = iArg + 1 nFetchFID = int(argv[iArg]) elif EQUAL(argv[iArg], "-spat") and iArg + 4 < nArgc: oRing = ogr.Geometry(ogr.wkbLinearRing) oRing.AddPoint(float(argv[iArg + 1]), float(argv[iArg + 2])) oRing.AddPoint(float(argv[iArg + 1]), float(argv[iArg + 4])) oRing.AddPoint(float(argv[iArg + 3]), float(argv[iArg + 4])) oRing.AddPoint(float(argv[iArg + 3]), float(argv[iArg + 2])) oRing.AddPoint(float(argv[iArg + 1]), float(argv[iArg + 2])) poSpatialFilter = ogr.Geometry(ogr.wkbPolygon) poSpatialFilter.AddGeometry(oRing) iArg = iArg + 4 elif EQUAL(argv[iArg], "-geomfield") and iArg < nArgc - 1: iArg = iArg + 1 pszGeomField = argv[iArg] elif EQUAL(argv[iArg], "-where") and iArg < nArgc - 1: iArg = iArg + 1 pszWHERE = argv[iArg] elif EQUAL(argv[iArg], "-sql") and iArg < nArgc - 1: iArg = iArg + 1 pszSQLStatement = argv[iArg] elif EQUAL(argv[iArg], "-dialect") and iArg < nArgc - 1: iArg = iArg + 1 pszDialect = argv[iArg] elif EQUAL(argv[iArg], "-rc") and iArg < nArgc - 1: iArg = iArg + 1 nRepeatCount = int(argv[iArg]) elif EQUAL(argv[iArg], "-al"): bAllLayers = True elif EQUAL(argv[iArg], "-so") or EQUAL(argv[iArg], "-summary"): bSummaryOnly = True elif len(argv[iArg]) > 8 and EQUAL(argv[iArg][0:8], "-fields="): options['DISPLAY_FIELDS'] = argv[iArg][7:len(argv[iArg])] elif len(argv[iArg]) > 6 and EQUAL(argv[iArg][0:6], "-geom="): options['DISPLAY_GEOMETRY'] = argv[iArg][6:len(argv[iArg])] elif argv[iArg][0] == '-': return Usage() elif pszDataSource is None: pszDataSource = argv[iArg] else: if papszLayers is None: papszLayers = [] papszLayers.append(argv[iArg]) bAllLayers = False iArg = iArg + 1 if pszDataSource is None: return Usage() # -------------------------------------------------------------------- # Open data source. # -------------------------------------------------------------------- poDS = None poDriver = None poDS = ogr.Open(pszDataSource, not bReadOnly) if poDS is None and not bReadOnly: poDS = ogr.Open(pszDataSource, False) if poDS is not None and bVerbose: print("Had to open data source read-only.") bReadOnly = True # -------------------------------------------------------------------- # Report failure. # -------------------------------------------------------------------- if poDS is None: print("FAILURE:\n" "Unable to open datasource `%s' with the following drivers." % pszDataSource) for iDriver in range(ogr.GetDriverCount()): print(" -> %s" % ogr.GetDriver(iDriver).GetName()) return 1 poDriver = poDS.GetDriver() # -------------------------------------------------------------------- # Some information messages. # -------------------------------------------------------------------- if bVerbose: print("INFO: Open of `%s'\n" " using driver `%s' successful." % (pszDataSource, poDriver.GetName())) poDS_Name = poDS.GetName() if str(type(pszDataSource)) == "<type 'unicode'>" and str( type(poDS_Name)) == "<type 'str'>": poDS_Name = poDS_Name.decode("utf8") if bVerbose and pszDataSource != poDS_Name: print("INFO: Internal data source name `%s'\n" " different from user name `%s'." % (poDS_Name, pszDataSource)) # -------------------------------------------------------------------- # Special case for -sql clause. No source layers required. # -------------------------------------------------------------------- if pszSQLStatement is not None: poResultSet = None nRepeatCount = 0 #// skip layer reporting. if papszLayers is not None: print("layer names ignored in combination with -sql.") if pszGeomField is None: poResultSet = poDS.ExecuteSQL(pszSQLStatement, poSpatialFilter, pszDialect) else: poResultSet = poDS.ExecuteSQL(pszSQLStatement, None, pszDialect) if poResultSet is not None: if pszWHERE is not None: if poResultSet.SetAttributeFilter(pszWHERE) != 0: print("FAILURE: SetAttributeFilter(%s) failed." % pszWHERE) return 1 if pszGeomField is not None: ReportOnLayer(poResultSet, None, pszGeomField, poSpatialFilter, options) else: ReportOnLayer(poResultSet, None, None, None, options) poDS.ReleaseResultSet(poResultSet) #gdal.Debug( "OGR", "GetLayerCount() = %d\n", poDS.GetLayerCount() ) for iRepeat in range(nRepeatCount): if papszLayers is None: # -------------------------------------------------------------------- # Process each data source layer. # -------------------------------------------------------------------- for iLayer in range(poDS.GetLayerCount()): poLayer = poDS.GetLayer(iLayer) if poLayer is None: print("FAILURE: Couldn't fetch advertised layer %d!" % iLayer) return 1 if not bAllLayers: line = "%d: %s" % (iLayer + 1, poLayer.GetLayerDefn().GetName()) nGeomFieldCount = poLayer.GetLayerDefn().GetGeomFieldCount( ) if nGeomFieldCount > 1: line = line + " (" for iGeom in range(nGeomFieldCount): if iGeom > 0: line = line + ", " poGFldDefn = poLayer.GetLayerDefn( ).GetGeomFieldDefn(iGeom) line = line + "%s" % ogr.GeometryTypeToName( poGFldDefn.GetType()) line = line + ")" if poLayer.GetLayerDefn().GetGeomType() != ogr.wkbUnknown: line = line + " (%s)" % ogr.GeometryTypeToName( poLayer.GetLayerDefn().GetGeomType()) print(line) else: if iRepeat != 0: poLayer.ResetReading() ReportOnLayer(poLayer, pszWHERE, pszGeomField, poSpatialFilter, options) else: # -------------------------------------------------------------------- # Process specified data source layers. # -------------------------------------------------------------------- for papszIter in papszLayers: poLayer = poDS.GetLayerByName(papszIter) if poLayer is None: print("FAILURE: Couldn't fetch requested layer %s!" % papszIter) return 1 if iRepeat != 0: poLayer.ResetReading() ReportOnLayer(poLayer, pszWHERE, pszGeomField, poSpatialFilter, options) # -------------------------------------------------------------------- # Close down. # -------------------------------------------------------------------- poDS.Destroy() return 0
def import_data(shapefile): # Extract the uploaded shapefile. fd, fname = tempfile.mkstemp(suffix=".zip") os.close(fd) f = open(fname, "wb") for chunk in shapefile.chunks(): f.write(chunk) f.close() if not zipfile.is_zipfile(fname): os.remove(fname) return "Not a valid zip archive." zip = zipfile.ZipFile(fname) required_suffixes = [".shp", ".shx", ".dbf", ".prj"] has_suffix = {} for suffix in required_suffixes: has_suffix[suffix] = False for info in zip.infolist(): suffix = os.path.splitext(info.filename)[1].lower() if suffix in required_suffixes: has_suffix[suffix] = True for suffix in required_suffixes: if not has_suffix[suffix]: zip.close() os.remove(fname) return "Archive missing required " + suffix + " file." shapefile_name = None dir_name = tempfile.mkdtemp() for info in zip.infolist(): if info.filename.endswith(".shp"): shapefile_name = info.filename dst_file = os.path.join(dir_name, info.filename) f = open(dst_file, "wb") f.write(zip.read(info.filename)) f.close() zip.close() # Open the shapefile. try: datasource = ogr.Open(os.path.join(dir_name, shapefile_name)) layer = datasource.GetLayer(0) shapefile_ok = True except: traceback.print_exc() shapefile_ok = False if not shapefile_ok: os.remove(fname) shutil.rmtree(dir_name) return "Not a valid shapefile." # Save Shapefile object to database. src_spatial_ref = layer.GetSpatialRef() geom_type = layer.GetLayerDefn().GetGeomType() geom_name = ogr.GeometryTypeToName(geom_type) shapefile = Shapefile(filename=shapefile_name, srs_wkt=src_spatial_ref.ExportToWkt(), geom_type=geom_name) shapefile.save() # Define the shapefile's attributes. attributes = [] layer_def = layer.GetLayerDefn() for i in range(layer_def.GetFieldCount()): field_def = layer_def.GetFieldDefn(i) attr = Attribute(shapefile=shapefile, name=field_def.GetName(), type=field_def.GetType(), width=field_def.GetWidth(), precision=field_def.GetPrecision()) attr.save() attributes.append(attr) # Save the Shapefile's features and attributes to disk. dst_spatial_ref = osr.SpatialReference() dst_spatial_ref.ImportFromEPSG(4326) coord_transform = osr.CoordinateTransformation(src_spatial_ref, dst_spatial_ref) for i in range(layer.GetFeatureCount()): src_feature = layer.GetFeature(i) src_geometry = src_feature.GetGeometryRef() src_geometry.Transform(coord_transform) geometry = GEOSGeometry(src_geometry.ExportToWkt()) geometry = utils.wrap_geos_geometry(geometry) geom_field = utils.calc_geometry_field(geom_name) fields = {} fields['shapefile'] = shapefile fields[geom_field] = geometry feature = Feature(**fields) feature.save() for attr in attributes: success, result = utils.get_ogr_feature_attribute( attr, src_feature) if not success: os.remove(fname) shutil.rmtree(dir_name) shapefile.delete() return result attr_value = AttributeValue(feature=feature, attribute=attr, value=result) attr_value.save() os.remove(fname) shutil.rmtree(dir_name) return None
def load_from_ogr(self, ogrlayer, strdecode): source_osr = ogrlayer.GetSpatialRef() target_osr = osr.SpatialReference() target_osr.ImportFromEPSG(self.srs_id) transform = osr.CoordinateTransformation(source_osr, target_osr) is_multi = self.geometry_type in GEOM_TYPE.is_multi has_z = self.geometry_type in GEOM_TYPE.has_z for fid, feature in enumerate(ogrlayer): geom = feature.GetGeometryRef() gtype = geom.GetGeometryType() if gtype not in GEOM_TYPE_OGR: raise ValidationError( _("Unknown geometry type: %d (%s).") % (gtype, ogr.GeometryTypeToName(gtype))) geom.Transform(transform) # Force single geometries to multi if is_multi: if gtype in (ogr.wkbPoint, ogr.wkbPoint25D): geom = ogr.ForceToMultiPoint(geom) elif gtype in (ogr.wkbLineString, ogr.wkbLineString25D): geom = ogr.ForceToMultiLineString(geom) elif gtype in (ogr.wkbPolygon, ogr.wkbPolygon25D): geom = ogr.ForceToMultiPolygon(geom) # Force Z if has_z and not geom.Is3D(): geom.Set3D(True) # Check geometry type again gtype = geom.GetGeometryType() if gtype not in GEOM_TYPE_OGR or _GEOM_OGR_2_TYPE[ gtype] != self.geometry_type: raise ValidationError( _("Unknown geometry type: %d (%s).") % (gtype, ogr.GeometryTypeToName(gtype))) fld_values = dict() for i in range(feature.GetFieldCount()): fld_type = feature.GetFieldDefnRef(i).GetType() if (not feature.IsFieldSet(i) or feature.IsFieldNull(i)): fld_value = None elif fld_type == ogr.OFTInteger: fld_value = feature.GetFieldAsInteger(i) elif fld_type == ogr.OFTInteger64: fld_value = feature.GetFieldAsInteger64(i) elif fld_type == ogr.OFTReal: fld_value = feature.GetFieldAsDouble(i) elif fld_type == ogr.OFTDate: year, month, day = feature.GetFieldAsDateTime(i)[0:3] fld_value = date(year, month, day) elif fld_type == ogr.OFTTime: hour, minute, second = feature.GetFieldAsDateTime(i)[3:6] fld_value = time(hour, minute, int(second)) elif fld_type == ogr.OFTDateTime: year, month, day, hour, minute, second, tz = \ feature.GetFieldAsDateTime(i) fld_value = datetime(year, month, day, hour, minute, int(second)) elif fld_type == ogr.OFTIntegerList: fld_value = json.dumps(feature.GetFieldAsIntegerList(i)) elif fld_type == ogr.OFTInteger64List: fld_value = json.dumps(feature.GetFieldAsInteger64List(i)) elif fld_type == ogr.OFTRealList: fld_value = json.dumps(feature.GetFieldAsDoubleList(i)) elif fld_type == ogr.OFTStringList: # TODO: encoding fld_value = json.dumps(feature.GetFieldAsStringList(i)) elif fld_type == ogr.OFTString: try: fld_value = strdecode(feature.GetFieldAsString(i)) except UnicodeDecodeError: raise ValidationError( _("It seems like declared and actual attributes " "encodings do not match. Unable to decode " "attribute #%(attr)d of feature #%(feat)d. " "Try declaring different encoding.") % dict(feat=fid, attr=i)) fld_name = strdecode(feature.GetFieldDefnRef(i).GetNameRef()) fld_values[self[fld_name].key] = fld_value obj = self.model(fid=fid, geom=ga.elements.WKBElement(bytearray( geom.ExportToWkb()), srid=self.srs_id), **fld_values) DBSession.add(obj)
def vectInfo(conf,inputs,outputs): global bReadOnly global bVerbose global bSummaryOnly global nFetchFID global papszOptions pszWHERE = None pszDataSource = None papszLayers = None poSpatialFilter = None nRepeatCount = 1 bAllLayers = False pszSQLStatement = None pszDialect = None options = {} pszSQLStatement = inputs["q"]["value"] pszDataSource = inputs["dstName"]["value"] #papszLayers.append(inputs["dsoName"]["value"]) #/* -------------------------------------------------------------------- */ #/* Open data source. */ #/* -------------------------------------------------------------------- */ poDS = None poDriver = None poDS = ogr.Open( pszDataSource, not bReadOnly ) if poDS is None and not bReadOnly: poDS = ogr.Open( pszDataSource, False ) if poDS is not None and bVerbose: print >> sys.stderr,"Had to open data source read-only." bReadOnly = True #/* -------------------------------------------------------------------- */ #/* Report failure */ #/* -------------------------------------------------------------------- */ if poDS is None: print >>sys.stderr, "FAILURE:\n"\ "Unable to open datasource `%s' with the following drivers." % pszDataSource conf["lenv"]["message"]="FAILURE:\n"\ "Unable to open datasource `%s' with the following drivers." % pszDataSource for iDriver in range(ogr.GetDriverCount()): conf["lenv"]["message"]+=" -> %s" % ogr.GetDriver(iDriver).GetName() return 4 poDriver = poDS.GetDriver() poDS_Name = poDS.GetName() if str(type(pszDataSource)) == "<type 'unicode'>" and str(type(poDS_Name)) == "<type 'str'>": poDS_Name = unicode(poDS_Name, "utf8") #/* -------------------------------------------------------------------- */ #/* Special case for -sql clause. No source layers required. */ #/* -------------------------------------------------------------------- */ if pszSQLStatement is not None: poResultSet = None nRepeatCount = 0 #// skip layer reporting. if papszLayers is not None: print >> sys.stderr, "layer names ignored in combination with -sql." poResultSet = poDS.ExecuteSQL( pszSQLStatement, poSpatialFilter, pszDialect ) if poResultSet is not None: if pszWHERE is not None: poResultSet.SetAttributeFilter( pszWHERE ) res=[] ReportOnLayer( inputs, res, poResultSet, None, None, options ) outputs["Result"]["value"]=json.dumps(res,ensure_ascii=False) poDS.ReleaseResultSet( poResultSet ) else: for iRepeat in range(nRepeatCount): if papszLayers is None: #/* -------------------------------------------------------------------- */ #/* Process each data source layer. */ #/* -------------------------------------------------------------------- */ for iLayer in range(poDS.GetLayerCount()): poLayer = poDS.GetLayer(iLayer) if poLayer is None: print( "FAILURE: Couldn't fetch advertised layer %d!" % iLayer ) return 1 if not bAllLayers: line = "%d: %s" % (iLayer+1, poLayer.GetLayerDefn().GetName()) if poLayer.GetLayerDefn().GetGeomType() != ogr.wkbUnknown: line = line + " (%s)" % ogr.GeometryTypeToName( poLayer.GetLayerDefn().GetGeomType() ) print(line) else: if iRepeat != 0: poLayer.ResetReading() res=[] ReportOnLayer( inputs, res, poLayer, pszWHERE, poSpatialFilter, options ) outputs["Result"]["value"]=json.dumps(res,ensure_ascii=False) else: #/* -------------------------------------------------------------------- */ #/* Process specified data source layers. */ #/* -------------------------------------------------------------------- */ for papszIter in papszLayers: poLayer = poDS.GetLayerByName(papszIter) if poLayer is None: print( "FAILURE: Couldn't fetch requested layer %s!" % papszIter ) return 1 if iRepeat != 0: poLayer.ResetReading() res=[] ReportOnLayer( inputs, res, poLayer, pszWHERE, poSpatialFilter, options ) outputs["Result"]["value"]=json.dumps(res,ensure_ascii=False) #/* -------------------------------------------------------------------- */ #/* Close down. */ #/* -------------------------------------------------------------------- */ poDS.Destroy() #import json #print >> sys.stderr,outputs["Result"]["value"] #outputs["Result"]["value"]=str(outputs["Result"]["value"]) return 3