def selectGeometry(self, geometry, mode=0, label="", toggleRendering=True): """Add the given geometry to the selection. Parameters ---------- geometry : QGisCore.QgsGeometry Geometry to add to the selection. mode : int, optional Mode to use for the selected geometry. Defaults to 0. label : str, optional Label to use for the selected geometry. Defaults to an empty label. toggleRendering : boolean, optional Redraw the map after changing the tempLayer. Defaults to True. When making multiple changes to the selection set only the last change to toggleRendering=`True` for improved performance. """ if not self.__getLayer(): return f = QGisCore.QgsFeature() f.fields().append(QGisCore.QgsField( 'mode', QtCore.QVariant.Int, 'int', 1, 0)) f.fields().append(QGisCore.QgsField( 'label', QtCore.QVariant.String, 'string', 1, 0)) f.setGeometry(geometry) f.setAttributes([mode, label]) self.main.iface.mapCanvas().setRenderFlag(False) self.layer.addFeature(f) if toggleRendering: self.main.iface.mapCanvas().setRenderFlag(True)
def createFeature(self, geom): #Método para criar feição #Parâmetro de entrada: geom (geometria adquirida) if not geom: return 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.setFields(fields) feature.setGeometry(simplifyGeometry) 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() featureAdded = True if (formSuppressOnLayer == core.QgsEditFormConfig.SuppressOn or (formSuppressOnLayer == core.QgsEditFormConfig.SuppressDefault and formSuppressOnSettings == 'true')): self.addFeatureWithoutForm(layer, feature) else: featureAdded = self.addFeatureWithForm(layer, feature) if featureAdded and core.QgsProject.instance().topologicalEditing(): self.createTopology(feature)
def exportToMemoryLayer(self, route, srid, valueMaps): vectorLyr = core.QgsVectorLayer( 'LineString?crs=epsg:{0}{1}'.format( srid, self.getMemoryLayerFieldsUrl()), 'rota', "memory") vl = core.QgsProject().instance().addMapLayer(vectorLyr) vl.startEditing() feat = core.QgsFeature(vl.fields()) pavingValueMap = [ valueMap for valueMap in valueMaps if valueMap['attribute'] == 'revestimento' ] pavingValueMap = pavingValueMap[0][ 'valueMap'] if pavingValueMap else {} getPavingValue = lambda code, valueMap=pavingValueMap: list( pavingValueMap.keys())[list(pavingValueMap.values()).index(code)] for step in route: step['covering'] = getPavingValue( step['covering']).split('(')[0].strip() feat.setAttribute('id', step['seq']) feat.setAttribute('nome', step['name']) feat.setAttribute('sigla', step['initials']) feat.setAttribute('revestimento', step['covering']) feat.setAttribute('faixas', step['tracks']) feat.setAttribute('velocidade', step['velocity']) feat.setAttribute('observacao', step['note']) feat.setGeometry(QgsGeometry.fromWkt(step['wkt'])) vl.addFeature(feat) vl.commitChanges() return vl
def create_kaartblad(self, withGrid): gridUUID = uuid.uuid4() geom = self.rubberBand.asGeometry() geom.convertToMultiType() layerName = PC.OBJECT["gridlayername"] layer = UC.getlayer_byname(layerName) targetFeature = QC.QgsFeature() targetFields = layer.fields() targetFeature.initAttributes(targetFields.count()) targetFeature.setFields(targetFields) targetFeature.setGeometry(geom) targetFeature["type"] = 'Kaartblad' if self.scale_25000.isChecked(): targetFeature["scale"] = GH.DEFAULTSCALE else: targetFeature["scale"] = self.scale_custom.value() targetFeature["papersize"] = self.format_combo.currentText() if self.orient_landscape.isChecked(): targetFeature["orientation"] = 'landscape' else: targetFeature["orientation"] = 'portrait' targetFeature["uuid"] = str(gridUUID) foreignKey = CH.get_foreign_key_ob(layerName) targetFeature[foreignKey] = self.objectId UC.write_layer(layer, targetFeature) bbox = geom.boundingBox() dist = self.distance_grid.value() if withGrid: self.create_grid(gridUUID, dist, bbox, 'Kaartblad') self.canvas.scene().removeItem(self.rubberBand)
def import_bouwlaag(self, bouwlaagFeature): """after the checks the import of the floor can start""" childFeature = QC.QgsFeature() layerName = 'Bouwlagen' layer = UC.getlayer_byname(layerName) # get necessary attributes from config file foreignKey = CH.get_foreign_key_bl(layerName) # construct QgsFeature to save childFeature.setGeometry(bouwlaagFeature.geometry()) fields = layer.fields() childFeature.initAttributes(fields.count()) childFeature.setFields(fields) childFeature[foreignKey] = str(self.object_id.text()) childFeature["bouwlaag"] = int(self.bouwlaag.text()) newFeatureId = UC.write_layer(layer, childFeature) self.bouwlaag_id.setText(str(newFeatureId)) self.iface.actionPan().trigger() self.label2.setVisible(False) self.selectId.setVisible(False) self.label3.setVisible(True) self.label4.setVisible(True) self.label5a.setVisible(True) self.label5b.setVisible(True) self.import_laag.setVisible(True) self.check.setVisible(True) self.type.setVisible(True)
def writeMeshShapefile(mesh, fileName, crs=None): try: os.remove(fileName) except OSError: pass fields = { 0: qgis.QgsField("ID", pyqt.QVariant.Int), 1: qgis.QgsField("Marker", pyqt.QVariant.Int), 2: qgis.QgsField("Node1", pyqt.QVariant.Int), 3: qgis.QgsField("Node2", pyqt.QVariant.Int), 4: qgis.QgsField("Node3", pyqt.QVariant.Int) } writer = qgis.QgsVectorFileWriter(fileName, "utf-8", fields, qgis.QGis.WKBPolygon, crs, "ESRI Shapefile") if writer.hasError() != qgis.QgsVectorFileWriter.NoError: print "Error when creating shapefile: ", writer.hasError() for index, triangle in enumerate(mesh.elements): nodeIDs = triangle[1] coordinates = mesh.nodes.coordinates[nodeIDs] fet = qgis.QgsFeature() fet.setGeometry( qgis.QgsGeometry.fromPolygon([[ qgis.QgsPoint(*coordinates[0]), qgis.QgsPoint(*coordinates[1]), qgis.QgsPoint(*coordinates[2]) ]])) fet.addAttribute(0, pyqt.QVariant(index)) fet.addAttribute(1, pyqt.QVariant(1)) fet.addAttribute(2, pyqt.QVariant(1)) writer.addFeature(fet)
def construct_feature(layerType, parentLayerName, points, objectId, iface): tempFeature = QC.QgsFeature() parentId = None #converteer lijst van punten naar QgsGeometry, afhankelijk van soort geometrie if layerType == "Point": tempFeature.setGeometry(QC.QgsGeometry.fromPointXY(points)) geom = points elif layerType == "LineString": tempFeature.setGeometry(QC.QgsGeometry.fromPolylineXY(points)) geom = points[0] elif layerType == "Polygon": tempFeature.setGeometry(QC.QgsGeometry.fromPolygonXY([points])) geom = points[0] if parentLayerName != '' and parentLayerName == PC.OBJECT[ "objectlayername"]: parentlayer = getlayer_byname(parentLayerName) parentId = int(objectId) elif parentLayerName != '' and parentLayerName is not None: parentlayer = getlayer_byname(parentLayerName) dummy, parentId = nearest_neighbor(iface, parentlayer, geom) elif parentLayerName is None: parentId = '' else: parentId = None #foutafhandeling ivm als er geen parentId is if parentId is None and parentLayerName != '': MSG.showMsgBox('noparentfeature') return None, None else: return parentId, tempFeature
def copy_layers(self, parentID, newID, layer, bouwlaag): """select the features""" fields = layer.fields() newFeature = QC.QgsFeature() newFeature.initAttributes(fields.count()) newFeature.setFields(fields) attrs = CH.get_allkeys_bl(layer.name()) # get features by bouwlaag ID it = layer.getFeatures( QC.QgsFeatureRequest().setFilterExpression(attrs[0] + '=' + str(parentID))) for feat in it: newFeature.setGeometry(feat.geometry()) if attrs[1]: if str(feat[attrs[1]]).isdigit(): newFeature[attrs[1]] = int(feat[attrs[1]]) else: newFeature[attrs[1]] = feat[attrs[1]] if attrs[2]: newFeature[attrs[2]] = feat[attrs[2]] if attrs[3]: newFeature[attrs[3]] = feat[attrs[3]] newFeature[attrs[0]] = int(newID) newFeature["bouwlaag"] = bouwlaag UC.write_layer(layer, newFeature)
def draw_feature(self, points, _dummy): """create the floor feature and save to the floors layer""" minBouwlaag = int(self.bouwlaag_min.text()) maxBouwlaag = int(self.bouwlaag_max.text()) childFeature = QC.QgsFeature() layerName = PC.PAND["bouwlaaglayername"] layer = UC.getlayer_byname(layerName) foreignKey = CH.get_foreign_key_bl(layerName) # construct QgsFeature to save for i in range(minBouwlaag, maxBouwlaag + 1): if i != 0: childFeature.setGeometry(QC.QgsGeometry.fromPolygonXY([points ])) fields = layer.fields() childFeature.initAttributes(fields.count()) childFeature.setFields(fields) childFeature[foreignKey] = self.objectId childFeature["bouwlaag"] = i UC.write_layer(layer, childFeature) # block the signals of changing the comboBox to add the new floor self.bouwlaag.blockSignals(True) self.bouwlaag.clear() if i not in self.bouwlaagList: self.bouwlaagList.append(i) self.bouwlaagList.sort() self.bouwlagen_to_combobox() self.bouwlaag.blockSignals(False) self.iface.actionPan().trigger() # set all layers substring to the right floor sub_string = "bouwlaag = " + str(minBouwlaag) UG.set_layer_substring(sub_string) if maxBouwlaag != minBouwlaag: MSG.showMsgBox('bouwlaagcreated')
def getFeatures(): fields = [ 'id', 'acquired', 'thumbnail', 'meta_html', 'meta_json', 'meta_jsize' ] # See FIELDs order from createLayer features = [] for item in self.scenes: # Fields meta_json = item['properties'] vFields = {} vFields[fields[0]] = item['id'] vFields[fields[1]] = meta_json['acquired'] del meta_json['acquired'] vFields[fields[2]] = "Need download thumbnail" meta_json['assets_status'] = { 'a_analytic': { 'status': '*Need calculate*' }, 'a_udm': { 'status': '*Need calculate*' } } vFields[fields[ 3]] = API_PlanetLabs.getHtmlTreeMetadata( meta_json, '') vjson = json.dumps(meta_json) vFields[fields[4]] = vjson vFields[fields[5]] = len(vjson) # Geom geomItem = item['geometry'] geomCoords = geomItem['coordinates'] if geomItem['type'] == 'Polygon': qpolygon = map( lambda polyline: map( lambda item: QgsCore.QgsPoint( item[0], item[1]), polyline), geomCoords) geom = QgsCore.QgsGeometry.fromMultiPolygon( [qpolygon]) elif geomItem['type'] == 'MultiPolygon': qmultipolygon = [] for polygon in geomCoords: qpolygon = map( lambda polyline: map( lambda item: QgsCore.QgsPoint( item[0], item[1]), polyline), polygon) qmultipolygon.append(qpolygon) geom = QgsCore.QgsGeometry.fromMultiPolygon( qmultipolygon) else: continue feat = QgsCore.QgsFeature() feat.setGeometry(geom) atts = map(lambda item: vFields[item], fields) feat.setAttributes(atts) features.append(feat) return features
def inlezen(self): """import the file after all settings wehere made""" targetLayerName = self.import_laag.currentText() if targetLayerName == "Ruimten": typeLayer = UC.getlayer_byname('ruimten_type') targetFeature = QC.QgsFeature() targetLayer = UC.getlayer_byname(targetLayerName) targetFields = targetLayer.fields() targetFeature.initAttributes(targetFields.count()) identifier = CH.get_identifier_bl(targetLayerName) targetFeature.setFields(targetFields) self.iface.setActiveLayer(self.importLayer) dummy, progressBar = self.progressdialog(0) progressBar.setValue(0) progressBar.setMaximum(100) count = 0 cntFeat = self.importLayer.featureCount() invalidCount = 0 for feature in self.importLayer.getFeatures(): count += 1 if self.mappingDict[feature[self.type.currentText( )]] != 'niet importeren' and feature.geometry(): if self.importTypeFile == 'DXF': if self.importLayer.geometryType( ) == QC.QgsWkbTypes.PolygonGeometry: geom = QC.QgsGeometry.fromPolygonXY( feature.geometry().asPolygon()) elif self.importLayer.wkbType( ) == QC.QgsWkbTypes.MultiLineString: geom = QC.QgsGeometry.fromMultiPolylineXY( feature.geometry().asMultiPolyline()) else: geom = QC.QgsGeometry.fromPolylineXY( feature.geometry().asPolyline()) elif self.importTypeFile in ('GPKG', 'SHP'): geom = feature.geometry() targetFeature.setGeometry(geom) targetFeature["bouwlaag_id"] = int(self.bouwlaag_id.text()) if targetLayerName == "Ruimten": request = QC.QgsFeatureRequest().setFilterExpression( '"naam" = ' + "'" + self.mappingDict[feature[self.type.currentText()]] + "'") tempFeature = next(typeLayer.getFeatures(request)) targetFeature[identifier] = tempFeature["id"] else: targetFeature[identifier] = self.mappingDict[feature[ self.type.currentText()]] invalidCheck = UC.write_layer(targetLayer, targetFeature, True) if invalidCheck == 'invalid': invalidCount += 1 progress = (float(count) / float(cntFeat)) * 100 progressBar.setValue(progress) if invalidCount > 0: MSG.showMsgBox('importpartiallysuccesfull', '{}'.format(invalidCount)) else: MSG.showMsgBox('importsuccesfull') QC.QgsProject.instance().removeMapLayers([self.importLayer.id()])
def place_feature(self, point): childFeature = QC.QgsFeature() newFeatureId = None self.iface.setActiveLayer(self.drawLayer) objectLayer = UC.getlayer_byname(PC.OBJECT["objectlayername"]) #set geometry from the point clicked on the canvas childFeature.setGeometry(QC.QgsGeometry.fromPointXY(point)) foreignKey = self.identificatienummer.text() buttonCheck, formeleNaam = self.get_attributes(foreignKey, childFeature) #return of new created feature id if buttonCheck != 'Cancel': newFeatureId = UC.write_layer(self.drawLayer, childFeature) objectLayer.reload() if not newFeatureId: idx = objectLayer.fields().indexFromName('id') maxObjectId = objectLayer.maximumValue(idx) request = QC.QgsFeatureRequest().setFilterExpression( '"id" > {}'.format(maxObjectId)) self.drawLayer.reload() tempFeatureIt = objectLayer.getFeatures(request) for feat in tempFeatureIt: if feat["formelenaam"] == formeleNaam: newFeatureId = feat["id"] #with new created feature run existing object widget if newFeatureId: self.run_objectgegevens(formeleNaam, newFeatureId) else: MSG.showMsgBox('newobjectslowanswer') else: self.iface.actionPan().trigger()
def writeFractureShapefile(fractures, fileName, crs=None): try: os.remove(fileName) except OSError: pass fields = { 0: qgis.QgsField("ID", pyqt.QVariant.Int), 1: qgis.QgsField("Aperture", pyqt.QVariant.Double) } writer = qgis.QgsVectorFileWriter(fileName, "utf-8", fields, qgis.QGis.WKBLineString, crs, "ESRI Shapefile") if writer.hasError() != qgis.QgsVectorFileWriter.NoError: print "Error when creating shapefile: ", writer.hasError() for index, fracture in enumerate(fractures): feat = qgis.QgsFeature() feat.setGeometry( qgis.QgsGeometry.fromPolyline([ qgis.QgsPoint(fracture[0], fracture[1]), qgis.QgsPoint(fracture[2], fracture[3]) ])) # feat.addAttribute(0, pyqt.QVariant(index)) # feat.addAttribute(1, pyqt.QVariant(1)) # feat.addAttribute(2, pyqt.QVariant(1)) writer.addFeature(feat) # delete the writer to flush features to disk (optional) del writer
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)
def setData(self, data): self.idWorker = data['idWorker'] self.lstSources = data['sources'] self.featTemplate = QgsCore.QgsFeature(data['provLayer'].fields()) self.ct = QgsCore.QgsCoordinateTransform() self.ct.setDestCRS(data['provLayer'].crs()) self.foot = Footprint(data['hasValidPixels'], data['wktCrsImages'])
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.pendingFields() feature = core.QgsFeature() feature.setGeometry(simplifyGeometry) feature.initAttributes(fields.count()) provider = layer.dataProvider() for i in range(fields.count()): feature.setAttribute(i, provider.defaultValue(i)) formSuppressOnLayer = layer.featureFormSuppress() formSuppressOnSettings = self.getFormSuppressStateSettings() if formSuppressOnLayer or (formSuppressOnSettings == u"true"): self.addFeatureWithoutForm(layer, feature) else: self.addFeatureWithForm(layer, feature)
def addFeature(self, layer, fieldValues, geometry): feat = core.QgsFeature() feat.setFields(layer.fields()) feat.setGeometry(geometry) for key in fieldValues: feat[key] = fieldValues[key] provider = layer.dataProvider() provider.addFeature(feat)
def make_feature(self, feat_id, rect): feat = qc.QgsFeature() feat.setFeatureId(feat_id) if rect[0] != rect[1] or rect[2] != rect[3]: print("WARNING: can only deal with point geometries right now") gPnt = qc.QgsGeometry.fromPoint(qc.QgsPoint(rect[0], rect[2])) feat.setGeometry(gPnt) return feat
def addRelationship(self, attributes, layer): relationshipFeature = core.QgsFeature() relationshipFeature.setFields(layer.fields()) for name in attributes: relationshipFeature[name] = attributes[name] layer.startEditing() layer.addFeature(relationshipFeature) layer.commitChanges()
def inlezen(self): """import the file after all settings wehere made""" importAttr = self.type.currentText() invalidCount = 0 for importType in self.mappingDict: if self.mappingDict[importType]["targetType"] != 'niet importeren': checkConv = False expr = QC.QgsExpression('"{}"= \'{}\''.format( importAttr, importType)) featureIt = self.importLayer.getFeatures( QC.QgsFeatureRequest(expr)) targetFeature = QC.QgsFeature() targetLayerName = self.mappingDict[importType]["layerName"] if 'Labels' in targetLayerName: LabelDialog.attributes = [ self.type.itemText(i) for i in range(self.type.count()) ] LabelDialog.importType = importType labelField, dummy = LabelDialog.getLabelAtrribute() targetLayer = UC.getlayer_byname(targetLayerName) targetFields = targetLayer.fields() targetFeature.initAttributes(targetFields.count()) targetFeature.setFields(targetFields) if self.mappingDict[importType][ "convType"] != self.layerImportType: checkConv = True query = "SELECT foreign_key, identifier, input_label FROM config_object WHERE child_layer = '{}'".format( targetLayerName) attrs = UC.read_settings(query, False)[0] targetFeature[ attrs[1]] = self.mappingDict[importType]["targetType"] targetFeature[attrs[0]] = self.object_id.text() targetLayer.startEditing() for feat in featureIt: geom = None if not checkConv: geom = EF.getfeature_geometry(feat.geometry(), self.layerImportType) if 'Labels' in targetLayerName: if feat[labelField]: targetFeature[attrs[2]] = feat[labelField] else: targetFeature[attrs[2]] = 'geen label' if geom: targetFeature.setGeometry(geom) invalidCheck = UC.write_layer(targetLayer, targetFeature, True) if invalidCheck == 'invalid': invalidCount += 1 targetLayer.commitChanges() if invalidCount > 0: MSG.showMsgBox('importpartiallysuccesfull', '{}'.format(invalidCount)) else: MSG.showMsgBox('importsuccesfull') QC.QgsProject.instance().removeMapLayers([self.importLayer.id()])
def canvasReleaseEvent(self, mouseEvent): """handle mouse release event and return indetified feature""" tempfeature = QC.QgsFeature() results = self.identify(mouseEvent.x(), mouseEvent.y(), self.TopDownStopAtFirst, self.VectorLayer) if not results == []: tempfeature = results[0].mFeature idlayer = results[0].mLayer self.geomIdentified.emit(idlayer, tempfeature) else: self.geomIdentified.emit(None, tempfeature)
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])
def pointBuffer(self,p): infoLayer = self.infoBoxManager.getInfolayer() toInfoLayerProjection = core.QgsCoordinateTransform(self.iface.mapCanvas().mapSettings().destinationCrs(),infoLayer.crs(), core.QgsProject.instance()) toWGS84 = core.QgsCoordinateTransform(infoLayer.crs(),core.QgsCoordinateReferenceSystem(4326), core.QgsProject.instance()) # create layer and replicate fields bufferLayer = core.QgsVectorLayer("Point?crs="+infoLayer.crs().toWkt(), "temporary_points", "memory") #bufferLayer.setCrs(infoLayer.crs()) #This generates alert message bufferLayer.startEditing() bufferLayer.addAttribute(core.QgsField("id",QtCore.QVariant.String)) bufferLayer.addAttribute(core.QgsField("html",QtCore.QVariant.String)) bufferLayer.addAttribute(core.QgsField("icon",QtCore.QVariant.String)) bufferLayer.addAttribute(core.QgsField("fid",QtCore.QVariant.Int)) self.enableControlShape(toInfoLayerProjection.transform(core.QgsPointXY(p))) fetched = 0 self.featsId = self.infoBoxManager.getContextFeatures(toInfoLayerProjection.transform(p)) for featId in self.featsId: feat = infoLayer.getFeatures(core.QgsFeatureRequest(featId)).__next__() if fetched < 200: if infoLayer.geometryType() == core.QgsWkbTypes.PolygonGeometry: fGeom = feat.geometry().pointOnSurface() elif infoLayer.geometryType() == core.QgsWkbTypes.PointGeometry: fGeom = feat.geometry() if fGeom.isMultipart(): multipoint = fGeom.asMultiPoint() point = multipoint[0] else: point = fGeom.asPoint() fetched += 1 newGeom = core.QgsGeometry.fromPointXY(core.QgsPointXY(point)) newFeat = core.QgsFeature() newFeat.setGeometry(newGeom) newFeat.setAttributes([self.infoBoxManager.getInfoField(feat),self.infoBoxManager.getHtml(feat),self.infoBoxManager.getIconPath(feat),self.infoBoxManager.getFeatId(feat)]) bufferLayer.addFeature(newFeat) else: core.QgsMessageLog.logMessage("fetched too much features..... 200 max", tag="go2streetview", level=core.Qgis.Warning) break bufferLayer.commitChanges() core.QgsMessageLog.logMessage("markers context rebuilt", tag="go2streetview", level=core.Qgis.Info) #StreetView markers tmpfile = os.path.join(self.dirPath,"tmp","tmp_markers.geojson") core.QgsVectorFileWriter.writeAsVectorFormat (bufferLayer, tmpfile,"UTF8",toWGS84,"GeoJSON") with open(tmpfile) as f: geojson = f.read().replace('\n','') os.remove(tmpfile) #js = geojson.replace("'",'') #js = js.replace("\n",'\n') js = """this.markersJson = %s""" % json.dumps(geojson) self.view.SV.page().mainFrame().evaluateJavaScript(js) self.view.BE.page().mainFrame().evaluateJavaScript(js) js = """this.readJson() """ self.view.SV.page().mainFrame().evaluateJavaScript(js) self.view.BE.page().mainFrame().evaluateJavaScript(js) core.QgsMessageLog.logMessage("webview markers refreshed", tag="go2streetview", level=core.Qgis.Info)
def copy_bag_bouwlaag(self, ilayer, ifeature): """copy the floor drom the BAG features""" if ilayer.name() == PC.PAND["bouwlaaglayername"] or ilayer.name( ) == PC.bagpand_layername(): childFeature = QC.QgsFeature() layerName = PC.PAND["bouwlaaglayername"] # get active floor from dockwidget minBouwlaag = int(self.bouwlaag_min.text()) maxBouwlaag = int(self.bouwlaag_max.text()) layer = UC.getlayer_byname(layerName) # get necessary attributes from config file foreignKey = CH.get_foreign_key_bl(layerName) # construct QgsFeature to save for i in range(minBouwlaag, maxBouwlaag + 1): if i != 0: childFeature.setGeometry(ifeature.geometry()) fields = layer.fields() childFeature.initAttributes(fields.count()) childFeature.setFields(fields) childFeature[foreignKey] = self.objectId childFeature["bouwlaag"] = i newFeatureId = UC.write_layer(layer, childFeature) # copy also the selected layers if ilayer.name() == PC.PAND["bouwlaaglayername"]: self.copy_selected_layers(ifeature, newFeatureId, i) # block the signals of changing the comboBox to add the new floor self.bouwlaag.blockSignals(True) self.bouwlaag.clear() if i not in self.bouwlaagList: self.bouwlaagList.append(i) self.bouwlaagList.sort() self.bouwlagen_to_combobox() self.bouwlaag.blockSignals(False) self.iface.actionPan().trigger() # set all layers substring to the right floor sub_string = "bouwlaag = " + str(minBouwlaag) UG.set_layer_substring(sub_string) try: self.parent.selectTool.geomSelected.disconnect() except: # pylint: disable=bare-except pass if maxBouwlaag >= minBouwlaag: MSG.showMsgBox('bouwlaagcreated') else: MSG.showMsgBox('nobouwlaagselected') try: self.parent.selectTool.geomSelected.disconnect() except: # pylint: disable=bare-except pass self.parent.selectTool.geomSelected.connect(self.copy_bag_bouwlaag)
def saveShapeFile(self): #The line below is commented to disable saving of static images in local directory to not violate point 10.1.3.b) of https://developers.google.com/maps/terms self.saveImg() #fov = str(int(90/max(1,float(self.pov['zoom'])))) zoom = float(self.pov['zoom']) fov = 3.9018 * pow(zoom, 2) - 42.432 * zoom + 123 urlimg = "http://maps.googleapis.com/maps/api/streetview?size=640x400&location=" + self.pov[ 'lat'] + "," + self.pov['lon'] + "&heading=" + self.pov[ 'heading'] + "&pitch=" + self.pov[ 'pitch'] + "&sensor=false" + "&fov=" + str( fov) + "&key=" + self.parent.APIkey self.cb.setText(urlimg) sfPath = os.path.join(self.sessionDirectory(), "Streetview_snapshots_log.shp") if not os.path.isfile(sfPath): self.createShapefile(sfPath) vlayer = core.QgsVectorLayer(sfPath, "Streetview_snapshots_log", "ogr") testIfLayPresent = None for lay in self.canvas.layers(): if lay.name() == "Streetview_snapshots_log": testIfLayPresent = True if not testIfLayPresent: vlayer.loadNamedStyle(os.path.join(self.path, "snapshotStyle.qml")) #self.iface.actionFeatureAction().trigger() core.QgsProject.instance().addMapLayer(vlayer) set = QtCore.QSettings() set.setValue("/qgis/showTips", True) feat = core.QgsFeature() feat.initAttributes(8) feat.setAttribute( 0, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) feat.setAttribute(1, self.pov['lon']) feat.setAttribute(2, self.pov['lat']) feat.setAttribute(3, self.pov['heading']) feat.setAttribute(4, self.pov['pitch']) feat.setAttribute(5, self.pov['address']) #self.getAddress()) feat.setAttribute(6, self.snapshotNotes) #feat.setAttribute(7,self.file_name) feat.setAttribute(7, QtCore.QUrl(urlimg).toString()) feat.setGeometry( core.QgsGeometry.fromPointXY( core.QgsPointXY(float(self.pov['lon']), float(self.pov['lat'])))) vlayer.dataProvider().addFeatures([feat]) vlayer.triggerRepaint()
def create_grid(self, gridUUID=None, dist=None, extent=None, gridType='Grid'): if not gridUUID: gridUUID = uuid.uuid4() if not dist and not extent: extent = self.canvas.extent() dist = self.distance.value() layerName = PC.OBJECT["gridlayername"] layer = UC.getlayer_byname(layerName) targetFeature = QC.QgsFeature() targetFields = layer.fields() targetFeature.initAttributes(targetFields.count()) targetFeature.setFields(targetFields) foreignKey = CH.get_foreign_key_ob(layerName) xmin, dummy, ymin, dummy, xIt, yIt = self.calculate_extent( dist, extent, gridType) objectId = self.objectId targetFeature[foreignKey] = objectId targetFeature["type"] = 'Grid' for x in range(0, xIt): for y in range(0, yIt): yLabel = str(y + 1) if xIt < 26: xLabel = chr(x + 97).upper() elif xIt >= 26: xLabel = chr(int(math.floor(x / 26)) + 97).upper() + chr(x % 26 + 97).upper() geom = self.calculate_geometry(dist, xmin, ymin, x, y, gridType) targetFeature['vaknummer'] = xLabel + yLabel if x != 0: yLabel = '' if y != 0: xLabel = '' targetFeature.setGeometry(geom) targetFeature['y_as_label'] = yLabel targetFeature['x_as_label'] = xLabel targetFeature['afstand'] = dist targetFeature["uuid"] = str(gridUUID) UC.write_layer(layer, targetFeature) MSG.showMsgBox('gridcreated')
def place_feature(self, point): childFeature = QC.QgsFeature() objectLayer = UC.getlayer_byname(PC.OBJECT["objectlayername"]) # set geometry from the point clicked on the canvas childFeature.setGeometry(QC.QgsGeometry.fromPointXY(point)) foreignKey = self.identificatienummer.text() buttonCheck, formeleNaam = self.get_attributes(foreignKey, childFeature) # return of new created feature id if buttonCheck != 'Cancel': UC.write_layer(self.drawLayer, childFeature) objectLayer.reload() self.close_objectnieuw_show_base() else: self.iface.actionPan().trigger() try: self.parent.pinTool.canvasClicked.disconnect() except: pass
def getFeatureById(self, layer, featureId): f = core.QgsFeature() it = layer.getFeatures(core.QgsFeatureRequest(featureId)) it.nextFeature(f) return f
def addFeature(self, attributes, geometry, layer): feat = core.QgsFeature() feat.setAttributes(attributes) feat.setGeometry(geometry) layer.addFeature(feat)
def inlezen_validatie(self): """import the file after all settings wehere made""" targetLayerName = self.import_laag.currentText() targetLayer = UC.getlayer_byname(targetLayerName) targetFields = targetLayer.fields() if targetLayerName == "Ruimten": typeLayer = UC.getlayer_byname('ruimten_type') tempImportLayer = self.init_layer_fields( targetFields, ["MultiPolygon?crs=epsg:28992", "tempImport", "memory"]) tempImportLayerInvalid = self.init_layer_fields( targetFields, [ "MultiPolygon?crs=epsg:28992", "tempImport_invalid", "memory" ]) else: tempImportLayer = self.init_layer_fields( targetFields, ["MultiLinestring?crs=epsg:28992", "tempImport", "memory"]) tempImportLayerInvalid = self.init_layer_fields( targetFields, [ "MultiLinestring?crs=epsg:28992", "tempImport_invalid", "memory" ]) identifier = CH.get_identifier_bl(targetLayerName) bouwlaagGeomCentroid = self.get_centroid() dummy, progressBar = self.progressdialog(0) count = 0 cntFeat = self.importLayer.featureCount() invalidCount = 0 validFeatures = [] invalidFeatures = [] geomCheck = True for feature in self.importLayer.getFeatures(): targetFeature = QC.QgsFeature() targetFeature.initAttributes(targetFields.count()) targetFeature.setFields(targetFields) count += 1 if self.mappingDict[feature[self.type.currentText( )]] != 'niet importeren' and feature.geometry(): if self.importTypeFile == 'DXF': geom, geomCheck = self.check_feature_validity( feature, bouwlaagGeomCentroid) elif self.importTypeFile in ('GPKG', 'SHP'): geom = feature.geometry() targetFeature.setGeometry(geom) targetFeature["bouwlaag_id"] = int(self.bouwlaag_id.text()) if targetLayerName == "Ruimten": req = '"naam" = ' + "'" + self.mappingDict[feature[ self.type.currentText()]] + "'" request = QC.QgsFeatureRequest().setFilterExpression(req) tempFeature = next(typeLayer.getFeatures(request)) targetFeature[identifier] = tempFeature["id"] else: targetFeature[identifier] = self.mappingDict[feature[ self.type.currentText()]] if geomCheck: validFeatures.append(targetFeature) else: invalidFeatures.append(targetFeature) invalidCount += 1 progress = (float(count) / float(cntFeat)) * 100 progressBar.setValue(progress) if validFeatures: UC.write_layer(tempImportLayer, validFeatures, False, False) if invalidFeatures: UC.write_layer(tempImportLayerInvalid, invalidFeatures, False, False) QC.QgsProject.instance().addMapLayer(tempImportLayer, True) QC.QgsProject.instance().addMapLayer(tempImportLayerInvalid, True) if invalidCount > 0: MSG.showMsgBox('importpartiallysuccesfull', '{}'.format(invalidCount)) else: MSG.showMsgBox('importsuccesfull') QC.QgsProject.instance().removeMapLayers([self.importLayer.id()]) self.label8.setVisible(True) self.import_file.setVisible(True)