Python qgis.core.QgsFields() Examples
The following are 6
code examples of qgis.core.QgsFields().
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.core
, or try the search function
.
Example #1
Source File: Qneat3Framework.py From QNEAT3 with GNU General Public License v3.0 | 5 votes |
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 #2
Source File: Qneat3Utilities.py From QNEAT3 with GNU General Public License v3.0 | 5 votes |
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 #3
Source File: htmlExpansionDialog.py From qgis-kmltools-plugin with GNU General Public License v2.0 | 5 votes |
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 #4
Source File: utilityFunctions.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
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
Example #5
Source File: tomgrs.py From qgis-latlontools-plugin with GNU General Public License v2.0 | 4 votes |
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 #6
Source File: htmlExpansionDialog.py From qgis-kmltools-plugin with GNU General Public License v2.0 | 4 votes |
def accept(self): """Called when the OK button has been pressed.""" layer = self.inputLayerComboBox.currentLayer() if not layer: return newlayername = self.outputLayerLineEdit.text().strip() type = self.typeComboBox.currentIndex() # Find all the possible fields in the description area field = self.descriptionComboBox.currentField() index = layer.fields().indexFromName(field) if index == -1: self.iface.messageBar().pushMessage("", "Invalid field name", level=Qgis.Warning, duration=3) return # Set up the HTML expansion processor self.htmlProcessor = HTMLExpansionProcess(layer, field, type) self.htmlProcessor.addFeature.connect(self.addFeature) # Have it generate a list of all possible expansion field names self.htmlProcessor.autoGenerateFileds() # From the expansion processor get the list of possible expansion fields # and show a popup of them so the user can select which he wants in the output. fieldsDialog = HTMLFieldSelectionDialog(self.iface, self.htmlProcessor.fields()) fieldsDialog.exec_() # From the users selections of expansion fields, set them in the processor. # This is just a list of names. self.htmlProcessor.setDesiredFields(fieldsDialog.selected) wkbtype = layer.wkbType() layercrs = layer.crs() # Create the new list of attribute names from the original data with the unique # expansion names. fieldsout = QgsFields(layer.fields()) for item in self.htmlProcessor.uniqueDesiredNames(layer.fields().names()): fieldsout.append(QgsField(item, QVariant.String)) newLayer = QgsVectorLayer("{}?crs={}".format(QgsWkbTypes.displayString(wkbtype), layercrs.authid()), newlayername, "memory") self.dp = newLayer.dataProvider() self.dp.addAttributes(fieldsout) newLayer.updateFields() # Process each record in the input layer with the expanded entries. # The actual record is added with the 'addFeature' callback self.htmlProcessor.processSource() self.htmlProcessor.addFeature.disconnect(self.addFeature) newLayer.updateExtents() QgsProject.instance().addMapLayer(newLayer) self.close()