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

The following are 15 code examples of qgis.PyQt.QtCore.QVariant.Double(). 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: Qneat3Utilities.py    From QNEAT3 with GNU General Public License v3.0 7 votes vote down vote up
def buildQgsVectorLayer(string_geomtype, string_layername, crs, feature_list, list_qgsfield):
    
    #create new vector layer from self.crs
    vector_layer = QgsVectorLayer(string_geomtype, string_layername, "memory")
    
    #set crs from class
    vector_layer.setCrs(crs)
    
    #set fields
    provider = vector_layer.dataProvider()
    provider.addAttributes(list_qgsfield) #[QgsField('fid',QVariant.Int),QgsField("origin_point_id", QVariant.Double),QgsField("iso", QVariant.Int)]
    vector_layer.updateFields()
    
    #fill layer with geom and attrs
    vector_layer.startEditing()
    for feat in feature_list:
        vector_layer.addFeature(feat, True)
    vector_layer.commitChanges()

    return vector_layer 
Example #2
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 #3
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 #4
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 #5
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 #6
Source File: Qneat3Framework.py    From QNEAT3 with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #7
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 #8
Source File: edgvLayerLoader.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def createMeasureColumn(self, layer):
        if layer.geometryType() == QgsWkbTypes.PolygonGeometry:
            layer.addExpressionField('$area', QgsField(self.tr('area_otf'), QVariant.Double))
        elif layer.geometryType() == QgsWkbTypes.LineGeometry:
            layer.addExpressionField('$length', QgsField(self.tr('lenght_otf'), QVariant.Double))
        return layer 
Example #9
Source File: addMetersPerSecAlgorithm.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)
        
        fields = input_layer.fields()
        output_fields = fields
        output_fields.append(QgsField('meters_per_sec', QVariant.Double))
        
        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
                                               output_fields, 
                                               QgsWkbTypes.Point, 
                                               input_layer.sourceCrs())
        
        trajectories = trajectories_from_qgis_point_layer(input_layer, timestamp_field, traj_id_field, timestamp_format)
        
        for traj in trajectories:
            traj.add_meters_per_sec()
            for index, row in traj.df.iterrows():
                pt = QgsGeometry.fromWkt(row['geometry'].wkt)
                f = QgsFeature()
                f.setGeometry(pt)
                attributes = []
                for field in fields:
                    if field.name() == timestamp_field:
                        attributes.append(str(index))
                    else:
                        attributes.append(row[field.name()])
                f.setAttributes(attributes)
                sink.addFeature(f, QgsFeatureSink.FastInsert)
        
        # default return type for function
        return {self.OUTPUT: dest_id} 
Example #10
Source File: addHeadingAlgorithm.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)
        
        fields = input_layer.fields()
        output_fields = fields
        output_fields.append(QgsField('heading', QVariant.Double))
        
        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
                                               output_fields, 
                                               QgsWkbTypes.Point, 
                                               input_layer.sourceCrs())
        
        trajectories = trajectories_from_qgis_point_layer(input_layer, timestamp_field, traj_id_field, timestamp_format)
        
        for traj in trajectories:
            traj.add_heading()
            for index, row in traj.df.iterrows():
                pt = QgsGeometry.fromWkt(row['geometry'].wkt)
                f = QgsFeature()
                f.setGeometry(pt)
                attributes = []
                for field in fields:
                    if field.name() == timestamp_field:
                        attributes.append(str(index))
                    else:
                        attributes.append(row[field.name()])
                f.setAttributes(attributes)
                sink.addFeature(f, QgsFeatureSink.FastInsert)
        
        # default return type for function
        return {self.OUTPUT: dest_id} 
Example #11
Source File: do_AssignLevelsToBuildings.py    From openoise-map with GNU General Public License v3.0 5 votes vote down vote up
def update_field_receiver_points_layer(self):

        if str(self.receiver_points_layer_comboBox.currentText()) == "":
            return

        receiver_points_layer = QgsProject.instance().mapLayersByName(self.receiver_points_layer_comboBox.currentText())[0]
        receiver_points_layer_fields = list(receiver_points_layer.dataProvider().fields())

        #print(receiver_points_layer_fields)

        #self.id_field_comboBox.clear()
        self.level_1_comboBox.clear()
        self.level_2_comboBox.clear()
        self.level_3_comboBox.clear()
        self.level_4_comboBox.clear()
        self.level_5_comboBox.clear()

        receiver_points_layer_fields_number = [""]

        for f in receiver_points_layer_fields:
            if f.type() == QVariant.Int or f.type() == QVariant.Double:
                receiver_points_layer_fields_number.append(str(f.name()))

        #print(receiver_points_layer_fields_number)

        for f_label in receiver_points_layer_fields_number:
            #self.id_field_comboBox.addItem(f_label)
            self.level_1_comboBox.addItem(f_label)
            self.level_2_comboBox.addItem(f_label)
            self.level_3_comboBox.addItem(f_label)
            self.level_4_comboBox.addItem(f_label)
            self.level_5_comboBox.addItem(f_label) 
Example #12
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 #13
Source File: IsoAreaAsPointcloudFromLayer.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
        startPoints = self.parameterAsSource(parameters, self.START_POINTS, context) #QgsProcessingFeatureSource
        id_field = self.parameterAsString(parameters, self.ID_FIELD, context) #str
        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 = getListOfPoints(startPoints)
        
        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)
        
        list_apoints = [Qneat3AnalysisPoint("from", feature, id_field, net, net.list_tiedPoints[i], entry_cost_calc_method, feedback) for i, feature in enumerate(getFeaturesFromQgsIterable(startPoints))]
        
        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', getFieldDatatype(startPoints, id_field)))
        
        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context, fields, QgsWkbTypes.Point, network.sourceCrs())
        
        feedback.pushInfo("[QNEAT3Algorithm] Calculating Iso-Pointcloud...")
        iso_pointcloud = net.calcIsoPoints(list_apoints, 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 #14
Source File: createRose.py    From qgis-shapetools-plugin with GNU General Public License v2.0 4 votes vote down vote up
def initAlgorithm(self, config):
        self.addParameter(
            QgsProcessingParameterFeatureSource(
                self.PrmInputLayer,
                tr('Input point layer'),
                [QgsProcessing.TypeVectorPoint])
        )
        self.addParameter(
            QgsProcessingParameterEnum(
                self.PrmShapeType,
                tr('Shape type'),
                options=SHAPE_TYPE,
                defaultValue=0,
                optional=False)
        )
        self.addParameter(
            QgsProcessingParameterNumber(
                self.PrmPetals,
                tr('Number of petals'),
                QgsProcessingParameterNumber.Integer,
                defaultValue=8,
                minValue=1,
                optional=True)
        )
        self.addParameter(
            QgsProcessingParameterNumber(
                self.PrmStartingAngle,
                tr('Starting angle'),
                QgsProcessingParameterNumber.Double,
                defaultValue=0,
                optional=True)
        )
        self.addParameter(
            QgsProcessingParameterNumber(
                self.PrmRadius,
                tr('Radius'),
                QgsProcessingParameterNumber.Double,
                defaultValue=40.0,
                minValue=0,
                optional=True)
        )
        self.addParameter(
            QgsProcessingParameterEnum(
                self.PrmUnitsOfMeasure,
                tr('Radius units of measure'),
                options=DISTANCE_LABELS,
                defaultValue=0,
                optional=False)
        )
        self.addParameter(
            QgsProcessingParameterBoolean(
                self.PrmExportInputGeometry,
                tr('Add input geometry fields to output table'),
                False,
                optional=True)
        )
        self.addParameter(
            QgsProcessingParameterFeatureSink(
                self.PrmOutputLayer,
                tr('Output layer'))
        ) 
Example #15
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)