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


Python core.QgsFeature方法代码示例

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


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

示例1: processAlgorithm

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFeature [as 别名]
def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.PrmInputLayer, context)
        mgrsfieldname = self.parameterAsString(parameters, self.PrmMgrsField, context)
        if not mgrsfieldname:
            msg = 'Select an MGRS field to process'
            feedback.reportError(msg)
            raise QgsProcessingException(msg)
        epsg4326 = QgsCoordinateReferenceSystem("EPSG:4326")
        (sink, dest_id) = self.parameterAsSink(
            parameters, self.PrmOutputLayer,
            context, source.fields(), QgsWkbTypes.Point, epsg4326)

        featureCount = source.featureCount()
        total = 100.0 / featureCount if featureCount else 0
        badFeatures = 0

        iterator = source.getFeatures()
        for cnt, feature in enumerate(iterator):
            if feedback.isCanceled():
                break
            m = feature[mgrsfieldname]
            try:
                m = re.sub(r'\s+', '', str(m))  # Remove all white space
                lat, lon = mgrs.toWgs(m)
            except Exception:
                # traceback.print_exc()
                badFeatures += 1
                continue
            f = QgsFeature()
            f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(lon, lat)))
            f.setAttributes(feature.attributes())
            sink.addFeature(f)
            if cnt % 100 == 0:
                feedback.setProgress(int(cnt * total))

        if badFeatures > 0:
            msg = "{} out of {} features contained MGRS coordinates".format(featureCount - badFeatures, featureCount)
            feedback.pushInfo(msg)

        return {self.PrmOutputLayer: dest_id} 
开发者ID:NationalSecurityAgency,项目名称:qgis-latlontools-plugin,代码行数:42,代码来源:mgrstogeom.py

示例2: canvasReleaseEvent

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFeature [as 别名]
def canvasReleaseEvent(self, mouseEvent):
        #results = self.identify(mouseEvent.x(), mouseEvent.y(), self.LayerSelection,[self.targetLayer],self.AllLayers)
        try:
            results = self.identify(mouseEvent.x(), mouseEvent.y(), self.LayerSelection,[self.targetLayer, self.parentInstance.sample_cursor.samplesLayer],self.AllLayers)
        except:
            results = []
        print (results)
        if len(results) > 0:
            print (results[0].mFeature.attributes())
            self.geomIdentified.emit(QgsFeature(results[0].mFeature)) 
开发者ID:enricofer,项目名称:go2mapillary,代码行数:12,代码来源:identifygeometry.py

示例3: getFeatureFromPointParameter

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFeature [as 别名]
def getFeatureFromPointParameter(qgs_point_xy):     
    feature = QgsFeature()
    fields = QgsFields()
    fields.append(QgsField('point_id', QVariant.String, '', 254, 0))
    feature.setFields(fields)
    feature.setGeometry(QgsGeometry.fromPointXY(qgs_point_xy))
    feature['point_id']="Start Point"
    return feature 
开发者ID:root676,项目名称:QNEAT3,代码行数:10,代码来源:Qneat3Utilities.py

示例4: processSource

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFeature [as 别名]
def processSource(self):
        """Iterate through each record and look for html table entries in the description
        filed and see if there are any name/value pairs that match the desired expanded
        ouput field names.
        """
        self.htmlparser.setMode(1)
        iterator = self.source.getFeatures()
        tableFields = self.htmlparser.fields()
        for feature in iterator:
            desc = "{}".format(feature[self.descField])
            self.htmlparser.clearData()
            if self.type == 0:
                self.htmlparser.feed(desc)
                self.htmlparser.close()
            elif self.type == 1:  # tag=value
                self.htmlparser.processHtmlTagValue(desc, '=')
            else:  # tag: value
                self.htmlparser.processHtmlTagValue(desc, ':')
            featureout = QgsFeature()
            featureout.setGeometry(feature.geometry())
            attr = []
            for item in self.selected:
                if item in tableFields:
                    attr.append(tableFields[item])
                else:
                    attr.append("")
            featureout.setAttributes(feature.attributes() + attr)
            self.addFeature.emit(featureout) 
开发者ID:NationalSecurityAgency,项目名称:qgis-kmltools-plugin,代码行数:30,代码来源:htmlExpansionDialog.py

示例5: add_feature

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFeature [as 别名]
def add_feature(data_provider, geom_container):
    """
    Adds a vector feature based on the geometry and point object
    :param data_provider:
    :param geom_container:
    :return: None
    :rtype: None
    """
    new_feature = q_core.QgsFeature()
    new_feature.setGeometry(geom_container)
    data_provider.addFeatures([new_feature]) 
开发者ID:gltn,项目名称:stdm,代码行数:13,代码来源:gps_tool_data_view_utils.py

示例6: createFeature

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFeature [as 别名]
def createFeature(self, geom):
        #Método para criar feição
        #Parâmetro de entrada: geom (geometria adquirida)
        if geom :
            settings = QtCore.QSettings()
            canvas = self.getIface().mapCanvas()
            layer = canvas.currentLayer() 
            tolerance = self.getTolerance(layer)
            geom = self.reprojectGeometry(geom)
            simplifyGeometry = self.simplifyGeometry(geom, tolerance)
            fields = layer.fields()
            feature = core.QgsFeature()
            feature.setGeometry(simplifyGeometry)
            feature.initAttributes(fields.count())            
            provider = layer.dataProvider()              
            for i in range(fields.count()):
                defaultClauseCandidate = provider.defaultValueClause(i)
                if defaultClauseCandidate:
                    feature.setAttribute(i, defaultClauseCandidate)
            formSuppressOnLayer = layer.editFormConfig().suppress()
            formSuppressOnSettings = self.getFormSuppressStateSettings()
            if formSuppressOnLayer == core.QgsEditFormConfig.SuppressOff or \
                (formSuppressOnLayer == core.QgsEditFormConfig.SuppressDefault \
                    and formSuppressOnSettings):
                self.addFeatureWithoutForm(layer, feature)
            else:
                self.addFeatureWithForm(layer, feature) 
开发者ID:dsgoficial,项目名称:DsgTools,代码行数:29,代码来源:acquisitionFreeController.py

示例7: createReprojectedLayer

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFeature [as 别名]
def createReprojectedLayer(layer, crs):
    """
    Creates a reprojected layer
    layer: layer used
    crs: crs used
    """
    temp = QgsVectorLayer('%s?crs=%s'% ('Multipolygon', crs.authid()), 'temp', 'memory')
    if not layer.isValid():
        raise GeoAlgorithmExecutionException('Problema ao criar camada reprojetada!')
        return None
    
    provider = temp.dataProvider()
    provider.addAttributes(layer.dataProvider().fields().toList())
    temp.updateFields()
    
    coordinateTransformer = QgsCoordinateTransform(layer.crs(), crs)
    features = []
    for feature in layer.getFeatures():
        feat = QgsFeature(feature)
        geom = feat.geometry()
        geom.transform(coordinateTransformer)
        feat.setGeometry(geom)
        features.append(feat)
        
    provider.addFeatures(features)
    
    return temp 
开发者ID:dsgoficial,项目名称:DsgTools,代码行数:29,代码来源:virtual_raster.py

示例8: insertFrameIntoQgsLayer

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFeature [as 别名]
def insertFrameIntoQgsLayer(self, layer, poly, map_index):
        """Inserts the poly into layer
        """
        provider = layer.dataProvider()

        #Creating the feature
        feature = QgsFeature()
        feature.initAttributes(1)
        feature.setAttribute(0, map_index)
        feature.setGeometry(poly)

        # Adding the feature into the file
        provider.addFeatures([feature]) 
开发者ID:dsgoficial,项目名称:DsgTools,代码行数:15,代码来源:map_index.py

示例9: to_shp

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFeature [as 别名]
def to_shp(path, any_features_list, layer_fields, crs, name, encoding, geom_type):
    if path is None:
        if geom_type == 0:
            network = QgsVectorLayer('Point?crs=' + crs.toWkt(), name, "memory")
        else:
            network = QgsVectorLayer('LineString?crs=' + crs.toWkt(), name, "memory")
    else:
        fields = QgsFields()
        for field in layer_fields:
            fields.append(field)
        file_writer = QgsVectorFileWriter(path, encoding, fields, geom_type, crs, "ESRI Shapefile")
        if file_writer.hasError() != QgsVectorFileWriter.NoError:
            print "Error when creating shapefile: ", file_writer.errorMessage()
        del file_writer
        network = QgsVectorLayer(path, name, "ogr")
    pr = network.dataProvider()
    if path is None:
        pr.addAttributes(layer_fields)
    new_features = []
    for i in any_features_list:
        new_feat = QgsFeature()
        new_feat.setFeatureId(i[0])
        new_feat.setAttributes([attr[0] for attr in i[1]])
        new_feat.setGeometry(QgsGeometry(QgsGeometry.fromWkt(str(i[2]))))
        #QgsGeometry()
        new_features.append(new_feat)
    network.startEditing()
    pr.addFeatures(new_features)
    network.commitChanges()
    return network 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:32,代码来源:utilityFunctions.py

示例10: processAlgorithm

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFeature [as 别名]
def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.PrmInputLayer, context)
        mgrs_name = self.parameterAsString(parameters, self.PrmMgrsFieldName, context).strip()
        precision = self.parameterAsInt(parameters, self.PrmMgrsPrecision, context)

        fieldsout = QgsFields(source.fields())

        if fieldsout.append(QgsField(mgrs_name, QVariant.String)) is False:
            msg = "MGRS Field Name must be unique. There is already a field named '{}'".format(mgrs_name)
            feedback.reportError(msg)
            raise QgsProcessingException(msg)

        layerCRS = source.sourceCrs()
        (sink, dest_id) = self.parameterAsSink(
            parameters, self.PrmOutputLayer,
            context, fieldsout, source.wkbType(), layerCRS)

        # The input to the mgrs conversions requires latitudes and longitudes
        # If the layer is not EPSG:4326 we need to convert it.
        epsg4326 = QgsCoordinateReferenceSystem('EPSG:4326')
        if layerCRS != epsg4326:
            transform = QgsCoordinateTransform(layerCRS, epsg4326, QgsProject.instance())

        total = 100.0 / source.featureCount() if source.featureCount() else 0

        iterator = source.getFeatures()
        for cnt, feature in enumerate(iterator):
            if feedback.isCanceled():
                break
            pt = feature.geometry().asPoint()
            if layerCRS != epsg4326:
                pt = transform.transform(pt)
            try:
                msg = mgrs.toMgrs(pt.y(), pt.x(), precision)
            except Exception:
                msg = ''
            f = QgsFeature()
            f.setGeometry(feature.geometry())
            f.setAttributes(feature.attributes() + [msg])
            sink.addFeature(f)
            if cnt % 100 == 0:
                feedback.setProgress(int(cnt * total))

        return {self.PrmOutputLayer: dest_id} 
开发者ID:NationalSecurityAgency,项目名称:qgis-latlontools-plugin,代码行数:46,代码来源:tomgrs.py

示例11: calcIsoContours

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFeature [as 别名]
def calcIsoContours(self, max_dist, interval, interpolation_raster_path):
        featurelist = []
        
        try:
            import matplotlib.pyplot as plt
        except:
            return featurelist
    
        ds_in = gdal.Open(interpolation_raster_path)
        band_in = ds_in.GetRasterBand(1)
        xsize_in = band_in.XSize
        ysize_in = band_in.YSize
    
        geotransform_in = ds_in.GetGeoTransform()
    
        srs = osr.SpatialReference()
        srs.ImportFromWkt( ds_in.GetProjectionRef() )

        raster_values = band_in.ReadAsArray(0, 0, xsize_in, ysize_in)
        raster_values[raster_values < 0] = max_dist + 1000 #necessary to produce rectangular array from raster
        #nodata values get replaced by the maximum value + 1
        
        x_pos = linspace(geotransform_in[0], geotransform_in[0] + geotransform_in[1] * raster_values.shape[1], raster_values.shape[1])
        y_pos = linspace(geotransform_in[3], geotransform_in[3] + geotransform_in[5] * raster_values.shape[0], raster_values.shape[0])
        x_grid, y_grid = meshgrid(x_pos, y_pos)        
        
        start = interval
        end = interval * ceil(max_dist/interval) +interval
    
        levels = arange(start, end, interval)
        
        fid = 0
        for current_level in nditer(levels):
            self.feedback.pushInfo("[QNEAT3Network][calcIsoContours] Calculating {}-level contours".format(current_level))
            contours = plt.contourf(x_grid, y_grid, raster_values, [0, current_level], antialiased=True)
            
            for collection in contours.collections:
                for contour_paths in collection.get_paths():                    
                    for polygon in contour_paths.to_polygons():
                        x = polygon[:,0]
                        y = polygon[:,1]

                        polylinexy_list = [QgsPointXY(i[0], i[1]) for i in zip(x,y)]
                    
                        feat = QgsFeature()
                        fields = QgsFields()
                        fields.append(QgsField('id', QVariant.Int, '', 254, 0))
                        fields.append(QgsField('cost_level', QVariant.Double, '', 20, 7))
                        feat.setFields(fields)
                        geom = QgsGeometry().fromPolylineXY(polylinexy_list)
                        feat.setGeometry(geom)
                        feat['id'] = fid
                        feat['cost_level'] = float(current_level)
                        featurelist.insert(0, feat)
                        
            fid=fid+1    
        return featurelist 
开发者ID:root676,项目名称:QNEAT3,代码行数:59,代码来源:Qneat3Framework.py

示例12: processAlgorithm

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFeature [as 别名]
def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.PrmInputLayer, context)
        srcCRS = source.sourceCrs()

        (sink, dest_id) = self.parameterAsSink(
            parameters, self.PrmOutputLayer, context, source.fields(),
            QgsWkbTypes.MultiLineString, srcCRS)

        # Set up CRS transformations
        if srcCRS != epsg4326:
            geomTo4326 = QgsCoordinateTransform(srcCRS, epsg4326, QgsProject.instance())
            toSinkCrs = QgsCoordinateTransform(epsg4326, srcCRS, QgsProject.instance())

        featureCount = source.featureCount()
        total = 100.0 / featureCount if featureCount else 0

        iterator = source.getFeatures()
        for cnt, feature in enumerate(iterator):
            if feedback.isCanceled():
                break
            try:
                if feature.geometry().isMultipart():
                    seg = feature.geometry().asMultiPolyline()
                else:
                    seg = [feature.geometry().asPolyline()]
                numseg = len(seg)
                if numseg < 1 or len(seg[0]) < 2:
                    continue

                outseg = []
                for pts in seg:
                    if srcCRS != epsg4326:
                        for x, pt in enumerate(pts):
                            pts[x] = geomTo4326.transform(pt)
                    normalizeLongitude(pts)
                    newseg = checkIdlCrossings(pts)
                    outseg.extend(newseg)
                if srcCRS != epsg4326:  # Convert each point to the output CRS
                    for y in range(len(outseg)):
                        for x, pt in enumerate(outseg[y]):
                            outseg[y][x] = toSinkCrs.transform(pt)

                f = QgsFeature()
                f.setGeometry(QgsGeometry.fromMultiPolylineXY(outseg))
                f.setAttributes(feature.attributes())
                sink.addFeature(f)

            except Exception:
                '''s = traceback.format_exc()
                feedback.pushInfo(s)'''
                pass

            if cnt % 100 == 0:
                feedback.setProgress(int(cnt * total))

        return {self.PrmOutputLayer: dest_id} 
开发者ID:NationalSecurityAgency,项目名称:qgis-shapetools-plugin,代码行数:58,代码来源:idlbreakline.py

示例13: accept

# 需要导入模块: from qgis import core [as 别名]
# 或者: from qgis.core import QgsFeature [as 别名]
def accept(self):
        try:
            distance = float(self.distLineEdit.text())
            azimuth = float(self.azimuthLineEdit.text())
            units = self.unitsComboBox.currentIndex()  # 0 km, 1 m, 2 nm, 3 miles, 4 yards, 5 ft, 6 inches, 7 cm
            start = self.checkBox.isChecked()
        except Exception:
            self.iface.messageBar().pushMessage("", tr("Either distance or azimuth were invalid"), level=Qgis.Warning, duration=4)
            return
        layer = self.iface.activeLayer()
        if layer is None:
            self.iface.messageBar().pushMessage("", tr("No point or line layer selected"), level=Qgis.Warning, duration=4)
            return

        measureFactor = conversionToMeters(units)

        distance = distance * measureFactor
        pt = self.pt
        destCRS = layer.crs()
        transform = QgsCoordinateTransform(epsg4326, destCRS, QgsProject.instance())
        if layer.wkbType() == QgsWkbTypes.Point:
            g = geod.Direct(pt.y(), pt.x(), azimuth, distance, Geodesic.LATITUDE | Geodesic.LONGITUDE)
            if start:
                ptStart = transform.transform(self.pt.x(), self.pt.y())
                feat = QgsFeature(layer.fields())
                feat.setGeometry(QgsGeometry.fromPointXY(ptStart))
                layer.addFeature(feat)
            pt = transform.transform(g['lon2'], g['lat2'])
            feat = QgsFeature(layer.fields())
            feat.setGeometry(QgsGeometry.fromPointXY(pt))
            layer.addFeature(feat)
        else:  # It will either be a LineString or MultiLineString
            maxseglen = settings.maxSegLength * 1000.0  # Needs to be in meters
            maxSegments = settings.maxSegments
            gline = geod.Line(pt.y(), pt.x(), azimuth)
            n = int(math.ceil(distance / maxseglen))
            if n > maxSegments:
                n = maxSegments
            seglen = distance / n
            pts = []
            for i in range(0, n + 1):
                s = seglen * i
                g = gline.Position(s, Geodesic.LATITUDE | Geodesic.LONGITUDE | Geodesic.LONG_UNROLL)
                ptc = transform.transform(g['lon2'], g['lat2'])
                pts.append(ptc)
            feat = QgsFeature(layer.fields())
            if layer.wkbType() == QgsWkbTypes.LineString:
                feat.setGeometry(QgsGeometry.fromPolylineXY(pts))
            else:
                feat.setGeometry(QgsGeometry.fromMultiPolylineXY([pts]))
            layer.addFeatures([feat])

        layer.updateExtents()
        self.iface.mapCanvas().refresh()
        self.close() 
开发者ID:NationalSecurityAgency,项目名称:qgis-shapetools-plugin,代码行数:57,代码来源:azDigitizer.py


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