当前位置: 首页>>代码示例>>Python>>正文


Python QGisLayers.getObjectFromUri方法代码示例

本文整理汇总了Python中processing.core.QGisLayers.QGisLayers.getObjectFromUri方法的典型用法代码示例。如果您正苦于以下问题:Python QGisLayers.getObjectFromUri方法的具体用法?Python QGisLayers.getObjectFromUri怎么用?Python QGisLayers.getObjectFromUri使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在processing.core.QGisLayers.QGisLayers的用法示例。


在下文中一共展示了QGisLayers.getObjectFromUri方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: processAlgorithm

# 需要导入模块: from processing.core.QGisLayers import QGisLayers [as 别名]
# 或者: from processing.core.QGisLayers.QGisLayers import getObjectFromUri [as 别名]
    def processAlgorithm(self, progress):
        inLayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER))
        inField = self.getParameterValue(self.INPUT_FIELD)
        targetLayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.TARGET_LAYER))
        targetField = self.getParameterValue(self.TARGET_FIELD)
        matType = self.getParameterValue(self.MATRIX_TYPE)
        nPoints = self.getParameterValue(self.NEAREST_POINTS)

        outputFile = self.getOutputValue(self.DISTANCE_MATRIX)

        if nPoints < 1:
            nPoints = len(QGisLayers.features(targetLayer))

        # prepare CSV file writer
        csvFile = open(outputFile, "wb")
        self.writer = UnicodeWriter(csvFile)

        if matType == 0:  # Linear distance matrix
            self.linearMatrix(inLayer, inField, targetLayer, targetField, matType, nPoints, progress)
        elif matType == 1:  # Standard distance matrix
            self.regularMatrix(inLayer, inField, targetLayer, targetField, nPoints, progress)
        elif matType == 2:  # Summary distance matrix
            self.linearMatrix(inLayer, inField, targetLayer, targetField, matType, nPoints, progress)

        csvFile.close()
        del self.writer
开发者ID:artfwo,项目名称:Quantum-GIS,代码行数:28,代码来源:PointDistance.py

示例2: calculateResamplingExtent

# 需要导入模块: from processing.core.QGisLayers import QGisLayers [as 别名]
# 或者: from processing.core.QGisLayers.QGisLayers import getObjectFromUri [as 别名]
 def calculateResamplingExtent(self):
     '''this method calculates the resampling extent, but it might set self.resample
     to false if, with the current layers, there is no need to resample'''
     auto = ProcessingConfig.getSetting(SagaUtils.SAGA_AUTO_RESAMPLING)
     if auto:
         first = True;
         self.inputExtentsCount = 0
         for param in self.parameters:
             if param.value:
                 if isinstance(param, ParameterRaster):
                     if isinstance(param.value, QgsRasterLayer):
                         layer = param.value
                     else:
                         layer = QGisLayers.getObjectFromUri(param.value)
                     self.addToResamplingExtent(layer, first)
                     first = False
                 if isinstance(param, ParameterMultipleInput):
                     if param.datatype == ParameterMultipleInput.TYPE_RASTER:
                         layers = param.value.split(";")
                         for layername in layers:
                             layer = QGisLayers.getObjectFromUri(layername)
                             self.addToResamplingExtent(layer, first)
                             first = False
         if self.inputExtentsCount < 2:
             self.resample = False
     else:
         self.xmin = ProcessingConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_XMIN)
         self.xmax = ProcessingConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_XMAX)
         self.ymin = ProcessingConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_YMIN)
         self.ymax = ProcessingConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_YMAX)
         self.cellsize = ProcessingConfig.getSetting(SagaUtils.SAGA_RESAMPLING_REGION_CELLSIZE)
开发者ID:alextheleritis,项目名称:QGIS,代码行数:33,代码来源:SagaAlgorithm.py

示例3: exportVectorLayer

# 需要导入模块: from processing.core.QGisLayers import QGisLayers [as 别名]
# 或者: from processing.core.QGisLayers.QGisLayers import getObjectFromUri [as 别名]
 def exportVectorLayer(self, orgFilename):
     # TODO: improve this. We are now exporting if it is not a shapefile,
     # but the functionality of v.in.ogr could be used for this.
     # We also export if there is a selection
     if not os.path.exists(orgFilename) or not orgFilename.endswith("shp"):
         layer = QGisLayers.getObjectFromUri(orgFilename, False)
         if layer:
             filename = LayerExporter.exportVectorLayer(layer)
     else:
         layer = QGisLayers.getObjectFromUri(orgFilename, False)
         if layer:
             useSelection = ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED)
             if useSelection and layer.selectedFeatureCount() != 0:
                 filename = LayerExporter.exportVectorLayer(layer)
             else:
                 filename = orgFilename
         else:
             filename = orgFilename
     destFilename = self.getTempFilename()
     self.exportedLayers[orgFilename] = destFilename
     command = "v.in.ogr"
     min_area = self.getParameterValue(self.GRASS_MIN_AREA_PARAMETER)
     command += " min_area=" + str(min_area)
     snap = self.getParameterValue(self.GRASS_SNAP_TOLERANCE_PARAMETER)
     command += " snap=" + str(snap)
     command += ' dsn="' + os.path.dirname(filename) + '"'
     command += " layer=" + os.path.basename(filename)[:-4]
     command += " output=" + destFilename
     command += " --overwrite -o"
     return command
开发者ID:artfwo,项目名称:Quantum-GIS,代码行数:32,代码来源:GrassAlgorithm.py

示例4: getSafeExportedLayers

# 需要导入模块: from processing.core.QGisLayers import QGisLayers [as 别名]
# 或者: from processing.core.QGisLayers.QGisLayers import getObjectFromUri [as 别名]
 def getSafeExportedLayers(self):
     '''Returns not the value entered by the user, but a string with semicolon-separated filenames
     which contains the data of the selected layers, but saved in a standard format (currently
     shapefiles for vector layers and GeoTiff for raster) so that they can be opened by most
     external applications.
     If there is a selection and QGIS is configured to use just the selection, if exports
     the layer even if it is already in a suitable format.
     Works only if the layer represented by the parameter value is currently loaded in QGIS.
     Otherwise, it will not perform any export and return the current value string.
     If the current value represents a layer in a suitable format, it does no export at all
     and returns that value.
     Currently, it works just for vector layer. In the case of raster layers, it returns the
     parameter value.
     The layers are exported just the first time the method is called. The method can be called
     several times and it will always return the same string, performing the export only the first time.'''
     if self.exported:
         return self.exported
     self.exported = self.value
     layers = self.value.split(";")
     if layers == None or len(layers) == 0:
         return self.value
     if self.datatype == ParameterMultipleInput.TYPE_RASTER:
         for layerfile in layers:
             layer = QGisLayers.getObjectFromUri(layerfile, False)
             if layer:
                 filename = LayerExporter.exportRasterLayer(layer)
                 self.exported = self.exported.replace(layerfile, filename)
         return self.exported
     else:
         for layerfile in layers:
             layer = QGisLayers.getObjectFromUri(layerfile, False)
             if layer:
                 filename = LayerExporter.exportVectorLayer(layer)
                 self.exported = self.exported.replace(layerfile, filename)
         return self.exported
开发者ID:alextheleritis,项目名称:QGIS,代码行数:37,代码来源:ParameterMultipleInput.py

示例5: convertUnsupportedFormats

# 需要导入模块: from processing.core.QGisLayers import QGisLayers [as 别名]
# 或者: from processing.core.QGisLayers.QGisLayers import getObjectFromUri [as 别名]
 def convertUnsupportedFormats(self, progress):
     i = 0
     progress.setText("Converting outputs")
     for out in self.outputs:
         if isinstance(out, OutputVector):
             if out.compatible is not None:
                 layer = QGisLayers.getObjectFromUri(out.compatible)
                 if layer is None: # for the case of memory layer, if the getCompatible method has been called
                     continue
                 provider = layer.dataProvider()
                 writer = out.getVectorWriter( provider.fields(), provider.geometryType(), layer.crs())
                 features = QGisLayers.features(layer)
                 for feature in features:
                     writer.addFeature(feature)
         elif isinstance(out, OutputRaster):
             if out.compatible is not None:
                 layer = QGisLayers.getObjectFromUri(out.compatible)
                 provider = layer.dataProvider()
                 writer = QgsRasterFileWriter(out.value)
                 format = self.getFormatShortNameFromFilename(out.value)
                 writer.setOutputFormat(format);
                 writer.writeRaster(layer.pipe(), layer.width(), layer.height(), layer.extent(), layer.crs())
         elif isinstance(out, OutputTable):
             if out.compatible is not None:
                 layer = QGisLayers.getObjectFromUri(out.compatible)
                 provider = layer.dataProvider()
                 writer = out.getTableWriter(provider.fields())
                 features = QGisLayers.features(layer)
                 for feature in features:
                     writer.addRecord(feature)
         progress.setPercentage(100 * i / float(len(self.outputs)))
开发者ID:alextheleritis,项目名称:QGIS,代码行数:33,代码来源:GeoAlgorithm.py

示例6: processAlgorithm

# 需要导入模块: from processing.core.QGisLayers import QGisLayers [as 别名]
# 或者: from processing.core.QGisLayers.QGisLayers import getObjectFromUri [as 别名]
    def processAlgorithm(self, progress):
        filename = self.getParameterValue(self.INPUT)
        inputLayer = QGisLayers.getObjectFromUri(filename)
        method = self.getParameterValue(self.METHOD)
        filename = self.getParameterValue(self.INTERSECT)
        selectLayer = QGisLayers.getObjectFromUri(filename)

        oldSelection = set(inputLayer.selectedFeaturesIds())
        index = spatialIndex = utils.createSpatialIndex(inputLayer)

        feat = QgsFeature()
        geom = QgsGeometry()
        selectedSet = []
        current = 0
        features = QGisLayers.features(selectLayer)
        total = 100.0 / float(len(features))
        for f in features:
            geom = QgsGeometry(f.geometry())
            intersects = index.intersects(geom.boundingBox())
            for i in intersects:
                request = QgsFeatureRequest().setFilterFid(i)
                feat = inputLayer.getFeatures(request).next()
                tmpGeom = QgsGeometry(feat.geometry())
                if geom.intersects(tmpGeom):
                    selectedSet.append(feat.id())
            current += 1
            progress.setPercentage(int(current * total))

        if method == 1:
            selectedSet = list(oldSelection.union(selectedSet))
        elif method == 2:
            selectedSet = list(oldSelection.difference(selectedSet))

        inputLayer.setSelectedFeatures(selectedSet)
        self.setOutputValue(self.OUTPUT, filename)
开发者ID:alextheleritis,项目名称:QGIS,代码行数:37,代码来源:SelectByLocation.py

示例7: getMinCoveringExtent

# 需要导入模块: from processing.core.QGisLayers import QGisLayers [as 别名]
# 或者: from processing.core.QGisLayers.QGisLayers import getObjectFromUri [as 别名]
 def getMinCoveringExtent(self):
     first = True
     found = False
     for param in self.params:
         if param.value:
             if isinstance(param, (ParameterRaster, ParameterVector)):
                 if isinstance(param.value, (QgsRasterLayer, QgsVectorLayer)):
                     layer = param.value
                 else:
                     layer = QGisLayers.getObjectFromUri(param.value)
                 if layer:
                     found = True
                     self.addToRegion(layer, first)
                     first = False
             elif isinstance(param, ParameterMultipleInput):
                 layers = param.value.split(";")
                 for layername in layers:
                     layer = QGisLayers.getObjectFromUri(layername, first)
                     if layer:
                         found = True
                         self.addToRegion(layer, first)
                         first = False
     if found:
         return str(self.xmin) + "," + str(self.xmax) + "," + str(self.ymin) + "," + str(self.ymax)
     else:
         return None
开发者ID:alextheleritis,项目名称:QGIS,代码行数:28,代码来源:ExtentSelectionPanel.py

示例8: processAlgorithm

# 需要导入模块: from processing.core.QGisLayers import QGisLayers [as 别名]
# 或者: from processing.core.QGisLayers.QGisLayers import getObjectFromUri [as 别名]
    def processAlgorithm(self, progress):
        polyLayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.POLYGONS))
        pointLayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.POINTS))
        fieldName = self.getParameterValue(self.FIELD)
        fieldIdx = pointLayer.fieldNameIndex(self.getParameterValue(self.WEIGHT))

        polyProvider = polyLayer.dataProvider()

        idxCount, fieldList = utils.findOrCreateField(polyLayer, polyLayer.pendingFields(), fieldName)

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(fieldList.toList(),
                     polyProvider.geometryType(), polyProvider.crs())

        spatialIndex = utils.createSpatialIndex(pointLayer)

        ftPoint = QgsFeature()
        outFeat = QgsFeature()
        geom = QgsGeometry()

        current = 0
        hasIntersections = False

        features = QGisLayers.features(polyLayer)
        total = 100.0 / float(len(features))
        for ftPoly in features:
            geom = ftPoly.geometry()
            attrs = ftPoly.attributes()

            count = 0
            hasIntersections = False
            points = spatialIndex.intersects(geom.boundingBox())
            if len(points) > 0:
                hasIntersections = True

            if hasIntersections:
                progress.setText(str(len(points)))
                for i in points:
                    request = QgsFeatureRequest().setFilterFid(i)
                    ftPoint = pointLayer.getFeatures(request).next()
                    tmpGeom = QgsGeometry(ftPoint.geometry())
                    if geom.contains(tmpGeom):
                        weight = str(ftPoint.attributes()[fieldIdx])
                        try:
                            count += float(weight)
                        except:
                            pass #ignore fields with non-numeric values

            outFeat.setGeometry(geom)
            if idxCount == len(attrs):
                attrs.append(count)
            else:
                attrs[idxCount] =  count
            outFeat.setAttributes(attrs)
            writer.addFeature(outFeat)

            current += 1
            progress.setPercentage(int(current * total))

        del writer
开发者ID:alextheleritis,项目名称:QGIS,代码行数:61,代码来源:PointsInPolygonWeighted.py

示例9: processAlgorithm

# 需要导入模块: from processing.core.QGisLayers import QGisLayers [as 别名]
# 或者: from processing.core.QGisLayers.QGisLayers import getObjectFromUri [as 别名]
    def processAlgorithm(self, progress):
        layerA = QGisLayers.getObjectFromUri(self.getParameterValue(Difference.INPUT))
        layerB = QGisLayers.getObjectFromUri(self.getParameterValue(Difference.OVERLAY))

        GEOS_EXCEPT = True

        FEATURE_EXCEPT = True

        writer = self.getOutputFromName(Difference.OUTPUT).getVectorWriter(layerA.pendingFields(),
                     layerA.dataProvider().geometryType(), layerA.dataProvider().crs())

        inFeatA = QgsFeature()
        inFeatB = QgsFeature()
        outFeat = QgsFeature()

        index = utils.createSpatialIndex(layerB)

        selectionA = QGisLayers.features(layerA)

        current = 0
        total = 100.0 / float(len(selectionA))

        for inFeatA in selectionA:
            add = True
            geom = QgsGeometry(inFeatA.geometry())
            diff_geom = QgsGeometry(geom)
            attrs = inFeatA.attributes()
            intersections = index.intersects(geom.boundingBox())
            for i in intersections:
                request = QgsFeatureRequest().setFilterFid(i)
                inFeatB = layerB.getFeatures(request).next()
                tmpGeom = QgsGeometry(inFeatB.geometry())
                try:
                    if diff_geom.intersects(tmpGeom):
                        diff_geom = QgsGeometry(diff_geom.difference(tmpGeom))
                except:
                    GEOS_EXCEPT = False
                    add = False
                    break

            if add:
                try:
                    outFeat.setGeometry(diff_geom)
                    outFeat.setAttributes(attrs)
                    writer.addFeature(outFeat)
                except:
                    FEATURE_EXCEPT = False
                    continue

            current += 1
            progress.setPercentage(int(current * total))

        del writer

        if not GEOS_EXCEPT:
            ProcessingLog.addToLog(ProcessingLog.LOG_WARNING, "Geometry exception while computing difference")
        if not FEATURE_EXCEPT:
            ProcessingLog.addToLog(ProcessingLog.LOG_WARNING, "Feature exception while computing difference")
开发者ID:alextheleritis,项目名称:QGIS,代码行数:60,代码来源:Difference.py

示例10: processAlgorithm

# 需要导入模块: from processing.core.QGisLayers import QGisLayers [as 别名]
# 或者: from processing.core.QGisLayers.QGisLayers import getObjectFromUri [as 别名]
    def processAlgorithm(self, progress):
        polyLayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.POLYGONS))
        pointLayer = QGisLayers.getObjectFromUri(self.getParameterValue(self.POINTS))
        fieldName = self.getParameterValue(self.FIELD)
        classFieldName = self.getParameterValue(self.CLASSFIELD)

        polyProvider = polyLayer.dataProvider()

        classFieldIndex = pointLayer.fieldNameIndex(classFieldName)
        idxCount, fieldList = utils.findOrCreateField(polyLayer, polyLayer.pendingFields(), fieldName)

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(
            fieldList.toList(), polyProvider.geometryType(), polyProvider.crs()
        )

        spatialIndex = utils.createSpatialIndex(pointLayer)

        ftPoint = QgsFeature()
        outFeat = QgsFeature()
        geom = QgsGeometry()

        current = 0
        hasIntersections = False

        features = QGisLayers.features(polyLayer)
        total = 100.0 / float(len(features))
        for ftPoly in features:
            geom = ftPoly.geometry()
            attrs = ftPoly.attributes()

            classes = []
            hasIntersections = False
            points = spatialIndex.intersects(geom.boundingBox())
            if len(points) > 0:
                hasIntersections = True

            if hasIntersections:
                for i in points:
                    request = QgsFeatureRequest().setFilterFid(i)
                    ftPoint = pointLayer.getFeatures(request).next()
                    tmpGeom = QgsGeometry(ftPoint.geometry())
                    if geom.contains(tmpGeom):
                        clazz = ftPoint.attributes()[classFieldIndex]
                        if not clazz in classes:
                            classes.append(clazz)

            outFeat.setGeometry(geom)
            if idxCount == len(attrs):
                attrs.append(len(classes))
            else:
                attrs[idxCount] = len(classes)
            outFeat.setAttributes(attrs)
            writer.addFeature(outFeat)

            current += 1
            progress.setPercentage(current / total)

        del writer
开发者ID:artfwo,项目名称:Quantum-GIS,代码行数:60,代码来源:PointsInPolygonUnique.py

示例11: processAlgorithm

# 需要导入模块: from processing.core.QGisLayers import QGisLayers [as 别名]
# 或者: from processing.core.QGisLayers.QGisLayers import getObjectFromUri [as 别名]
  def processAlgorithm(self, progress):

    layer1 = QGisLayers.getObjectFromUri(self.getParameterValue(self.LAYER1))
    layer2 = QGisLayers.getObjectFromUri(self.getParameterValue(self.LAYER2))

    fields = []
    layers = [layer1, layer2]
    totalfeaturecount = 0

    if (layer1.dataProvider().geometryType() != layer2.dataProvider().geometryType()):
      raise GeoAlgorithmExecutionException("Merged layers must all be same type of geometry (" + \
          mmqgisx_wkbtype_to_text(layer2.dataProvider().geometryType()) + " != " + \
          mmqgisx_wkbtype_to_text(layer2.dataProvider().geometryType()) + ")")

    for layer in layers:
      totalfeaturecount += layer.featureCount()

      # Add any fields not in the composite field list
      for sfield in layer.pendingFields():
        found = None
        for dfield in fields:
          if (dfield.name() == sfield.name()) and (dfield.type() == sfield.type()):
            found = dfield
            break

        if not found:
          fields.append(sfield)

    output = self.getOutputFromName(self.SAVENAME)
    out = output.getVectorWriter(fields, layer1.wkbType(), layer1.crs())

    # Copy layer features to output file
    featurecount = 0
    for layer in layers:
      idx = {}
      for dfield in fields:
        i = 0
        for sfield in layer.pendingFields():
          if (sfield.name() == dfield.name()) and (sfield.type() == dfield.type()):
            idx[dfield] = i
            break
          i += 1

      features = QGisLayers.features(layer)
      for feature in features:
        sattributes = feature.attributes()
        dattributes = []
        for dfield in fields:
          if (dfield in idx):
            dattributes.append(sattributes[idx[dfield]])
          else:
            dattributes.append(dfield.type())
        feature.setAttributes(dattributes)
        out.addFeature(feature)
        featurecount += 1
        progress.setPercentage(float(featurecount) / totalfeaturecount * 100)

    del out
开发者ID:alextheleritis,项目名称:QGIS,代码行数:60,代码来源:MMQGISXAlgorithms.py

示例12: processAlgorithm

# 需要导入模块: from processing.core.QGisLayers import QGisLayers [as 别名]
# 或者: from processing.core.QGisLayers.QGisLayers import getObjectFromUri [as 别名]
    def processAlgorithm(self, progress):
        input = self.getParameterValue(self.INPUT_LAYER)
        input2 = self.getParameterValue(self.INPUT_LAYER_2)
        output = self.getOutputFromName(self.OUTPUT_LAYER)
        field = self.getParameterValue(self.TABLE_FIELD)
        field2 = self.getParameterValue(self.TABLE_FIELD_2)

        # Layer 1
        layer = QGisLayers.getObjectFromUri(input)
        provider = layer.dataProvider()
        joinField1Index = layer.fieldNameIndex(field)
        # Layer 2
        layer2 = QGisLayers.getObjectFromUri(input2)
        provider2 = layer2.dataProvider()

        joinField2Index = layer2.fieldNameIndex(field2)

        # Output
        outFields = []
        outFields.extend(provider.fields())
        outFields.extend(provider2.fields())

        writer = output.getVectorWriter(outFields, provider.geometryType(), layer.crs())

        inFeat = QgsFeature()
        inFeat2 = QgsFeature()
        outFeat = QgsFeature()

        # Create output vector layer with additional attribute
        features = QGisLayers.features(layer);
        for inFeat in features:
            inGeom = inFeat.geometry()
            attrs = inFeat.attributes()
            joinValue1 = attrs[joinField1Index]
            features2 = QGisLayers.features(layer2);
            for inFeat2 in features2:
                ## Maybe it should cache this entries...
                attrs2 = inFeat2.attributes()
                joinValue2 = attrs2[joinField2Index]
                if joinValue1 == joinValue2:
                    # create the new feature
                    outFeat.setGeometry(inGeom)
                    attrs.extend(attrs2)
                    break;
            outFeat.setAttributes(attrs)
            writer.addFeature(outFeat)

        del writer
开发者ID:alextheleritis,项目名称:QGIS,代码行数:50,代码来源:JoinAttributes.py

示例13: processAlgorithm

# 需要导入模块: from processing.core.QGisLayers import QGisLayers [as 别名]
# 或者: from processing.core.QGisLayers.QGisLayers import getObjectFromUri [as 别名]
    def processAlgorithm(self, progress):
        source = self.getParameterValue(self.INPUT)
        vlayer = QGisLayers.getObjectFromUri(source)
        output = self.getOutputFromName(self.OUTPUT)
        vprovider = vlayer.dataProvider()
        fields = vprovider.fields()
        writer = output.getVectorWriter(fields, QGis.WKBPoint, self.crs)
        xfieldindex = vlayer.fieldNameIndex(self.getParameterValue(self.XFIELD))
        yfieldindex = vlayer.fieldNameIndex(self.getParameterValue(self.YFIELD))

        crsId = self.getParameterValue(self.TARGET_CRS)
        targetCrs = QgsCoordinateReferenceSystem(crsId)
        self.crs = targetCrs

        outFeat = QgsFeature()
        nElement = 0
        features = QGisLayers.features(vlayer)
        nFeat = len(features)
        for feature in features:
            nElement += 1
            progress.setPercentage((nElement*100)/nFeat)
            attrs = feature.attributes()
            try:
                x =  float(attrs[xfieldindex])
                y =  float(attrs[yfieldindex])
            except:
                continue
            pt = QgsPoint(x, y)
            outFeat.setGeometry(QgsGeometry.fromPoint(pt))
            outFeat.setAttributes(attrs)
            writer.addFeature(outFeat)

        del writer
开发者ID:alextheleritis,项目名称:QGIS,代码行数:35,代码来源:PointsLayerFromTable.py

示例14: processAlgorithm

# 需要导入模块: from processing.core.QGisLayers import QGisLayers [as 别名]
# 或者: from processing.core.QGisLayers.QGisLayers import getObjectFromUri [as 别名]
    def processAlgorithm(self, progress):
        layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT_LAYER))

        writer = self.getOutputFromName(self.OUTPUT_LAYER).getVectorWriter(
            layer.pendingFields().toList(), QGis.WKBPoint, layer.crs()
        )

        outFeat = QgsFeature()

        features = QGisLayers.features(layer)
        total = 100.0 / float(len(features))
        current = 0

        for inFeat in features:
            inGeom = inFeat.geometry()
            attrs = inFeat.attributes()

            outGeom = QgsGeometry(inGeom.centroid())
            if outGeom is None:
                raise GeoAlgorithmExecutionException("Error calculating centroid")

            outFeat.setGeometry(outGeom)
            outFeat.setAttributes(attrs)
            writer.addFeature(outFeat)
            current += 1
            progress.setPercentage(int(current * total))

        del writer
开发者ID:artfwo,项目名称:Quantum-GIS,代码行数:30,代码来源:Centroids.py

示例15: test_SagaVectorAlgorithmWithSelection

# 需要导入模块: from processing.core.QGisLayers import QGisLayers [as 别名]
# 或者: from processing.core.QGisLayers.QGisLayers import getObjectFromUri [as 别名]
 def test_SagaVectorAlgorithmWithSelection(self):
     layer = processing.getobject(polygons2());
     feature = layer.getFeatures().next()
     selected = [feature.id()]
     layer.setSelectedFeatures(selected)
     outputs=processing.runalg("saga:polygoncentroids",polygons2(),True,None)
     layer.setSelectedFeatures([])
     output=outputs['CENTROIDS']
     layer=QGisLayers.getObjectFromUri(output, True)
     fields=layer.pendingFields()
     expectednames=['ID','POLY_NUM_B','POLY_ST_B']
     expectedtypes=['Real','Real','String']
     names=[str(f.name()) for f in fields]
     types=[str(f.typeName()) for f in fields]
     self.assertEqual(expectednames, names)
     self.assertEqual(expectedtypes, types)
     features=processing.getfeatures(layer)
     self.assertEqual(1, len(features))
     feature=features.next()
     attrs=feature.attributes()
     expectedvalues=["2","1","string a"]
     values=[str(attr) for attr in attrs]
     self.assertEqual(expectedvalues, values)
     wkt='POINT(270806.69221918 4458924.97720492)'
     self.assertEqual(wkt, str(feature.geometry().exportToWkt()))
开发者ID:alextheleritis,项目名称:QGIS,代码行数:27,代码来源:SagaTest.py


注:本文中的processing.core.QGisLayers.QGisLayers.getObjectFromUri方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。