Python qgis.PyQt.QtCore.QVariant.String() Examples

The following are 23 code examples of qgis.PyQt.QtCore.QVariant.String(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module qgis.PyQt.QtCore.QVariant , or try the search function .
Example #1
Source File: pluscodes.py    From qgis-latlontools-plugin with GNU General Public License v2.0 6 votes vote down vote up
def initAlgorithm(self, config):
        self.addParameter(
            QgsProcessingParameterFeatureSource(
                self.PrmInputLayer,
                'Input vector layer or table',
                [QgsProcessing.TypeVector])
        )
        self.addParameter(
            QgsProcessingParameterField(
                self.PrmPlusCodesField,
                'Field containing Plus Code coordinate',
                defaultValue='pluscodes',
                parentLayerParameterName=self.PrmInputLayer,
                type=QgsProcessingParameterField.String)
        )
        self.addParameter(
            QgsProcessingParameterFeatureSink(
                self.PrmOutputLayer,
                'Output layer')
        ) 
Example #2
Source File: heatmapDialog.py    From qgis-d3datavis-plugin with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, iface, parent):
        """ Constructor to initialize the circular heatmap dialog box """
        super(HeatmapDialog, self).__init__(parent)
        self.setupUi(self)
        self.iface = iface
        self.canvas = iface.mapCanvas()
        self.layerComboBox.setFilters(QgsMapLayerProxyModel.VectorLayer)
        self.layerComboBox.layerChanged.connect(self.userSelectsLayer)
        self.dtComboBox.setFilters(QgsFieldProxyModel.String | QgsFieldProxyModel.Date | QgsFieldProxyModel.Time)
        self.dateComboBox.setFilters(QgsFieldProxyModel.String | QgsFieldProxyModel.Date)
        self.timeComboBox.setFilters(QgsFieldProxyModel.String | QgsFieldProxyModel.Time)
        self.categoryComboBox.setFilters(QgsFieldProxyModel.String | QgsFieldProxyModel.Numeric)
        self.dtRadioButton.clicked.connect(self.enableComponents)
        self.notdtRadioButton.clicked.connect(self.enableComponents)
        self.radialComboBox.addItems(OPTIONMENU)
        self.circleComboBox.addItems(OPTIONMENU)
        self.buttonBox.button(QDialogButtonBox.Ok).setText("Create Chart")
        self.buttonBox.button(QDialogButtonBox.Help).clicked.connect(self.help) 
Example #3
Source File: importKml.py    From qgis-kmltools-plugin with GNU General Public License v2.0 6 votes vote down vote up
def addpoint(self, feature):
        if self.cntPt == 0:
            f = QgsFields()
            f.append(QgsField("name", QVariant.String))
            f.append(QgsField("folders", QVariant.String))
            f.append(QgsField("description", QVariant.String))
            f.append(QgsField("altitude", QVariant.Double))
            f.append(QgsField("alt_mode", QVariant.String))
            f.append(QgsField("time_begin", QVariant.String))
            f.append(QgsField("time_end", QVariant.String))
            f.append(QgsField("time_when", QVariant.String))
            for item in self.extData:
                f.append(QgsField(item, QVariant.String))
            (self.sinkPt, self.dest_id_pt) = self.parameterAsSink(
                self.parameters,
                self.PrmPointOutputLayer, self.context, f,
                QgsWkbTypes.PointZ, epsg4326)

        self.cntPt += 1
        self.sinkPt.addFeature(feature) 
Example #4
Source File: importKml.py    From qgis-kmltools-plugin with GNU General Public License v2.0 6 votes vote down vote up
def addline(self, feature):
        if self.cntLine == 0:
            f = QgsFields()
            f.append(QgsField("name", QVariant.String))
            f.append(QgsField("folders", QVariant.String))
            f.append(QgsField("description", QVariant.String))
            f.append(QgsField("altitude", QVariant.Double))
            f.append(QgsField("alt_mode", QVariant.String))
            f.append(QgsField("time_begin", QVariant.String))
            f.append(QgsField("time_end", QVariant.String))
            f.append(QgsField("time_when", QVariant.String))
            for item in self.extData:
                f.append(QgsField(item, QVariant.String))
            (self.sinkLine, self.dest_id_line) = self.parameterAsSink(
                self.parameters,
                self.PrmLineOutputLayer, self.context, f,
                QgsWkbTypes.MultiLineStringZ, epsg4326)

        self.cntLine += 1
        self.sinkLine.addFeature(feature) 
Example #5
Source File: importKml.py    From qgis-kmltools-plugin with GNU General Public License v2.0 6 votes vote down vote up
def addpolygon(self, feature):
        if self.cntPoly == 0:
            f = QgsFields()
            f.append(QgsField("name", QVariant.String))
            f.append(QgsField("folders", QVariant.String))
            f.append(QgsField("description", QVariant.String))
            f.append(QgsField("altitude", QVariant.Double))
            f.append(QgsField("alt_mode", QVariant.String))
            f.append(QgsField("time_begin", QVariant.String))
            f.append(QgsField("time_end", QVariant.String))
            f.append(QgsField("time_when", QVariant.String))
            for item in self.extData:
                f.append(QgsField(item, QVariant.String))
            (self.sinkPoly, self.dest_id_poly) = self.parameterAsSink(
                self.parameters,
                self.PrmPolygonOutputLayer, self.context, f,
                QgsWkbTypes.MultiPolygonZ, epsg4326)
        self.cntPoly += 1
        self.sinkPoly.addFeature(feature) 
Example #6
Source File: splitOnDayBreakAlgorithm.py    From qgis-processing-trajectory with GNU General Public License v3.0 5 votes vote down vote up
def processAlgorithm(self, parameters, context, feedback):
        input_layer = self.parameterAsSource(parameters, self.INPUT, context)
        traj_id_field = self.parameterAsFields(parameters, self.TRAJ_ID_FIELD, context)[0]
        timestamp_field = self.parameterAsFields(parameters, self.TIMESTAMP_FIELD, context)[0]
        timestamp_format = self.parameterAsString(parameters, self.TIMESTAMP_FORMAT, context)

        output_fields = QgsFields()
        output_fields.append(QgsField(traj_id_field, QVariant.String))
        output_fields.append(QgsField('date', QVariant.DateTime))

        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
                                               output_fields,
                                               QgsWkbTypes.LineStringM,
                                               input_layer.sourceCrs())
        
        trajectories = trajectories_from_qgis_point_layer(input_layer, timestamp_field, traj_id_field, timestamp_format)
        
        for traj in trajectories:
            splitting_results = traj.split()
            for split_traj in splitting_results:
                line = QgsGeometry.fromWkt(split_traj.to_linestringm_wkt())
                f = QgsFeature()
                f.setGeometry(line)
                f.setAttributes([split_traj.id, str(split_traj.get_start_time().date())])
                sink.addFeature(f, QgsFeatureSink.FastInsert)
        
        # default return type for function
        return {self.OUTPUT: dest_id} 
Example #7
Source File: bulkDialog.py    From qgis-bulk-nominatim with GNU General Public License v2.0 5 votes vote down vote up
def createPointLayerReverse(self):
        layername = self.layerLineEdit.text()
        self.pointLayer = QgsVectorLayer("point?crs=epsg:4326", layername, "memory")
        self.provider = self.pointLayer.dataProvider()
        if self.detailedAddressCheckBox.checkState():
            self.provider.addAttributes([
                QgsField("osm_type", QVariant.String),
                QgsField("osm_id", QVariant.String),
                QgsField("display_name", QVariant.String),
                QgsField("house_number", QVariant.String),
                QgsField("road", QVariant.String),
                QgsField("neighbourhood", QVariant.String),
                QgsField("locality", QVariant.String),
                QgsField("town", QVariant.String),
                QgsField("city", QVariant.String),
                QgsField("county", QVariant.String),
                QgsField("state", QVariant.String),
                QgsField("postcode", QVariant.String),
                QgsField("country", QVariant.String),
                QgsField("country_code", QVariant.String)])
        else:
            self.provider.addAttributes([QgsField("display_name", QVariant.String)])
        self.pointLayer.updateFields()
        if self.showLabelCheckBox.checkState():
            # Display labels
            label = QgsPalLayerSettings()
            label.fieldName = 'display_name'
            label.placement= QgsPalLayerSettings.AroundPoint
            labeling = QgsVectorLayerSimpleLabeling(label)
            self.pointLayer.setLabeling(labeling)
            self.pointLayer.setLabelsEnabled(True) 
Example #8
Source File: trajectoriesFromPointLayerAlgorithm.py    From qgis-processing-trajectory with GNU General Public License v3.0 5 votes vote down vote up
def processAlgorithm(self, parameters, context, feedback):
        input_layer = self.parameterAsSource(parameters, self.INPUT, context)
        traj_id_field = self.parameterAsFields(parameters, self.TRAJ_ID_FIELD, context)[0]
        timestamp_field = self.parameterAsFields(parameters, self.TIMESTAMP_FIELD, context)[0]
        timestamp_format = self.parameterAsString(parameters, self.TIMESTAMP_FORMAT, context)
        
        output_fields = QgsFields()
        output_fields.append(QgsField(traj_id_field, QVariant.String))
        
        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
                                               output_fields, 
                                               QgsWkbTypes.LineStringM, 
                                               input_layer.sourceCrs())
        
        trajectories = trajectories_from_qgis_point_layer(input_layer, timestamp_field, traj_id_field, timestamp_format)
        
        for traj in trajectories:
            line = QgsGeometry.fromWkt(traj.to_linestringm_wkt())
            f = QgsFeature()
            f.setGeometry(line)
            f.setAttributes([traj.id])
            sink.addFeature(f, QgsFeatureSink.FastInsert)
        
        # default return type for function
        return {self.OUTPUT: dest_id} 
Example #9
Source File: clipTrajectoriesByExtentAlgorithm.py    From qgis-processing-trajectory with GNU General Public License v3.0 5 votes vote down vote up
def processAlgorithm(self, parameters, context, feedback):
        input_layer = self.parameterAsSource(parameters, self.INPUT, context)
        traj_id_field = self.parameterAsFields(parameters, self.TRAJ_ID_FIELD, context)[0]
        timestamp_field = self.parameterAsFields(parameters, self.TIMESTAMP_FIELD, context)[0]
        timestamp_format = self.parameterAsString(parameters, self.TIMESTAMP_FORMAT, context)
        extent = self.parameterAsExtent(parameters, self.EXTENT, context)
        
        output_fields = QgsFields()
        output_fields.append(QgsField(traj_id_field, QVariant.String))
        
        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
                                               output_fields, 
                                               QgsWkbTypes.LineStringM, 
                                               input_layer.sourceCrs())
        
        trajectories = trajectories_from_qgis_point_layer(input_layer, timestamp_field, traj_id_field, timestamp_format)
        
        xmin = extent.xMinimum()
        xmax = extent.xMaximum()
        ymin = extent.yMinimum()
        ymax = extent.yMaximum()
        polygon = Polygon([(xmin,ymin), (xmin,ymax), (xmax,ymax), (xmax,ymin), (xmin,ymin)])
        
        intersections = []
        for traj in trajectories:
            for intersection in traj.intersection(polygon):
                intersections.append(intersection)
            
        for traj in intersections:
            line = QgsGeometry.fromWkt(traj.to_linestringm_wkt())
            f = QgsFeature()
            f.setGeometry(line)
            f.setAttributes([traj.id])
            sink.addFeature(f, QgsFeatureSink.FastInsert)
        
        # default return type for function
        return {self.OUTPUT: dest_id} 
Example #10
Source File: validationAlgorithm.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def getFlagFields(self):
        fields = QgsFields()
        fields.append(QgsField('reason',QVariant.String))
        return fields 
Example #11
Source File: batchRunAlgorithm.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        super(BatchRunAlgorithm, self).__init__()
        self.flagSink = None
        self.flag_id = None
        self.flagFields = QgsFields()
        self.flagFields.append(
                QgsField('alg_name',QVariant.String)
            )
        self.flagFields.append(
                QgsField('layer_name',QVariant.String)
            ) 
Example #12
Source File: networkHandler.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def getFlagFields(self):
        fields = QgsFields()
        fields.append(QgsField('reason',QVariant.String))
        return fields 
Example #13
Source File: htmlExpansionDialog.py    From qgis-kmltools-plugin with GNU General Public License v2.0 5 votes vote down vote up
def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.PrmInputLayer, context)
        field = self.parameterAsString(parameters, self.PrmDescriptionField, context)
        tags = self.parameterAsString(parameters, self.PrmExpansionTags, context).strip()
        type = self.parameterAsInt(parameters, self.PrmExpansionType, context)
        feedback.pushInfo(tags)
        if not field:
            msg = tr('Must have a valid description field')
            feedback.reportError(msg)
            raise QgsProcessingException(msg)

        # Set up the HTML expansion processor
        self.htmlProcessor = HTMLExpansionProcess(source, field, type)
        self.htmlProcessor.addFeature.connect(self.addFeature)
        # Have it generate a list of all possible expansion field names
        if self.PrmExpansionTags in parameters and tags != '':
            expansionNames = [x.strip() for x in tags.split(',')]
            feedback.pushInfo('{}'.format(expansionNames))
            self.htmlProcessor.setDesiredFields(expansionNames)
        else:
            self.htmlProcessor.autoGenerateFileds()

        srcCRS = source.sourceCrs()
        wkbtype = source.wkbType()

        # Create a copy of the fields for the output
        fieldsout = QgsFields(source.fields())
        for item in self.htmlProcessor.uniqueDesiredNames(source.fields().names()):
            fieldsout.append(QgsField(item, QVariant.String))

        (self.sink, dest_id) = self.parameterAsSink(parameters,
                self.PrmOutputLayer, context, fieldsout, wkbtype, srcCRS)

        self.htmlProcessor.processSource()
        self.htmlProcessor.addFeature.disconnect(self.addFeature)
        return {self.PrmOutputLayer: dest_id} 
Example #14
Source File: htmlExpansionDialog.py    From qgis-kmltools-plugin with GNU General Public License v2.0 5 votes vote down vote up
def initAlgorithm(self, config):
        self.addParameter(
            QgsProcessingParameterFeatureSource(
                self.PrmInputLayer,
                tr('Input layer'),
                [QgsProcessing.TypeVector])
        )
        self.addParameter(
            QgsProcessingParameterField(
                self.PrmDescriptionField,
                tr('Description field'),
                defaultValue='description',
                parentLayerParameterName=self.PrmInputLayer,
                type=QgsProcessingParameterField.String
            )
        )
        self.addParameter(
            QgsProcessingParameterString(
                self.PrmExpansionTags,
                tr('Comma separated list of expansion tags - Left blank autogenerates all tags'),
                optional=True)
        )
        self.addParameter(
            QgsProcessingParameterEnum(
                self.PrmExpansionType,
                tr('How to expand the description field'),
                options=[tr('Expand from a 2 column HTML table'),
                    tr('Expand from "tag = value" pairs'),
                    tr('Expand from "tag: value" pairs')],
                defaultValue=0,
                optional=False)
        )
        self.addParameter(
            QgsProcessingParameterFeatureSink(
                self.PrmOutputLayer,
                tr('Output layer'))
        ) 
Example #15
Source File: QgsFmvLayers.py    From QGISFMV with GNU General Public License v3.0 5 votes vote down vote up
def _toQgsField(f):
    ''' Create QgsFiel '''
    if isinstance(f, QgsField):
        return f
    return QgsField(f[0], TYPE_MAP.get(f[1], QVariant.String)) 
Example #16
Source File: Qneat3Utilities.py    From QNEAT3 with GNU General Public License v3.0 5 votes vote down vote up
def getFieldDatatypeFromPythontype(pythonvar):
    if isinstance(pythonvar, str):
        return QVariant.String
    elif isinstance(pythonvar, int):
        return QVariant.Int
    elif isinstance(pythonvar, float):
        return QVariant.Double
    else: 
        return QVariant.String 
Example #17
Source File: Qneat3Utilities.py    From QNEAT3 with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #18
Source File: multizoom.py    From qgis-latlontools-plugin with GNU General Public License v2.0 5 votes vote down vote up
def createLayer(self):
        '''Create a memory layer from the zoom to locations'''
        rowcnt = self.resultsTable.rowCount()
        if rowcnt == 0:
            return
        attr = []
        for item, label in enumerate(LABELS[0:self.numCol]):
            label = label.lower()
            if item <= 1:
                attr.append(QgsField(label, QVariant.Double))
            else:
                attr.append(QgsField(label, QVariant.String))
        ptLayer = QgsVectorLayer("Point?crs=epsg:4326", u"Lat Lon Locations", "memory")
        provider = ptLayer.dataProvider()
        provider.addAttributes(attr)
        ptLayer.updateFields()

        for id in range(rowcnt):
            item = self.resultsTable.item(id, 0).data(Qt.UserRole)
            feature = QgsFeature()
            feature.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(item.lon, item.lat)))
            attr = [item.lat, item.lon, item.label]
            for i in range(3, self.numCol):
                attr.append(item.data[i - 3])
            feature.setAttributes(attr)
            provider.addFeatures([feature])

        ptLayer.updateExtents()
        if self.settings.multiZoomStyleID == 1:
            settings = QgsPalLayerSettings()
            settings.fieldName = 'label'
            settings.placement = QgsPalLayerSettings.AroundPoint
            labeling = QgsVectorLayerSimpleLabeling(settings)
            ptLayer.setLabeling(labeling)
            ptLayer.setLabelsEnabled(True)
        elif self.settings.multiZoomStyleID == 2 and os.path.isfile(self.settings.customQMLFile()):
            ptLayer.loadNamedStyle(self.settings.customQMLFile())

        QgsProject.instance().addMapLayer(ptLayer) 
Example #19
Source File: bulkDialog.py    From qgis-bulk-nominatim with GNU General Public License v2.0 5 votes vote down vote up
def createPointLayer(self):
        layername = self.layerLineEdit.text()
        self.pointLayer = QgsVectorLayer("point?crs=epsg:4326", layername, "memory")
        self.provider = self.pointLayer.dataProvider()
        if self.detailedAddressCheckBox.checkState():
            self.provider.addAttributes([
                QgsField("osm_type", QVariant.String),
                QgsField("osm_id", QVariant.String),
                QgsField("class", QVariant.String),
                QgsField("type", QVariant.String),
                QgsField("source_addr", QVariant.String),
                QgsField("display_name", QVariant.String),
                QgsField("house_number", QVariant.String),
                QgsField("road", QVariant.String),
                QgsField("neighbourhood", QVariant.String),
                QgsField("locality", QVariant.String),
                QgsField("town", QVariant.String),
                QgsField("city", QVariant.String),
                QgsField("county", QVariant.String),
                QgsField("state", QVariant.String),
                QgsField("postcode", QVariant.String),
                QgsField("country", QVariant.String),
                QgsField("country_code", QVariant.String)])
        else:
            self.provider.addAttributes([QgsField("display_name", QVariant.String)])
        self.pointLayer.updateFields()
        if self.showLabelCheckBox.checkState():
            # Display labels
            label = QgsPalLayerSettings()
            label.fieldName = 'display_name'
            label.placement= QgsPalLayerSettings.AroundPoint
            labeling = QgsVectorLayerSimpleLabeling(label)
            self.pointLayer.setLabeling(labeling)
            self.pointLayer.setLabelsEnabled(True) 
Example #20
Source File: geodesicMeasureTool.py    From qgis-shapetools-plugin with GNU General Public License v2.0 4 votes vote down vote up
def saveToLayer(self):
        units = self.unitDesignator()
        canvasCrs = self.canvas.mapSettings().destinationCrs()
        fields = QgsFields()
        fields.append(QgsField("label", QVariant.String))
        fields.append(QgsField("value", QVariant.Double))
        fields.append(QgsField("units", QVariant.String))
        fields.append(QgsField("heading_to", QVariant.Double))
        fields.append(QgsField("heading_from", QVariant.Double))
        fields.append(QgsField("total_dist", QVariant.Double))

        layer = QgsVectorLayer("LineString?crs={}".format(canvasCrs.authid()), "Measurements", "memory")
        dp = layer.dataProvider()
        dp.addAttributes(fields)
        layer.updateFields()

        num = len(self.capturedPoints)
        total = 0.0
        for i in range(1, num):
            (distance, startA, endA) = self.calcParameters(self.capturedPoints[i - 1], self.capturedPoints[i])
            total += distance
        total = self.unitDistance(total)
        for i in range(1, num):
            (distance, startA, endA) = self.calcParameters(self.capturedPoints[i - 1], self.capturedPoints[i])
            pts = self.getLinePts(distance, self.capturedPoints[i - 1], self.capturedPoints[i])
            distance = self.unitDistance(distance)
            feat = QgsFeature(layer.fields())
            feat.setAttribute(0, "{:.2f} {}".format(distance, units))
            feat.setAttribute(1, distance)
            feat.setAttribute(2, units)
            feat.setAttribute(3, startA)
            feat.setAttribute(4, endA)
            feat.setAttribute(5, total)
            feat.setGeometry(QgsGeometry.fromPolylineXY(pts))
            dp.addFeatures([feat])

        label = QgsPalLayerSettings()
        label.fieldName = 'label'
        try:
            label.placement = QgsPalLayerSettings.Line
        except Exception:
            label.placement = QgsPalLayerSettings.AboveLine
        format = label.format()
        format.setColor(settings.measureTextColor)
        format.setNamedStyle('Bold')
        label.setFormat(format)
        labeling = QgsVectorLayerSimpleLabeling(label)
        layer.setLabeling(labeling)
        layer.setLabelsEnabled(True)
        renderer = layer.renderer()
        renderer.symbol().setColor(settings.measureLineColor)
        renderer.symbol().setWidth(0.5)

        layer.updateExtents()
        QgsProject.instance().addMapLayer(layer) 
Example #21
Source File: IsoAreaAsPointcloudFromPoint.py    From QNEAT3 with GNU General Public License v3.0 4 votes vote down vote up
def processAlgorithm(self, parameters, context, feedback):
        feedback.pushInfo(self.tr("[QNEAT3Algorithm] This is a QNEAT3 Algorithm: '{}'".format(self.displayName())))
        network = self.parameterAsSource(parameters, self.INPUT, context) #QgsProcessingFeatureSource
        startPoint = self.parameterAsPoint(parameters, self.START_POINT, context, network.sourceCrs()) #QgsPointXY
        max_dist = self.parameterAsDouble(parameters, self.MAX_DIST, context)#float
        strategy = self.parameterAsEnum(parameters, self.STRATEGY, context) #int

        entry_cost_calc_method = self.parameterAsEnum(parameters, self.ENTRY_COST_CALCULATION_METHOD, context) #int
        directionFieldName = self.parameterAsString(parameters, self.DIRECTION_FIELD, context) #str (empty if no field given)
        forwardValue = self.parameterAsString(parameters, self.VALUE_FORWARD, context) #str
        backwardValue = self.parameterAsString(parameters, self.VALUE_BACKWARD, context) #str
        bothValue = self.parameterAsString(parameters, self.VALUE_BOTH, context) #str
        defaultDirection = self.parameterAsEnum(parameters, self.DEFAULT_DIRECTION, context) #int
        speedFieldName = self.parameterAsString(parameters, self.SPEED_FIELD, context) #str
        defaultSpeed = self.parameterAsDouble(parameters, self.DEFAULT_SPEED, context) #float
        tolerance = self.parameterAsDouble(parameters, self.TOLERANCE, context) #float

        analysisCrs = network.sourceCrs()
        input_coordinates = [startPoint]
        input_point = getFeatureFromPointParameter(startPoint)
        
        feedback.pushInfo("[QNEAT3Algorithm] Building Graph...")
        feedback.setProgress(10)  
        net = Qneat3Network(network, input_coordinates, strategy, directionFieldName, forwardValue, backwardValue, bothValue, defaultDirection, analysisCrs, speedFieldName, defaultSpeed, tolerance, feedback)
        feedback.setProgress(40)

        analysis_point = Qneat3AnalysisPoint("point", input_point, "point_id", net, net.list_tiedPoints[0], entry_cost_calc_method, feedback)
        
        fields = QgsFields()
        fields.append(QgsField('vertex_id', QVariant.Int, '', 254, 0))
        fields.append(QgsField('cost', QVariant.Double, '', 254, 7))
        fields.append(QgsField('origin_point_id',QVariant.String, '', 254, 7))
        
        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context, fields, QgsWkbTypes.Point, network.sourceCrs())
        
        feedback.pushInfo("[QNEAT3Algorithm] Calculating Iso-Pointcloud...")
        iso_pointcloud = net.calcIsoPoints([analysis_point], max_dist)
        feedback.setProgress(90)
        
        sink.addFeatures(iso_pointcloud, QgsFeatureSink.FastInsert)
        
        feedback.pushInfo("[QNEAT3Algorithm] Ending Algorithm")
        feedback.setProgress(100)        
        
        results = {}
        results[self.OUTPUT] = dest_id
        return results 
Example #22
Source File: tomgrs.py    From qgis-latlontools-plugin with GNU General Public License v2.0 4 votes vote down vote up
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} 
Example #23
Source File: pluscodes.py    From qgis-latlontools-plugin with GNU General Public License v2.0 4 votes vote down vote up
def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.PrmInputLayer, context)
        field_name = self.parameterAsString(parameters, self.PrmPlusCodesFieldName, context).strip()
        plusCodesLength = self.parameterAsInt(parameters, self.PrmPlusCodesLength, context)

        fieldsout = QgsFields(source.fields())

        if fieldsout.append(QgsField(field_name, QVariant.String)) is False:
            msg = "Plus Codes Field Name must be unique. There is already a field named '{}'".format(field_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 plus codes 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 = olc.encode(pt.y(), pt.x(), plusCodesLength)
            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}