def test_AddPALToVectorLayer(self): """Check if we can set a label field, verify that PAL is assigned and that output is rendered correctly""" # TODO: add UTM PAL-specific shps, with 4326 as on-the-fly cross-check # setCanvasCrs(26913) myShpFile = os.path.join(TEST_DATA_DIR, 'lines.shp') myVectorLayer = QgsVectorLayer(myShpFile, 'Lines', 'ogr') self._MapRegistry.addMapLayer(myVectorLayer) myLayers = QStringList() myLayers.append(myVectorLayer.id()) self._MapRenderer.setLayerSet(myLayers) self._MapRenderer.setExtent(myVectorLayer.extent()) self._Canvas.zoomToFullExtent() # check layer labeling is PAL with customProperty access # should not be activated on layer load myPalSet = myVectorLayer.customProperty( "labeling" ).toString() myMessage = '\nExpected: Empty QString\nGot: %s' % (str(myPalSet)) assert str(myPalSet) == '', myMessage # simulate clicking checkbox, setting label field and clicking apply self._testFont.setPointSize(20) myPalLyr = QgsPalLayerSettings() myPalLyr.enabled = True myPalLyr.fieldName = 'Name' myPalLyr.placement = QgsPalLayerSettings.Line myPalLyr.placementFlags = QgsPalLayerSettings.AboveLine myPalLyr.xQuadOffset = 0 myPalLyr.yQuadOffset = 0 myPalLyr.xOffset = 0 myPalLyr.yOffset = 0 myPalLyr.angleOffset = 0 myPalLyr.centroidWhole = False myPalLyr.textFont = self._testFont myPalLyr.textNamedStyle = QString("Medium") myPalLyr.textColor = Qt.black myPalLyr.textTransp = 0 myPalLyr.previewBkgrdColor = Qt.white myPalLyr.priority = 5 myPalLyr.obstacle = True myPalLyr.dist = 0 myPalLyr.scaleMin = 0 myPalLyr.scaleMax = 0 myPalLyr.bufferSize = 1 myPalLyr.bufferColor = Qt.white myPalLyr.bufferTransp = 0 myPalLyr.bufferNoFill = False myPalLyr.bufferJoinStyle = Qt.RoundJoin myPalLyr.formatNumbers = False myPalLyr.decimals = 3 myPalLyr.plusSign = False myPalLyr.labelPerPart = False myPalLyr.displayAll = True myPalLyr.mergeLines = False myPalLyr.minFeatureSize = 0.0 myPalLyr.vectorScaleFactor = 1.0 myPalLyr.rasterCompressFactor = 1.0 myPalLyr.addDirectionSymbol = False myPalLyr.upsidedownLabels = QgsPalLayerSettings.Upright myPalLyr.fontSizeInMapUnits = False myPalLyr.bufferSizeInMapUnits = False myPalLyr.labelOffsetInMapUnits = True myPalLyr.distInMapUnits = False myPalLyr.wrapChar = "" myPalLyr.preserveRotation = True myPalLyr.writeToLayer(myVectorLayer) # check layer labeling is PAL with customProperty access myPalSet = myVectorLayer.customProperty( "labeling" ).toString() myMessage = '\nExpected: pal\nGot: %s' % (str(myPalSet)) assert str(myPalSet) == 'pal', myMessage # check layer labeling is PAL via engine interface myMessage = '\nCould not get whether PAL enabled from labelingEngine' assert self._PalEngine.willUseLayer(myVectorLayer), myMessage # myChecker = QgsRenderChecker() myChecker.setControlName("expected_pal_aboveLineLabeling") myChecker.setMapRenderer(self._MapRenderer) myResult = myChecker.runTest("pal_aboveLineLabeling_python"); myMessage = ('\nVector layer \'above line\' label engine ' 'rendering test failed') assert myResult, myMessage # compare against a straight rendering/save as from QgsMapCanvasMap # unnecessary? works a bit different than QgsRenderChecker, though # myImage = os.path.join(unicode(QDir.tempPath()), # 'render_pal_aboveLineLabeling.png') # self._Map.render() # self._Canvas.saveAsImage(myImage) # myChecker.setRenderedImage(myImage) # myResult = myChecker.compareImages("pal_aboveLineLabeling_python") # myMessage = ('\nVector layer \'above line\' label engine ' # 'comparison to QgsMapCanvasMap.render() test failed') # assert myResult, myMessage self._MapRegistry.removeMapLayer(myVectorLayer.id())
def save_adres_point(self, point, address, typeAddress='', layername="Geopunt_adres", saveToFile=False, sender=None, startFolder=None ): attributes = [QgsField("adres", QVariant.String), QgsField("type", QVariant.String)] mapcrs = self.getGetMapCrs(self.iface) if not QgsProject.instance().mapLayer(self.adreslayerid): self.adreslayer = QgsVectorLayer("Point", layername, "memory") self.adresProvider = self.adreslayer.dataProvider() self.adresProvider.addAttributes(attributes) self.adreslayer.updateFields() # add a feature fields= self.adreslayer.fields() fet = QgsFeature(fields) #set geometry and project from mapCRS xform = QgsCoordinateTransform( mapcrs, self.adreslayer.crs(), QgsProject.instance() ) prjPoint = xform.transform( point ) fet.setGeometry(QgsGeometry.fromPointXY(prjPoint)) #populate fields fet['adres'] = address fet['type'] = typeAddress self.adresProvider.addFeatures([ fet ]) "" # update layer's extent when new features have been added # because change of extent in provider is not propagated to the layer self.adreslayer.updateExtents() # save memoryLAYER to file and replace all references if saveToFile and not QgsProject.instance().mapLayer(self.adreslayerid): save = self._saveToFile( sender, startFolder ) if save: fpath, flType = save error, msg = QgsVectorFileWriter.writeAsVectorFormat(self.adreslayer, fileName=fpath, fileEncoding="utf-8", driverName=flType) if error == QgsVectorFileWriter.NoError: self.adreslayer = QgsVectorLayer( fpath, layername, "ogr") self.adresProvider = self.adreslayer.dataProvider() else: del self.adreslayer, self.adresProvider return else: del self.adreslayer, self.adresProvider return # add to map QgsProject.instance().addMapLayer(self.adreslayer) #labels text_format = QgsTextFormat() text_format.setSize(12) buffer_settings = QgsTextBufferSettings() buffer_settings.setEnabled(True) buffer_settings.setSize(1) buffer_settings.setColor(QColor("white")) palyr = QgsPalLayerSettings() text_format.setBuffer(buffer_settings) palyr.setFormat(text_format) palyr.enabled = True palyr.fieldName = 'adres' palyr.placement = QgsPalLayerSettings.Free self.adreslayer.setLabelsEnabled(True) self.adreslayer.setLabeling( QgsVectorLayerSimpleLabeling(palyr) ) # store layer id and refresh self.adreslayerid = self.adreslayer.id() self.canvas.refresh()
def resultSelectedFeatureByRectTasDraw(self, geom, distance, direction_bearing): # flag = FlightPlanBaseSimpleDlg.btnConstruct_Click(self) # if not flag: # return if define._userLayers == None: mapUnits = define._canvas.mapUnits() constructionLayer = AcadHelper.createVectorLayer( "Lines", QGis.Line) AcadHelper.setGeometryAndAttributesInLayer( constructionLayer, geom.asPolyline(), False, {"Caption": str(round(distance, 4)) + "m"}) define._userLayers = constructionLayer palSetting = QgsPalLayerSettings() palSetting.readFromLayer(constructionLayer) palSetting.enabled = True palSetting.fieldName = "Caption" palSetting.isExpression = True palSetting.placement = QgsPalLayerSettings.Line palSetting.placementFlags = QgsPalLayerSettings.AboveLine palSetting.setDataDefinedProperty(QgsPalLayerSettings.Size, True, True, '8', "") palSetting.writeToLayer(constructionLayer) QgisHelper.appendToCanvas(define._canvas, [constructionLayer], "Users layer", True) # self.resultLayerList = [constructionLayer] else: # constructionLayer = AcadHelper.createVectorLayer("Lines", QGis.Line) constructionLayer = define._userLayers iter = define._userLayers.getFeatures() equalFlag = 0 for feat in iter: # AcadHelper.setGeometryAndAttributesInLayer(constructionLayer, feat) if geom.equals(feat.geometry()): equalFlag += 1 if equalFlag <= 0: AcadHelper.setGeometryAndAttributesInLayer( constructionLayer, geom.asPolyline(), False, {"Caption": str(round(distance, 4)) + "m"}) palSetting = QgsPalLayerSettings() palSetting.readFromLayer(constructionLayer) palSetting.enabled = True palSetting.fieldName = "Caption" palSetting.isExpression = True palSetting.placement = QgsPalLayerSettings.Line palSetting.placementFlags = QgsPalLayerSettings.AboveLine palSetting.setDataDefinedProperty(QgsPalLayerSettings.Size, True, True, '8', "") palSetting.writeToLayer(constructionLayer) # QgisHelper.appendToCanvas(define._canvas,[constructionLayer], "Users layer", True) # self.resultLayerList = [constructionLayer] QgisHelper.zoomToLayers([constructionLayer]) define._userLayers = constructionLayer pass
def defaultSettings(self): lyr = QgsPalLayerSettings() lyr.enabled = True lyr.fieldName = 'text' # default in data sources lyr.textFont = self._TestFont lyr.textNamedStyle = 'Medium' return lyr
def prepare_ordered_marker(self, coords, idx): """ Try to display nice marker on a point layer, showing the order of the path computed by OSRM. """ self.tsp_marker_lr = QgsVectorLayer( "Point?crs=epsg:4326&field=id:integer" "&field=TSP_nb:integer(20)&field=Origin_nb:integer(20)", "tsp_markers_osrm{}".format(self.nb_route), "memory") symbol = QgsSymbolV2.defaultSymbol(self.tsp_marker_lr.geometryType()) symbol.setSize(4.5) symbol.setColor(QtGui.QColor("yellow")) ordered_pts = \ [coords[i["waypoint_index"]] for i in self.parsed['waypoints']] print("ordered_pts : ", ordered_pts) features = [] for nb, pt in enumerate(ordered_pts): ft = QgsFeature() ft.setGeometry(QgsGeometry.fromPoint(QgsPoint(pt))) ft.setAttributes([nb, nb + 1, coords.index(pt)]) features.append(ft) self.tsp_marker_lr.dataProvider().addFeatures(features) pal_lyr = QgsPalLayerSettings() pal_lyr.readFromLayer(self.tsp_marker_lr) pal_lyr.enabled = True pal_lyr.fieldName = 'TSP_nb' pal_lyr.placement= QgsPalLayerSettings.OverPoint pal_lyr.setDataDefinedProperty(QgsPalLayerSettings.Size,True,True,'12','') pal_lyr.writeToLayer(self.tsp_marker_lr) self.tsp_marker_lr.setRendererV2(QgsSingleSymbolRendererV2(symbol)) QgsMapLayerRegistry.instance().addMapLayer(self.tsp_marker_lr)
def linkProperty(self): layer = self.iface.mapCanvas().currentLayer() # parameters for advanced labeling -- picked up from a qgs model file # generic labeling properties layer.setCustomProperty("labeling/fieldName", share.field_list[0][0]) #[0][0] ) layer.setCustomProperty("labeling", "pal") # new gen labeling activated layer.setCustomProperty("labeling/multiLineLabels", "true") # default value layer.setCustomProperty("labeling/enabled", "true") # default value layer.setCustomProperty("labeling/priority", "10") # puts a high priority to labeling layer layer.setCustomProperty("labeling/multilineAlign", "1") # multiline align to center # line properties case layer.setCustomProperty( "labeling/placement", "2" ) # OnLine = 1, AboveLine = 2, BelowLine = 4, MapOrientation = 8 # data defined properties layer.setCustomProperty("labeling/dataDefined/PositionX", "1~~0~~~~" + share.field_list[1][0]) layer.setCustomProperty("labeling/dataDefined/PositionY", "1~~0~~~~" + share.field_list[2][0]) layer.setCustomProperty("labeling/dataDefined/Rotation", "1~~0~~~~" + share.field_list[3][0]) layer.setCustomProperty("labeling/dataDefined/Show", "1~~0~~~~" + share.field_list[4][0]) layer.setCustomProperty("labeling/dataDefined/Hali", "1~~0~~~~" + share.field_list[5][0]) layer.setCustomProperty("labeling/dataDefined/Vali", "1~~0~~~~" + share.field_list[6][0]) # set data define in a pyqigs3 way # link:https://gis.stackexchange.com/questions/313898/how-to-set-qgspropertycollection-via-an-dict pc = QgsPropertyCollection('qpc') sp = { 9: share.field_list[1][0], 10: share.field_list[2][0], 96: share.field_list[3][0], 15: share.field_list[4][0], 11: share.field_list[5][0], 12: share.field_list[6][0] } for k, v in sp.items(): x = QgsProperty() x.setField(v) pc.setProperty(k, x) pal_layer = QgsPalLayerSettings() pal_layer.fieldName = share.field_list[0][0] pal_layer.setDataDefinedProperties(pc) pal_layer.enabled = True labeler = QgsVectorLayerSimpleLabeling(pal_layer) layer.setLabeling(labeler) layer.setLabelsEnabled(True)
def pintaLabels(self, campEtiqueta): """Pinta sobre el canvas les etiquetas de la capa activa, segons campEtiqueta. Arguments: campEtiqueta {[String]} -- És el nom del camp del que volem pintar etiquetes. """ # layer=self.llegenda.currentLayer() layer_settings = QgsPalLayerSettings() text_format = QgsTextFormat() text_format.setFont(QvConstants.FONTTEXT) text_format.setSize(12) buffer_settings = QgsTextBufferSettings() buffer_settings.setEnabled(True) buffer_settings.setSize(1) buffer_settings.setColor(QColor("white")) text_format.setBuffer(buffer_settings) layer_settings.setFormat(text_format) layer_settings.fieldName = campEtiqueta layer_settings.placement = 0 layer_settings.enabled = True print("layer settings:" + layer_settings.fieldName) labeling = QgsVectorLayerSimpleLabeling(layer_settings) self.layer.setLabelsEnabled(True) self.layer.setLabeling(labeling) self.layer.triggerRepaint()
def showMarkDaSoc(self): try: flag = FlightPlanBaseDlg.btnConstruct_Click(self) self.putDistances() point3dMapt = self.parametersPanel.pnlMaPtPosition.Point3d socLayer = AcadHelper.createVectorLayer( "SOC_MAPt_" + self.surfaceType, QGis.Point) AcadHelper.setGeometryAndAttributesInLayer(socLayer, self.socPoint3d, False, {"Caption": "SOC"}) AcadHelper.setGeometryAndAttributesInLayer(socLayer, point3dMapt, False, {"Caption": "MAPt"}) QgisHelper.appendToCanvas(define._canvas, [socLayer], self.surfaceType) palSetting = QgsPalLayerSettings() palSetting.readFromLayer(socLayer) palSetting.enabled = True palSetting.fieldName = "Caption" palSetting.isExpression = True palSetting.placement = QgsPalLayerSettings.AroundPoint palSetting.setDataDefinedProperty(QgsPalLayerSettings.Size, True, True, '8', "") palSetting.writeToLayer(socLayer) self.resultLayerList = [socLayer] return socLayer except: pass
def set_label(layer, field_label): """Function that sets the label to a field value. Inspiration found at: https://gis.stackexchange.com/questions/277106/loading-labels-from-python-script-in-qgis Parameters ---------- layer: QgsVectorLayer valid qgis layer. field_label: str The label of the field """ layer_settings = QgsPalLayerSettings() text_format = QgsTextFormat() text_format.setFont(QFont("Arial", 12)) text_format.setSize(12) buffer_settings = QgsTextBufferSettings() buffer_settings.setEnabled(True) buffer_settings.setSize(0.10) buffer_settings.setColor(QColor("black")) text_format.setBuffer(buffer_settings) layer_settings.setFormat(text_format) layer_settings.fieldName = field_label layer_settings.placement = 4 layer_settings.enabled = True layer_settings = QgsVectorLayerSimpleLabeling(layer_settings) layer.setLabelsEnabled(True) layer.setLabeling(layer_settings) layer.triggerRepaint()
def SetDefaultPointStyle(layer): """ Point Symbol """ style = S.getDrawingPoint() symbol = QgsMarkerSymbol.createSimple({ "name": style["NAME"], "line_color": style["LINE_COLOR"], "line_width": style["LINE_WIDTH"], "size": style["SIZE"], }) renderer = QgsSingleSymbolRenderer(symbol) layer.setRenderer(renderer) layer_settings = QgsPalLayerSettings() text_format = QgsTextFormat() text_format.setFont(QFont(style["LABEL_FONT"], style["LABEL_FONT_SIZE"])) text_format.setColor(QColor(style["LABEL_FONT_COLOR"])) text_format.setSize(style["LABEL_SIZE"]) buffer_settings = QgsTextBufferSettings() buffer_settings.setEnabled(True) buffer_settings.setSize(1) buffer_settings.setColor(QColor(style["LABEL_BUFFER_COLOR"])) text_format.setBuffer(buffer_settings) layer_settings.setFormat(text_format) layer_settings.fieldName = "number" layer_settings.placement = 2 layer_settings.enabled = True layer_settings = QgsVectorLayerSimpleLabeling(layer_settings) layer.setLabelsEnabled(True) layer.setLabeling(layer_settings)
def createLayer(self): '''Create a memory layer from the zoom to locations''' if self.numcoord == 0: return ptLayer = QgsVectorLayer("Point?crs=epsg:4326", "Lat Lon Locations", "memory") provider = ptLayer.dataProvider() provider.addAttributes([ QgsField("latitude", QVariant.Double), QgsField("longitude", QVariant.Double), QgsField("label", QVariant.String) ]) ptLayer.updateFields() for item in self.llitems: feature = QgsFeature() feature.setGeometry( QgsGeometry.fromPoint(QgsPoint(item.lon, item.lat))) feature.setAttributes([item.lat, item.lon, item.label]) provider.addFeatures([feature]) ptLayer.updateExtents() if self.settings.multiZoomStyleID == 1: label = QgsPalLayerSettings() label.readFromLayer(ptLayer) label.enabled = True label.fieldName = 'label' label.placement = QgsPalLayerSettings.AroundPoint label.writeToLayer(ptLayer) elif self.settings.multiZoomStyleID == 2 and os.path.isfile( self.settings.customQMLFile()): ptLayer.loadNamedStyle(self.settings.customQMLFile()) QgsProject.instance().addMapLayer(ptLayer)
def createDefinedProperties(self): props = (('"auxiliary_storage_labeling_positionx"', QgsPalLayerSettings.PositionX), ('"auxiliary_storage_labeling_positiony"', QgsPalLayerSettings.PositionY), ('case when "auxiliary_storage_labeling_positionx" is NULL then NULL when "auxiliary_storage_labeling_positionx" < x( if( layer_property( @layer_name, \'geometry_type\' ) = \'Line\', closest_point( $geometry, make_point("auxiliary_storage_labeling_positionx", "auxiliary_storage_labeling_positiony") ), centroid($geometry) ) ) then \'Right\' else \'Left\' end', QgsPalLayerSettings.Hali), ('\'Half\'', QgsPalLayerSettings.Vali), ('if( "auxiliary_storage_labeling_positionx" is not NULL, True, False )', QgsPalLayerSettings.BufferDraw) # ,('10', QgsPalLayerSettings.BufferSize) ) pc = QgsPropertyCollection('labelConnector') for prop in props: p = QgsProperty() p.setExpressionString(prop[0]) pc.setProperty(prop[1], p) pal_layer = QgsPalLayerSettings() pal_layer.setDataDefinedProperties(pc) labeling = self.layer.labeling() if labeling is None: pal_layer.fieldName = self.layer.fields()[0].name() pal_layer.isExpression = False else: pal_layer.fieldName = labeling.settings().fieldName pal_layer.isExpression = labeling.settings().isExpression if self.layer.geometryType() == QgsWkbTypes.LineGeometry: pal_layer.placement = QgsPalLayerSettings.Line pal_layer.enabled = True labeler = QgsVectorLayerSimpleLabeling(pal_layer) self.layer.setLabeling(labeler) self.layer.setLabelsEnabled(True)
def createProfileLayers(heightSource): lyrCrs = heightSource.spatialRef.authid() pointA = heightSource.getFirstPoint() pointE = heightSource.getLastPoint() # Create profile layer surveyLineLayer = QgsVectorLayer('Linestring?crs=' + lyrCrs, tr('Felddaten-Profil'), 'memory') pr = surveyLineLayer.dataProvider() feature = QgsFeature() feature.setGeometry( QgsGeometry.fromPolyline( [QgsPoint(*tuple(pointA)), QgsPoint(*tuple(pointE))])) pr.addFeatures([feature]) surveyLineLayer.updateExtents() QgsProject.instance().addMapLayers([surveyLineLayer]) # Create survey point layer surveyPointLayer = QgsVectorLayer('Point?crs=' + lyrCrs, tr('Felddaten-Messpunkte'), 'memory') pr = surveyPointLayer.dataProvider() pr.addAttributes([QgsField("nr", QVariant.String)]) surveyPointLayer.updateFields() features = [] # TODO: Survey points are NOT rounded for x, y, nr, notes in zip(heightSource.x, heightSource.y, heightSource.nr, heightSource.plotNotes): feature = QgsFeature() feature.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(x, y))) feature.setId(int(nr + 1)) labelText = f"{nr}{':' if notes else ''} {notes if len(notes) <= 25 else notes[:22] + '...'}" feature.setAttributes([labelText]) features.append(feature) pr.addFeatures(features) surveyPointLayer.updateExtents() QgsProject.instance().addMapLayers([surveyPointLayer]) # Add Labels for point layer layer_settings = QgsPalLayerSettings() text_format = QgsTextFormat() text_format.setFont(QFont("Arial", 12)) text_format.setSize(12) buffer_settings = QgsTextBufferSettings() buffer_settings.setEnabled(True) buffer_settings.setSize(1) buffer_settings.setColor(QColor("white")) text_format.setBuffer(buffer_settings) layer_settings.setFormat(text_format) layer_settings.fieldName = "nr" layer_settings.placement = 2 layer_settings.enabled = True layer_settings = QgsVectorLayerSimpleLabeling(layer_settings) surveyPointLayer.setLabelsEnabled(True) surveyPointLayer.setLabeling(layer_settings) surveyPointLayer.triggerRepaint() return surveyLineLayer, surveyPointLayer
def defaultLayerSettings(self): lyr = QgsPalLayerSettings() lyr.enabled = True lyr.fieldName = "text" # default in test data sources font = self.getTestFont() font.setPointSize(32) lyr.textFont = font lyr.textNamedStyle = "Roman" return lyr
def defaultSettings(self): lyr = QgsPalLayerSettings() lyr.enabled = True lyr.fieldName = 'text' # default in data sources font = self.getTestFont() font.setPointSize(48) lyr.textFont = font lyr.textNamedStyle = 'Roman' return lyr
def defaultLayerSettings(self): lyr = QgsPalLayerSettings() lyr.enabled = True lyr.fieldName = 'text' # default in test data sources font = self.getTestFont() font.setPointSize(32) lyr.textFont = font lyr.textNamedStyle = 'Roman' lyr.bufferJoinStyle = Qt.BevelJoin # handle change of default join style return lyr
def setCollectionSettings(self): lyrids, lyrnames = self.lyrPair() coll = self.setFieldsCollection() arial = self.setArialDict() ssnr = self.setSsnrDict() swi = self.setSwiDict() times = self.setTimesDict() for names in lyrnames.values(): lyr = QgsProject.instance().mapLayersByName(names)[0] iface.setActiveLayer(lyr) pc = QgsPropertyCollection('qpc') lyr_settings = QgsPalLayerSettings() txt_format = QgsTextFormat() txt_format.setSizeUnit(QgsUnitTypes.RenderPoints) for nColl, fColl in coll.items(): x = QgsProperty() x.setField(fColl) pc.setProperty(nColl, x) pc.setProperty(31, '/') pc.setProperty(32, 0.8) if names in arial.values(): txt_format.setFont(QFont("Arial")) txt_format.setColor(QColor(0, 0, 0)) elif names in ssnr.values(): txt_format.setFont(QFont("Xerox Sans Serif Narrow")) txt_format.setColor(QColor(0, 0, 0)) elif names in swi.values(): txt_format.setFont(QFont("Xerox Serif Wide")) if re.search(r"\Bcotado", names): txt_format.setColor(QColor(140, 58, 61)) elif re.search(r"\Bcurva", names): txt_format.setColor(QColor(140, 58, 61)) else: txt_format.setColor(QColor(0, 119, 189)) elif names in times.values(): txt_format.setFont(QFont("Times New Roman")) txt_format.setColor(QColor(0, 0, 0)) pass lyr_settings.setFormat(txt_format) lyr_settings.setDataDefinedProperties(pc) lyr_settings.enabled = True if names == "rel_ponto_cotado_altimetrico_p": lyr_settings.fieldName = "cota" else: lyr_settings.fieldName = "legenda" lyr_settings = QgsVectorLayerSimpleLabeling(lyr_settings) lyr.setLabelsEnabled(True) lyr.setLabeling(lyr_settings) lyr.triggerRepaint()
def defaultLayerSettings(self): lyr = QgsPalLayerSettings() lyr.enabled = True lyr.fieldName = 'text' # default in test data sources font = self.getTestFont() font.setPointSize(32) format = lyr.format() format.setFont(font) format.setNamedStyle('Roman') format.setSize(32) format.setSizeUnit(QgsUnitTypes.RenderPoints) format.buffer().setJoinStyle(Qt.BevelJoin) lyr.setFormat(format) return lyr
def setLayerLabels(self, layer, fieldName): firstCondition = layer.geometryType( ) == 0 and self.cbNodeLabels.isChecked() secondCondition = layer.geometryType( ) != 0 and self.cbLinkLabels.isChecked() if firstCondition or secondCondition: pal_layer = QgsPalLayerSettings() pal_layer.fieldName = fieldName pal_layer.enabled = True pal_layer.placement = QgsPalLayerSettings.Line labels = QgsVectorLayerSimpleLabeling(pal_layer) layer.setLabeling(labels) layer.setLabelsEnabled(True) layer.triggerRepaint()
def _set_labeling(): pal_layer = QgsPalLayerSettings() pal_layer.fieldName = 'value' pal_layer.enabled = True pal_layer.placementFlags = QgsLabeling.OnLine pal_layer.placement = QgsPalLayerSettings.PerimeterCurved text_format = pal_layer.format() buffer = text_format.buffer() buffer.setColor(QColor(255, 255, 255)) buffer.setOpacity(0.5) buffer.setEnabled(True) text_format.setBuffer(buffer) pal_layer.setFormat(text_format) labels = QgsVectorLayerSimpleLabeling(pal_layer) return labels
def setLabelFormatter(self, layer): # remove topicType try: palyr = QgsPalLayerSettings() palyr.readFromLayer(layer) palyr.enabled = True palyr.fontBold = True palyr.shapeDraw = True palyr.shapeTransparency = 0 palyr.shapeType = QgsPalLayerSettings.ShapeRectangle palyr.textColor = QColor(255,255,255) # white palyr.placement = QgsPalLayerSettings.OverPoint palyr.quadOffset = QgsPalLayerSettings.QuadrantBelow palyr.multilineAlign = QgsPalLayerSettings.MultiCenter palyr.yOffset = 0.01 palyr.fieldName = '$format_label' palyr.writeToLayer(layer) Log.debug("Palyr Settings updated") except Exception as e: Log.debug("Error setting Label Format " + str(e))
def setLabelFormatter(self, layer): # remove topicType try: palyr = QgsPalLayerSettings() palyr.readFromLayer(layer) palyr.enabled = True palyr.fontBold = True palyr.shapeDraw = True palyr.shapeTransparency = 0 palyr.shapeType = QgsPalLayerSettings.ShapeRectangle palyr.textColor = QColor(255, 255, 255) # white palyr.placement = QgsPalLayerSettings.OverPoint palyr.quadOffset = QgsPalLayerSettings.QuadrantBelow palyr.multilineAlign = QgsPalLayerSettings.MultiCenter palyr.yOffset = 2 palyr.labelOffsetInMapUnits = False self.setPalLabelSettings(palyr) # obj so pass by reference palyr.writeToLayer(layer) Log.debug("Palyr Settings updated") except Exception as e: Log.debug("Error setting Label Format " + str(e))
def getLayers(self): text = self.layersText.toPlainText() names = text.split("\n") crs = self.crsText.toPlainText() for name in names: subprocess.run([ "scp", "acald013@hn:/tmp/edges{}.wkt".format(name), "/home/and/tmp/edges/edges{}.wkt".format(name) ]) instance = QgsProject.instance() for name in names: layers = instance.mapLayersByName(name) for layer in layers: instance.removeMapLayer(layer) iface.mapCanvas().refresh() for name in names: uri = "file:///home/and/tmp/edges/edges{}.wkt?delimiter={}&useHeader=no&crs=epsg:{}&wktField={}".format( name, "\\t", crs, "field_1") layer = iface.addVectorLayer(uri, name, "delimitedtext") if name == "Cells": symbol = QgsFillSymbol.createSimple({ 'color_border': 'blue', 'style': 'no', 'style_border': 'dash' }) layer.renderer().setSymbol(symbol) layer.triggerRepaint() if name == "Faces": symbol = QgsFillSymbol.createSimple({'color': 'green'}) layer.renderer().setSymbol(symbol) pal_layer = QgsPalLayerSettings() pal_layer.fieldName = 'field_2' pal_layer.enabled = True pal_layer.placement = QgsPalLayerSettings.Free labels = QgsVectorLayerSimpleLabeling(pal_layer) layer.setLabeling(labels) layer.setLabelsEnabled(True) layer.triggerRepaint() with open(os.path.join(os.path.dirname(__file__), 'history.txt'), 'w') as f: f.write("{}\n{}".format(text, crs))
def __calculate_Lane_IDs__(self): "..." laneList = ad.map.lane.getLanes() for each_layer in self.layer_group: layer = QgsProject.instance().mapLayersByName(each_layer)[0] for each_lane in laneList: lane = ad.map.lane.getLane(each_lane) text_format = QgsTextFormat() label = QgsPalLayerSettings() label.fieldName = 'Id' label.__setattr__('Id', lane.id) label.enabled = True label.setFormat(text_format) label.placement = QgsPalLayerSettings.OverPoint labeler = QgsVectorLayerSimpleLabeling(label) layer.setLabelsEnabled(True) layer.setLabeling(labeler) layer.triggerRepaint(True)
def setLayerLabels(self, layer, fieldName): firstCondition = layer.geometryType( ) == 0 and self.cbNodeLabels.isChecked() secondCondition = layer.geometryType( ) != 0 and self.cbLinkLabels.isChecked() if firstCondition or secondCondition: layer_settings = QgsPalLayerSettings() text_format = QgsTextFormat() text_format.setFont(QFont("Arial", 10)) color = "black" if secondCondition: color = "blue" text_format.setColor(QColor(color)) layer_settings.setFormat(text_format) layer_settings.fieldName = fieldName layer_settings.placement = QgsPalLayerSettings.Line layer_settings.enabled = True labels = QgsVectorLayerSimpleLabeling(layer_settings) layer.setLabeling(labels) layer.setLabelsEnabled(True) layer.triggerRepaint()
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("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.readFromLayer(self.pointLayer) label.enabled = True label.fieldName = 'display_name' label.placement = QgsPalLayerSettings.AroundPoint label.setDataDefinedProperty(QgsPalLayerSettings.Size, True, True, '8', '') label.writeToLayer(self.pointLayer)
def apply_label(self): ''' apply the label of the currently selected label field to the output layer ''' layer = self.input.layer if self.input else None if not layer: return self.label_field_name = self.label_field_combo.currentData() self.label_cache[layer.id] = self.label_field_name layer = self.output.layer if self.output else None if not layer: return if not self.label_field_name: layer.setLabelsEnabled(False) layer.reload() return layer.setLabelsEnabled(True) labeling = layer.labeling() if not labeling: settings = QgsPalLayerSettings() settings.enabled = True buffer = QgsTextBufferSettings() buffer.setEnabled(True) buffer.setSize(0.8) text_format = QgsTextFormat() text_format.setBuffer(buffer) text_format.setSize(8) settings.setFormat(text_format) labeling = QgsVectorLayerSimpleLabeling(settings) settings = labeling.settings() settings.fieldName = self.label_field_name labeling.setSettings(settings) layer.setLabeling(labeling) layer.reload()
def prepare_ordered_marker(self, coords, idx): """ Try to display nice marker on a point layer, showing the order of the path computed by OSRM. """ self.tsp_marker_lr = QgsVectorLayer( "Point?crs=epsg:4326&field=id:integer" "&field=TSP_nb:integer(20)&field=Origin_nb:integer(20)", "tsp_markers_osrm{}".format(self.nb_route), "memory") symbol = QgsSymbolV2.defaultSymbol(self.tsp_marker_lr.geometryType()) symbol.setSize(4.5) symbol.setColor(QtGui.QColor("yellow")) ordered_pts = \ [coords[i["waypoint_index"]] for i in self.parsed['waypoints']] print("ordered_pts : ", ordered_pts) features = [] for nb, pt in enumerate(ordered_pts): ft = QgsFeature() ft.setGeometry(QgsGeometry.fromPoint(QgsPoint(pt))) ft.setAttributes([nb, nb + 1, coords.index(pt)]) features.append(ft) self.tsp_marker_lr.dataProvider().addFeatures(features) pal_lyr = QgsPalLayerSettings() pal_lyr.readFromLayer(self.tsp_marker_lr) pal_lyr.enabled = True pal_lyr.fieldName = 'TSP_nb' pal_lyr.placement = QgsPalLayerSettings.OverPoint pal_lyr.setDataDefinedProperty(QgsPalLayerSettings.Size, True, True, '12', '') pal_lyr.writeToLayer(self.tsp_marker_lr) self.tsp_marker_lr.setRendererV2(QgsSingleSymbolRendererV2(symbol)) QgsMapLayerRegistry.instance().addMapLayer(self.tsp_marker_lr)
def run(self): print("paso por el run") #coloco el puntero arriba del todo QgsProject.instance().layerTreeRegistryBridge().setLayerInsertionPoint( QgsProject.instance().layerTreeRoot(), 0) def haceelcruce(x1, y1, ang1, x2, y2, ang2): #saco las pendientes m1 = (1 / math.tan(math.radians(ang1 + 0.000001))) m2 = (1 / math.tan(math.radians(ang2 + 0.000001))) #print ("m1") #print (m1) #print("m2") #print (m2) #saco las coordenadas de x e y x = ((y2 - y1) + (m1 * x1) - (m2 * x2)) / ((m1 - m2) + 0.000001) y = m1 * x + y1 - m1 * x1 #compruebo que el cruce no es erroneo if ang1 > 0 and ang1 < 180 and x < x1: iface.messageBar().pushMessage( "OJO: LAS VISUALES NO SE CRUZAN", qgisCore.Qgis.Info, 5) x, y, error = 0, 0, 0 if ang1 > 180 and ang1 < 360 and x > x1: iface.messageBar().pushMessage( "OJO: LAS VISUALES NO SE CRUZAN", qgisCore.Qgis.Info, 5) x, y, error = 0, 0, 0 if ang1 > 0 and ang1 < 90 and y < y1: iface.messageBar().pushMessage( "OJO: LAS VISUALES NO SE CRUZAN", qgisCore.Qgis.Info, 5) x, y, error = 0, 0, 0 if ang1 > 270 and ang1 < 360 and y < y1: iface.messageBar().pushMessage( "OJO: LAS VISUALES NO SE CRUZAN", qgisCore.Qgis.Info, 5) x, y, error = 0, 0, 0 if ang1 > 90 and ang1 < 270 and y > y1: iface.messageBar().pushMessage( "OJO: LAS VISUALES NO SE CRUZAN", qgisCore.Qgis.Info, 5) x, y, error = 0, 0, 9999999999999999999999999 else: #calculo el error d1a = math.sqrt((x - x1)**2 + (y - y1)**2) d2a = math.sqrt((x - x2)**2 + (y - y2)**2) d12 = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) A = math.acos((d1a**2 + d2a**2 - d12**2) / (2 * d1a * d2a)) if math.degrees(A) > 90: A = math.pi - A distancias = [d1a, d2a] distancias.sort(reverse=True) mayordistancia = distancias[0] error = mayordistancia * erroralidada / (math.sin(A / 2) + 0.000001) #print (ang1,ang2) #print (x,y,error) return x, y, error def generapunto(x, y): #creo una capa de puntos temporal con los resultados # create layer vl = QgsVectorLayer("Point?crs=epsg:25830", "Pto_Cruce", "memory") pr = vl.dataProvider() #print ("ok creada la capa") vl.startEditing() # add fields pr.addAttributes([ QgsField("error", QVariant.Int), QgsField("x", QVariant.Int), QgsField("y", QVariant.Double) ]) vl.updateFields() # tell the vector layer to fetch changes from the provider #print ("ok creados los campos") # add a feature fet = QgsFeature() fet.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(x, y))) fet.setAttributes([error, x, y]) pr.addFeatures([fet]) #print ("ok, anadido el elemento con error "+str(error)) #cambio la simbologia symbol = QgsMarkerSymbol.createSimple({ 'name': 'circle', 'color': 'orange', 'size': '5', }) vl.renderer().setSymbol(symbol) # update layer's extent when new features have been added # because change of extent in provider is not propagated to the layer #vl.updateExtents() vl.commitChanges() #vl.updateExtents() # show the point if x != 0 and y != 0: QgsProject.instance().addMapLayers([vl]) canvas = self.iface.mapCanvas() #canvas.setExtent(vl.extent()) #vl.updateFieldMap() def generalinea(x, y, angulo): m = (1 / math.tan(math.radians(angulo + 0.000001))) x1 = x + 100000 * math.sin(math.radians(angulo + 0.0000001)) y1 = y - m * (x - x1) line_start = QgsPoint(x, y) line_end = QgsPoint(x1, y1) #print (m) # create a new memory layer v_layer = QgsVectorLayer("LineString?crs=epsg:25830", "visual", "memory") pr = v_layer.dataProvider() # create a new feature seg = QgsFeature() # add the geometry to the feature, seg.setGeometry(QgsGeometry.fromPolyline([line_start, line_end])) # add the geometry to the layer pr.addFeatures([seg]) # update extent of the layer (not necessary) v_layer.updateExtents() #cambio la simbologia symbol3 = QgsLineSymbol.createSimple({ 'penstyle': 'solid', 'color': 'yellow', 'width': '2' }) v_layer.renderer().setSymbol(symbol3) # show the line QgsProject.instance().addMapLayers([v_layer]) def deg_to_dms(deg, type='lat'): decimals, number = math.modf(deg) d = int(number) m = int(decimals * 60) s = (deg - d - m / 60) * 3600.00 compass = {'lat': ('N', 'S'), 'lon': ('E', 'W')} compass_str = compass[type][0 if d >= 0 else 1] return '{}º{}\'{:.2f}"{}'.format(abs(d), abs(m), abs(s), compass_str) erroralidada = 1 #selecciono la capa de las torretas global rutapuestosvigiancia layer = QgsVectorLayer(rutapuestosvigiancia, '42_Puestos_vigilancia_etrs89', 'ogr') time.sleep(1) #layer = iface.activeLayer() ## ojo comprobar que layer existe """if layer is None or (layer.type() == RasterLayer): iface.messageBar().pushMessage("Warning:", u"Seleciona la capa de los puestos de vigilancia", QgsMessageBar.WARNING, 10) """ #genero una lista con las torres y ls coordenadas misdatos = [] feats = [feat for feat in layer.getFeatures()] for feature in feats: if feature.geometry().type( ) != 0: #0 es ptos, 1 lineas y 2 poligonos QGis.Point: iface.messageBar().pushMessage( "Warning:", u"Debe selecionar una capa de puntos", QgsMessageBar.WARNING, 10) point = [] idTM = layer.dataProvider().fieldNameIndex('Nombre') idx = layer.dataProvider().fieldNameIndex('x') idy = layer.dataProvider().fieldNameIndex('y') point = [ feature.attributes()[idTM], feature.attributes()[idx], feature.attributes()[idy] ] misdatos.append(point) #trato de rellenar el desplegable con las torretas #self.dlg.cb1.clear() #ordeno por el primer elemento misdatos.sort(key=lambda x: x[0]) #anado un elemneto enblanco en el desplegable self.dlg.cb1.clear() self.dlg.cb2.clear() self.dlg.cb3.clear() self.dlg.cb4.clear() self.dlg.cb1.addItem("") self.dlg.cb2.addItem("") self.dlg.cb3.addItem("") self.dlg.cb4.addItem("") for element in misdatos: self.dlg.cb1.addItem(element[0]) self.dlg.cb2.addItem(element[0]) self.dlg.cb3.addItem(element[0]) self.dlg.cb4.addItem(element[0]) #count vertices if there is layer in project in order to show it when dialog is loaded #layer = self.dlg.cb1.itemData(self.cb1.currentIndex()) """Run method that performs all the real work""" # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start == True: self.first_start = False #self.dlg = SilvilidarDialog() #la siguiente linea inicia el boton de cargar carpetas, peta al cerrar el qgis, deberia poner algun close o algo #self.dlg.pushButton_select_path.clicked.connect(self.select_laz_folder) #print("inicio el boton en el gui") #self.dlg.pushButton_select_path.setEnabled(True) #print ("pone le boton como habiltado") # show the dialog self.dlg.show() #self.dlg.pushButton_select_path.clicked.connect(self.select_laz_folder) # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. #print ("lo imprime si le doy a aceptar en el dialogo") #la carpeta la he cogido al pulsar el boton de la carpeta #meto aqui variables que luego deberan estar en la cajita OJO torret1 = self.dlg.cb1.currentIndex() torret2 = self.dlg.cb2.currentIndex() torret3 = self.dlg.cb3.currentIndex() torret4 = self.dlg.cb4.currentIndex() angulo1 = self.dlg.ang1.text() ##displayText() angulo2 = self.dlg.ang2.text() ##displayText() angulo3 = self.dlg.ang3.text() ##displayText() angulo4 = self.dlg.ang4.text() ##displayText() if angulo2 == "": angulo2 = 9999 if angulo3 == "": angulo3 = 9999 if angulo4 == "": angulo4 = 9999 try: ang1 = float(angulo1) ang2 = float(angulo2) ang3 = float(angulo3) ang4 = float(angulo4) except: pass #print (misdatos) torre1 = misdatos[int(torret1) - 1][0] x1 = float(misdatos[int(torret1) - 1][1]) y1 = float(misdatos[int(torret1) - 1][2]) torre2 = misdatos[int(torret2) - 1][0] x2 = float(misdatos[int(torret2) - 1][1]) y2 = float(misdatos[int(torret2) - 1][2]) torre3 = misdatos[int(torret3) - 1][0] x3 = float(misdatos[int(torret3) - 1][1]) y3 = float(misdatos[int(torret3) - 1][2]) torre4 = misdatos[int(torret4) - 1][0] x4 = float(misdatos[int(torret4) - 1][1]) y4 = float(misdatos[int(torret4) - 1][2]) #print (angulo1, angulo2, angulo3, angulo4) #print (torret1) #print (torre1, x1, y1) #print (torret2) #print (torre2, x2, y2) #print (torret3) #print (torret4) generalinea(x1, y1, ang1) resultado = [] if angulo2 != 9999: generalinea(x2, y2, ang2) x, y, error = haceelcruce(x1, y1, ang1, x2, y2, ang2) #print ("hecho el cruce") #print (x,y, error) generapunto(x, y) resultado = [] resultado.append(x) resultado.append(y) resultado.append(error) if angulo3 != 9999: generalinea(x3, y3, ang3) x, y, error = haceelcruce(x1, y1, ang1, x3, y3, ang3) generapunto(x, y) if error < resultado[2]: resultado = [] resultado.append(x) resultado.append(y) resultado.append(error) x, y, error = haceelcruce(x2, y2, ang2, x3, y3, ang3) generapunto(x, y) if error < resultado[2]: resultado = [] resultado.append(x) resultado.append(y) resultado.append(error) if angulo4 != 9999: generalinea(x4, y4, ang4) #print ("empiezo el angulo4") x, y, error = haceelcruce(x1, y1, ang1, x4, y4, ang4) generapunto(x, y) if error < resultado[2]: resultado = [] resultado.append(x) resultado.append(y) resultado.append(error) x, y, error = haceelcruce(x2, y2, ang2, x4, y4, ang4) generapunto(x, y) if error < resultado[2]: resultado = [] resultado.append(x) resultado.append(y) resultado.append(error) x, y, error = haceelcruce(x3, y3, ang3, x4, y4, ang4) generapunto(x, y) if error < resultado[2]: resultado = [] resultado.append(x) resultado.append(y) resultado.append(error) #hago una nueva capa con el mejor resultado if resultado != []: x, y, error = resultado[0], resultado[1], resultado[2] if x != 0 and y != 0: #creo una capa temporal con los resultados # create layer vl2 = QgsVectorLayer("Point?crs=epsg:25830", "MejorResultado", "memory") pr2 = vl2.dataProvider() #print ("ok creada la capa resultado final") vl2.startEditing() #calculo las coordenadas geograficas huso = 30 origenProj = pyproj.Proj(proj="utm", zone=huso, ellps="WGS84", units="m") destinoProj = pyproj.Proj(proj='longlat', ellps='WGS84', datum='WGS84') xxx, yyy = pyproj.transform(origenProj, destinoProj, x, y) xx = (deg_to_dms(xxx, 'lon')) yy = (deg_to_dms(yyy)) # add fields pr2.addAttributes([ QgsField("error", QVariant.Int), QgsField("x", QVariant.Double), QgsField("y", QVariant.Double), QgsField("xx", QVariant.String), QgsField("yy", QVariant.String) ]) vl2.updateFields() # tell the vector layer to fetch changes from the provider #print ("ok creados los campos") #$add a feature fet = QgsFeature() fet.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(x, y))) fet.setAttributes([error, x, y, xx, yy]) pr2.addFeatures([fet]) print("MEJOR RESULTADO") print(int(resultado[0]), int(resultado[1])) #print ("ok, creda la capa con el resultado final") #cambio la simbologia symbol = QgsMarkerSymbol.createSimple({ 'name': 'circle', 'color': 'red', 'size': '10', }) vl2.renderer().setSymbol(symbol) #etiqueto con la x e y layer_settings = QgsPalLayerSettings() text_format = QgsTextFormat() text_format.setFont(QFont("Arial", 12)) text_format.setSize(12) text_format.setColor(QColor("Orange")) # meto un buffer a la etiqueta buffer_settings = QgsTextBufferSettings() buffer_settings.setEnabled(True) buffer_settings.setSize(1) buffer_settings.setColor(QColor("white")) text_format.setBuffer(buffer_settings) layer_settings.setFormat(text_format) #myexp=QgsExpression('''concat('X: ',"X",' Y: ',"Y")''') layer_settings.fieldName = '''concat('X: ',round("X",0),' Y: ',round("Y",0),'\n','Lat: ',"yy",' Lon: ',"xx")''' layer_settings.isExpression = True #layer_settings.placement = 7 #layer_settings.quadOffset = QgsPalLayerSettings.QuadrantBelow #layer_settings.yOffset = 1 layer_settings.enabled = True layer_settings = QgsVectorLayerSimpleLabeling( layer_settings) vl2.setLabelsEnabled(True) vl2.setLabeling(layer_settings) vl2.triggerRepaint() # update layer's extent when new features have been added # because change of extent in provider is not propagated to the layer vl2.updateExtents() vl2.commitChanges() vl2.updateExtents() canvas = self.iface.mapCanvas() canvas.setExtent(vl2.extent()) self.iface.mapCanvas().zoomScale(100000) #QgsProject.instance().addMapLayer(vl) QgsProject.instance().addMapLayer(vl2) pass
def run_open_pli(self): file = QFileDialog.getOpenFileName( self.dlg, "Select pli-file ", self.directory, '*') # .ldb,*.pol,*.pli,*.xyn,*.xyz') # file = r'd:\projecten\11200569_Maas_G6\20171114 Deltashell2\files\dflowfm\invoer\j17_5-v1_landboundaries.ldb' self.directory, filename = os.path.split(file) layername, extension = os.path.splitext(filename) print(layername) if extension == '.xyz' or extension == '.xyn': vl = QgsVectorLayer("Point", layername, "memory") QgsMapLayerRegistry.instance().addMapLayer(vl) pr = vl.dataProvider() # add fields if extension == 'xyz': attribute = 'z' else: attribute = 'name' pr.addAttributes([QgsField(attribute, QVariant.String)]) vl.updateFields( ) # tell the vector layer to fetch changes from the provider with open(file) as f: for line in f: ls = line.strip().split('\t') X = float(ls[0]) Y = float(ls[1]) Z = ls[2] fet = QgsFeature() fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(X, Y))) fet.setAttributes([Z]) pr.addFeatures([fet]) # update layer's extent when new features have been added # because change of extent in provider is not propagated to the layer vl.updateExtents() else: D = tek.tekal(file) # initialize D.info(file) # get file meta-data: all blocks vl = QgsVectorLayer("LineString", layername, "memory") QgsMapLayerRegistry.instance().addMapLayer(vl) pr = vl.dataProvider() attribute = "name" # add fields pr.addAttributes([QgsField(attribute, QVariant.String)]) vl.updateFields( ) # tell the vector layer to fetch changes from the provider for ii in range(len(D.blocks)): Name = D.blocks[ii].name M = D.read(ii) P = [] for ix in range(len(M[0])): P.append(QgsPoint(M[0][ix], M[1][ix])) # If line of just one points: duplicate if ix == 0: P.append(QgsPoint(M[0][ix] + 0.01, M[1][ix] + 0.01)) # add a feature fet = QgsFeature() fet.setGeometry(QgsGeometry.fromPolyline(P)) fet.setAttributes([Name]) pr.addFeatures([fet]) # update layer's extent when new features have been added # because change of extent in provider is not propagated to the layer vl.updateExtents() # Enable labels if attribute == 'name': label = QgsPalLayerSettings() label.readFromLayer(vl) label.enabled = True label.fieldName = attribute label.writeToLayer(vl)
def save_pois_points(self, points, layername="Geopunt_poi", saveToFile=None, sender=None, startFolder=None): attributes = [ QgsField("id", QVariant.Int), QgsField("thema", QVariant.String), QgsField("categorie", QVariant.String), QgsField("type", QVariant.String), QgsField("naam", QVariant.String), QgsField("telefoon", QVariant.String), QgsField("email", QVariant.String), #address QgsField("straat", QVariant.String), QgsField("huisnr", QVariant.String), QgsField("busnr", QVariant.String), QgsField("postcode", QVariant.String), QgsField("gemeente", QVariant.String), QgsField("link", QVariant.String), QgsField("lastupdate", QVariant.String), QgsField("owner", QVariant.String) ] if not QgsProject.instance().mapLayer(self.poilayerid): self.poilayer = QgsVectorLayer("Point", layername, "memory") self.poiProvider = self.poilayer.dataProvider() self.poiProvider.addAttributes(attributes) self.poilayer.updateFields() fields = self.poilayer.fields() for point in points: pt = QgsPointXY( point['location']['points'][0]['Point']['coordinates'][0], point['location']['points'][0]['Point']['coordinates'][1]) poiId = point["id"] if "categories" in list( point.keys()) and len(point["categories"]) > 0: theme = point["categories"][0]['value'] else: theme = '' if "categories" in list( point.keys()) and len(point["categories"]) > 1: category = point["categories"][1]['value'] else: category = '' if "categories" in point and len(point["categories"]) > 2: poiType = point["categories"][2]['value'] else: poiType = '' name = point["labels"][0]["value"] if "phone" in list(point.keys()): phone = point["phone"] else: phone = "" if "email" in list(point.keys()): email = point["email"] else: email = "" #address if "address" in list(point['location'].keys()): if "street" in list(point['location']["address"].keys()): straat = point['location']["address"]["street"] else: straat = '' if "streetnumber" in list(point['location']["address"].keys()): huisnr = point['location']["address"]["streetnumber"] else: huisnr = '' if "boxnumber" in list(point['location']["address"].keys()): busnr = point['location']["address"]["boxnumber"] else: boxnr = '' postcode = point['location']["address"]["postalcode"] gemeente = point['location']["address"]["municipality"] else: straat = "" huisnr = "" busnr = "" postcode = "" gemeente = "" if "links" in point: link = point["links"][0]['href'] else: link = "" tijd = point["updated"] if "authors" in point: owner = point["authors"][0]["value"] else: owner = "" # add a feature fet = QgsFeature(fields) #set geometry fromCrs = QgsCoordinateReferenceSystem(4326) xform = QgsCoordinateTransform(fromCrs, self.poilayer.crs(), QgsProject.instance()) prjPt = xform.transform(pt) fet.setGeometry(QgsGeometry.fromPointXY(prjPt)) fet['id'] = int(poiId) fet['thema'] = theme fet['categorie'] = category fet['type'] = poiType fet['naam'] = name fet["email"] = email fet["telefoon"] = phone #address fet['straat'] = straat fet['huisnr'] = huisnr fet['busnr'] = busnr fet['postcode'] = postcode fet['gemeente'] = gemeente fet['link'] = link fet['lastupdate'] = tijd fet['owner'] = owner self.poiProvider.addFeatures([fet]) self.poilayer.updateExtents() if saveToFile and not QgsProject.instance().mapLayer(self.poilayerid): save = self._saveToFile(sender, startFolder) if save: fpath, flType = save error, msg = QgsVectorFileWriter.writeAsVectorFormat( self.poilayer, fileName=fpath, fileEncoding="utf-8", driverName=flType) if error == QgsVectorFileWriter.NoError: self.poilayer = QgsVectorLayer(fpath, layername, "ogr") self.poiProvider = self.poilayer.dataProvider() else: del self.poilayer, self.poiProvider raise Exception(msg) else: del self.poilayer, self.poiProvider return # add Labels text_format = QgsTextFormat() text_format.setSize(12) buffer_settings = QgsTextBufferSettings() buffer_settings.setEnabled(True) buffer_settings.setSize(1) buffer_settings.setColor(QColor("white")) palyr = QgsPalLayerSettings() text_format.setBuffer(buffer_settings) palyr.setFormat(text_format) palyr.enabled = True palyr.fieldName = 'naam' palyr.placement = QgsPalLayerSettings.Free self.poilayer.setLabelsEnabled(True) self.poilayer.setLabeling(QgsVectorLayerSimpleLabeling(palyr)) # add layer if not already QgsProject.instance().addMapLayer(self.poilayer) # store layer id and refresh self.poilayerid = self.poilayer.id() self.canvas.refresh()
def run(self): """Run method that performs all the real work""" # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start == True: self.first_start = False self.dlg = ReanalysisVisualizationDialog() project = QgsProject.instance() if not project.mapLayersByName('back'): layer = QgsVectorLayer( './background/ne_110m_admin_0_countries.shp', "back", "ogr") project.addMapLayer(layer) # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: params, variables, drawStyle, need_slideshow = self.dlg.prepare_form_data() try: root = QgsProject.instance().layerTreeRoot() group = root.findGroup('contours') if group: group.removeAllChildren() else: group = root.addGroup("contours") root.insertChildNode(-1, QgsLayerTreeLayer(project.mapLayersByName('back')[0])) root.removeLayer(project.mapLayersByName('back')[0]) data_grid = DataGrid(params, variables) geojsons = Isolines(data_grid, drawStyle).get_geojsons() for geojson in geojsons: layer = QgsVectorLayer( geojson['geojson'], "leadTime = " + str(geojson['leadTime']), "ogr") layer.setOpacity(0.87) # apply contour style properties symbol_layer = layer.renderer().symbol().symbolLayers()[0] symbol_layer.setDataDefinedProperty( QgsSymbolLayer.PropertyStrokeColor, QgsProperty.fromField("stroke")) symbol_layer.setDataDefinedProperty( QgsSymbolLayer.PropertyFillColor, QgsProperty.fromField("fill")) symbol_layer.setDataDefinedProperty( QgsSymbolLayer.PropertyStrokeWidth, QgsProperty.fromField("stroke-width")) # add labels pal_layer = QgsPalLayerSettings() pal_layer.fieldName = 'title' pal_layer.enabled = True pal_layer.placement = QgsPalLayerSettings.PerimeterCurved pal_layer.placementFlags = QgsPalLayerSettings.OnLine labeler = QgsVectorLayerSimpleLabeling(pal_layer) layer.setLabeling(labeler) layer.setLabelsEnabled(True) # add vector layer with isolines QgsProject.instance().addMapLayer(layer, False) group.insertChildNode(-1, QgsLayerTreeLayer(layer)) group.setIsMutuallyExclusive(True, 0) if need_slideshow: slideshow = threading.Thread( target=self.__change_active_layer, args=(group,)) slideshow.start() except Exception as e: error_text = '' if (params['east'] > 180 or params['east'] < -180 or params['west'] > 180 or params['west'] < -180 or params['south'] > 90 or params['south'] < -90 or params['north'] > 90 or params['north'] < -90): error_text += "Ошибка: Некорректно заданы координаты области" else: error_text += "Ошибка: \n" + str(e) error_dialog = QErrorMessage() error_dialog.showMessage(error_text) error_dialog.exec_()
def run(self): print("paso por el run") vl = iface.activeLayer() if vl.wkbType() == QgsWkbTypes.Polygon or vl.wkbType( ) == QgsWkbTypes.MultiPolygon: vl.startEditing() fields = vl.fields() idx = fields.indexFromName('hectareas') if idx == -1: myField = QgsField('hectareas', QVariant.Double) vl.dataProvider().addAttributes([myField]) vl.updateFields() for f in vl.getFeatures(): f.setAttribute(f.fieldNameIndex('hectareas'), f.geometry().area() / 10000) #f[idx] = '"$area"*1000' vl.updateFeature(f) vl.commitChanges() #coloco el puntero arriba del todo #QgsProject.instance().layerTreeRegistryBridge().setLayerInsertionPoint( QgsProject.instance().layerTreeRoot(), 0 ) #defino simbologia sym1 = QgsFillSymbol.createSimple({ 'style': 'vertical', 'color': '0,0,0,0', 'outline_color': 'red' }) renderer = QgsSingleSymbolRenderer(sym1) #defino formato etiquetas layer_settings = QgsPalLayerSettings() text_format = QgsTextFormat() text_format.setFont(QFont("Arial", 12)) text_format.setSize(12) text_format.setColor(QColor("Red")) layer_settings.setFormat(text_format) # defino etiquetas layer_settings.fieldName = '''concat(format_number("hectareas",2),' ha.')''' layer_settings.isExpression = True layer_settings.enabled = True layer_settings = QgsVectorLayerSimpleLabeling(layer_settings) vl.setLabelsEnabled(True) vl.setLabeling(layer_settings) vl.triggerRepaint() vl.setRenderer(renderer) #QgsProject.instance().addMapLayer(v1) #QgsProject.instance().removeMapLayer(layer) #canvas.freeze(False) vl.updateExtents() vl.commitChanges() vl.updateExtents() #canvas.setExtent(lyr9.extent()) """Run method that performs all the real work""" # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start == True: self.first_start = False
def save_pois_points(self, points, layername="Geopunt_poi", saveToFile=None, sender=None, startFolder=None ): attributes = [ QgsField("id", QVariant.Int), QgsField("thema", QVariant.String), QgsField("categorie", QVariant.String), QgsField("type", QVariant.String), QgsField("naam", QVariant.String), QgsField("telefoon", QVariant.String), QgsField("email", QVariant.String) , #address QgsField("straat", QVariant.String), QgsField("huisnr", QVariant.String), QgsField("busnr", QVariant.String), QgsField("postcode", QVariant.String), QgsField("gemeente", QVariant.String), QgsField("link", QVariant.String), QgsField("lastupdate", QVariant.String), QgsField("owner", QVariant.String) ] if not QgsProject.instance().mapLayer(self.poilayerid) : self.poilayer = QgsVectorLayer("Point", layername, "memory") self.poiProvider = self.poilayer.dataProvider() self.poiProvider.addAttributes(attributes) self.poilayer.updateFields() fields=self.poilayer.fields() for point in points: pt = QgsPointXY( point['location']['points'][0]['Point']['coordinates'][0], point['location']['points'][0]['Point']['coordinates'][1] ) poiId = point["id"] if "categories" in list(point.keys()) and len(point["categories"]) > 0: theme = point["categories"][0]['value'] else: theme = '' if "categories" in list(point.keys()) and len(point["categories"]) > 1: category = point["categories"][1]['value'] else: category = '' if "categories" in point and len(point["categories"]) > 2: poiType = point["categories"][2]['value'] else: poiType = '' name = point["labels"][0]["value"] if "phone" in list(point.keys()): phone = point["phone"] else: phone= "" if "email" in list(point.keys()): email = point["email"] else: email= "" #address if "address" in list(point['location'].keys()): if "street" in list(point['location']["address"].keys()): straat = point['location']["address"]["street"] else: straat = '' if "streetnumber" in list(point['location']["address"].keys()): huisnr = point['location']["address"]["streetnumber"] else: huisnr = '' if "boxnumber" in list(point['location']["address"].keys()): busnr = point['location']["address"]["boxnumber"] else: boxnr = '' postcode = point['location']["address"]["postalcode"] gemeente = point['location']["address"]["municipality"] else: straat = "" huisnr = "" busnr = "" postcode = "" gemeente = "" if "links" in point: link = point["links"][0]['href'] else: link = "" tijd = point["updated"] if "authors" in point: owner = point["authors"][0]["value"] else: owner= "" # add a feature fet = QgsFeature(fields) #set geometry fromCrs = QgsCoordinateReferenceSystem(4326) xform = QgsCoordinateTransform( fromCrs, self.poilayer.crs(), QgsProject.instance() ) prjPt = xform.transform( pt ) fet.setGeometry(QgsGeometry.fromPointXY(prjPt)) fet['id'] = int( poiId ) fet['thema'] = theme fet['categorie'] = category fet['type'] = poiType fet['naam'] = name fet["email"] = email fet["telefoon"] = phone #address fet['straat'] = straat fet['huisnr'] = huisnr fet['busnr'] = busnr fet['postcode'] = postcode fet['gemeente'] = gemeente fet['link'] = link fet['lastupdate'] = tijd fet['owner'] = owner self.poiProvider.addFeatures([ fet ]) self.poilayer.updateExtents() if saveToFile and not QgsProject.instance().mapLayer(self.poilayerid): save = self._saveToFile( sender, startFolder ) if save: fpath, flType = save error, msg = QgsVectorFileWriter.writeAsVectorFormat(self.poilayer,fileName=fpath, fileEncoding="utf-8", driverName=flType ) if error == QgsVectorFileWriter.NoError: self.poilayer = QgsVectorLayer( fpath , layername, "ogr") self.poiProvider = self.poilayer.dataProvider() else: del self.poilayer, self.poiProvider raise Exception( msg ) else: del self.poilayer, self.poiProvider return # add Labels text_format = QgsTextFormat() text_format.setSize(12) buffer_settings = QgsTextBufferSettings() buffer_settings.setEnabled(True) buffer_settings.setSize(1) buffer_settings.setColor(QColor("white")) palyr = QgsPalLayerSettings() text_format.setBuffer(buffer_settings) palyr.setFormat(text_format) palyr.enabled = True palyr.fieldName = 'naam' palyr.placement = QgsPalLayerSettings.Free self.poilayer.setLabelsEnabled(True) self.poilayer.setLabeling( QgsVectorLayerSimpleLabeling(palyr) ) # add layer if not already QgsProject.instance().addMapLayer(self.poilayer) # store layer id and refresh self.poilayerid = self.poilayer.id() self.canvas.refresh()
def btnConstruct_Click(self): flag = FlightPlanBaseSimpleDlg.btnConstruct_Click(self) if not flag: return constructionLayer = AcadHelper.createVectorLayer(SurfaceTypes.DmeTolerance, QGis.Line) point3d1 = self.parametersPanel.pnlDME.Point3d circleAreaList = [] # length = self.groundDistance.Metres / 5 # # rectangle = QgsRectangle(point3d1.get_X() - length / 2, point3d1.get_Y() - length / 2, point3d1.get_X() + length / 2, point3d1.get_Y() + length / 2,) # point1 = Point3D(point3d1.get_X() - length / 2, point3d1.get_Y() + length / 2) # point2 = Point3D(point3d1.get_X() - length / 2, point3d1.get_Y() - length / 2) captionCircleLine = [] centerPoint = None radius = 0.0 arc = None; resultPoint3dArrayList = [] if (self.groundDistance.Metres > 0): metres = self.dmeTolerance.valueMetres / 1.7; if (self.parametersPanel.cmbConstructionType.currentIndex() != 0): num1 = Unit.ConvertDegToRad(float(self.parametersPanel.pnlRadial.Value)); num2 = math.asin(min([1 / self.groundDistance.NauticalMiles, 1])); num3 = num1 + num2 num4 = num1 - num2 # arc = PolylineArea() # arc.Add(PolylineAreaPoint(point3d1, self.groundDistance.Metres)) arc = MathHelper.constructArc(point3d1, self.groundDistance.Metres, num3, num4, 30); point3d = MathHelper.distanceBearingPoint(point3d1, num1, self.groundDistance.Metres); captionCircleLine = [MathHelper.distanceBearingPoint(point3d, MathHelper.getBearing(point3d, point3d1) + math.pi / 2, self.groundDistance.Metres / 20), MathHelper.distanceBearingPoint(point3d, MathHelper.getBearing(point3d, point3d1) - math.pi / 2, self.groundDistance.Metres / 20)] num = -num1; if (self.parametersPanel.chbDrawRadial.isChecked()): line = PolylineArea([point3d1, point3d]); resultPoint3dArrayList.append([point3d1, point3d]) # AcadHelper.smethod_18(transaction, blockTableRecord, line, constructionLayer); else: arc = MathHelper.constructCircle(point3d1, self.groundDistance.Metres, 50); circleAreaList.append(PolylineArea(None, point3d1, self.groundDistance.Metres)) centerPoint = point3d1 radius = self.groundDistance.Metres point3d = MathHelper.distanceBearingPoint(point3d1, 0, self.groundDistance.Metres); length = self.groundDistance.Metres / 5 # rectangle = QgsRectangle(point3d1.get_X() - length / 2, point3d1.get_Y() - length / 2, point3d1.get_X() + length / 2, point3d1.get_Y() + length / 2,) point1 = MathHelper.distanceBearingPoint(point3d, Unit.ConvertDegToRad(270), length / 4)#Point3D(point3d.get_X() - length / 4, point3d.get_Y()) point2 = MathHelper.distanceBearingPoint(point3d, Unit.ConvertDegToRad(90), length / 4)#Point3D(point3d.get_X() + length / 4, point3d.get_Y()) captionCircleLine = [point1, point2] num = 0; resultPoint3dArrayList.append(arc) # AcadHelper.smethod_18(transaction, blockTableRecord, arc, constructionLayer); if (self.parametersPanel.chbWriteText.isChecked()): nauticalMiles = self.groundDistance.NauticalMiles; # DBText dBText = AcadHelper.smethod_138(string.Format("{0} DME", nauticalMiles.ToString("0.#")), point3d, metres, 1); # dBText.set_Rotation(num); # AcadHelper.smethod_18(transaction, blockTableRecord, dBText, constructionLayer); if (self.parametersPanel.chbDrawDmeTol.isVisible() and self.parametersPanel.chbDrawDmeTol.isChecked() and self.dmeTolerance.IsValid() and arc != None): offsetCurf = QgisHelper.offsetCurve(arc, self.dmeTolerance.Metres) if self.parametersPanel.cmbConstructionType.currentIndex() == 0: circleAreaList.append(PolylineArea(None, centerPoint, radius + self.dmeTolerance.Metres)) if (self.parametersPanel.cmbConstructionType.currentIndex() == 0): endPoint = offsetCurf[0] offsetCurf.append(endPoint) resultPoint3dArrayList.append(offsetCurf) # foreach (Entity offsetCurf in arc.GetOffsetCurves(self.dmeTolerance.Metres)) # { # AcadHelper.smethod_19(transaction, blockTableRecord, offsetCurf, constructionLayer, 5); # } entity = QgisHelper.offsetCurve(arc, -(self.dmeTolerance.Metres + self.slantTolerance.Metres)) if self.parametersPanel.cmbConstructionType.currentIndex() == 0: circleAreaList.append(PolylineArea(None, centerPoint, radius -(self.dmeTolerance.Metres + self.slantTolerance.Metres))) if (self.parametersPanel.cmbConstructionType.currentIndex() == 0): endPoint = entity[0] entity.append(endPoint) resultPoint3dArrayList.append(entity) # foreach (Entity entity in arc.GetOffsetCurves(-(self.dmeTolerance.Metres + self.slantTolerance.Metres))) # { # AcadHelper.smethod_19(transaction, blockTableRecord, entity, constructionLayer, 5); # } # } if (self.parametersPanel.chbDrawSlantTol.isVisible() and self.parametersPanel.chbDrawSlantTol.isChecked() and self.slantTolerance.IsValid() and arc != None): offsetCurf1 = QgisHelper.offsetCurve(arc, -self.slantTolerance.Metres) if self.parametersPanel.cmbConstructionType.currentIndex() == 0: circleAreaList.append(PolylineArea(None, centerPoint, radius -self.slantTolerance.Metres)) if (self.parametersPanel.cmbConstructionType.currentIndex() == 0): endPoint = offsetCurf1[0] offsetCurf1.append(endPoint) resultPoint3dArrayList.append(offsetCurf1) # foreach (Entity offsetCurf1 in arc.GetOffsetCurves(-self.slantTolerance.Metres)) # { # AcadHelper.smethod_19(transaction, blockTableRecord, offsetCurf1, constructionLayer, 2); # } # } if (self.parametersPanel.chbInsertSymbol.isChecked()): length = self.groundDistance.Metres / 5 rectangle = QgsRectangle(point3d1.get_X() - length / 2, point3d1.get_Y() - length / 2, point3d1.get_X() + length / 2, point3d1.get_Y() + length / 2,) point1 = MathHelper.distanceBearingPoint(point3d1, Unit.ConvertDegToRad(315), length / 2)#Point3D(point3d1.get_X() - length / 2, point3d1.get_Y() + length / 2) point2 = MathHelper.distanceBearingPoint(point3d1, Unit.ConvertDegToRad(225), length / 2)#Point3D(point3d1.get_X() - length / 2, point3d1.get_Y() - length / 2) point3 = MathHelper.distanceBearingPoint(point3d1, Unit.ConvertDegToRad(135), length / 2)#Point3D(point3d1.get_X() + length / 2, point3d1.get_Y() - length / 2) point4 = MathHelper.distanceBearingPoint(point3d1, Unit.ConvertDegToRad(45), length / 2)#Point3D(point3d1.get_X() + length / 2, point3d1.get_Y() + length / 2) resultPoint3dArrayList.append([point1, point2, point3, point4, point1]) # Symbol symbol = new Symbol(SymbolType.Dme); # AcadHelper.smethod_57(transaction, blockTableRecord, symbol.BlockName, symbol.BlockFileName, point3d1, new Scale3d(1), 0, constructionLayer, None); # } for point3dArray in resultPoint3dArrayList: if (self.parametersPanel.cmbConstructionType.currentIndex() != 0): bulge = MathHelper.smethod_60(point3dArray[0], point3dArray[int(len(point3dArray)/2)], point3dArray[len(point3dArray)-1]) AcadHelper.setGeometryAndAttributesInLayer(constructionLayer, point3dArray, False, {"Bulge":bulge}) if self.parametersPanel.cmbConstructionType.currentIndex() == 0: for area in circleAreaList: AcadHelper.setGeometryAndAttributesInLayer(constructionLayer, area) if self.parametersPanel.chbInsertSymbol.isChecked(): AcadHelper.setGeometryAndAttributesInLayer(constructionLayer, [point1, point2, point3, point4, point1]) if (self.parametersPanel.chbWriteText.isChecked()): AcadHelper.setGeometryAndAttributesInLayer(constructionLayer, captionCircleLine, False, {"Caption":"3DME"} ) palSetting = QgsPalLayerSettings() palSetting.readFromLayer(constructionLayer) palSetting.enabled = True palSetting.fieldName = "Caption" palSetting.isExpression = True palSetting.placement = QgsPalLayerSettings.Line palSetting.placementFlags = QgsPalLayerSettings.AboveLine palSetting.setDataDefinedProperty(QgsPalLayerSettings.Size, True, True, '12', "") palSetting.writeToLayer(constructionLayer) QgisHelper.appendToCanvas(define._canvas, [constructionLayer], self.surfaceType, True) QgisHelper.zoomToLayers([constructionLayer]) self.resultLayerList = [constructionLayer]
def extract_layers(self, tree): """Return a list of RFU layers.""" # Create vector layers.. l_vertex = QgsVectorLayer(r"Point?crs=epsg:4326&index=yes", u"Sommet RFU", r"memory") l_edge = QgsVectorLayer(r"LineString?crs=epsg:4326&index=yes", u"Limite RFU", r"memory") p_vertex = l_vertex.dataProvider() p_edge = l_edge.dataProvider() # Define default style renderer.. renderer_vertex = QgsRuleBasedRendererV2(QgsMarkerSymbolV2()) vertex_root_rule = renderer_vertex.rootRule() vertex_rules = ( ( (u"Borne, borne à puce, pierre, piquet, clou ou broche"), (u"$id >= 0 AND \"som_nature\" IN ('Borne'," u"'Borne à puce', 'Pierre', 'Piquet', 'Clou ou broche')"), r"#EC0000", 2.2 ), ( (u"Axe cours d'eau, axe fossé, haut de talus, pied de talus"), (u"$id >= 0 AND \"som_nature\" IN ('Axe cours d\'\'eau'," u"'Axe fossé', 'Haut de talus', 'Pied de talus')"), r"#EE8012", 2.2 ), ( (u"Angle de bâtiment, axe de mur, angle de mur, " u"angle de clôture, pylône et toute autre valeur"), (u"$id >= 0 AND \"som_nature\" NOT IN ('Borne'," u"'Borne à puce', 'Pierre', 'Piquet', 'Clou ou broche'," u"'Axe cours d\'\'eau', 'Axe fossé', 'Haut de talus'," u"'Pied de talus')"), r"#9784EC", 2.2 ), ( u"Temporaire", r"$id < 0", "cyan", 2.4 )) for label, expression, color, size in vertex_rules: rule = vertex_root_rule.children()[0].clone() rule.setLabel(label) rule.setFilterExpression(expression) rule.symbol().setColor(QColor(color)) rule.symbol().setSize(size) vertex_root_rule.appendChild(rule) vertex_root_rule.removeChildAt(0) l_vertex.setRendererV2(renderer_vertex) renderer_edge = QgsRuleBasedRendererV2(QgsLineSymbolV2()) edge_root_rule = renderer_edge.rootRule() edge_rules = ((r"Limite", r"$id >= 0", "#0A0AFF", 0.5), (r"Temporaire", r"$id < 0", "cyan", 1)) for label, expression, color, width in edge_rules: rule = edge_root_rule.children()[0].clone() rule.setLabel(label) rule.setFilterExpression(expression) rule.symbol().setColor(QColor(color)) rule.symbol().setWidth(width) edge_root_rule.appendChild(rule) edge_root_rule.removeChildAt(0) l_edge.setRendererV2(renderer_edge) # Add fields.. p_vertex.addAttributes([ QgsField(r"@id_noeud", QVariant.Int), # QgsField(r"@changeset", QVariant.Int), # QgsField(r"@timestamp", QVariant.Date), QgsField(r"@version", QVariant.Int), QgsField(r"som_ge_createur", QVariant.String), QgsField(r"som_nature", QVariant.String), QgsField(r"som_precision_rattachement", QVariant.Int), QgsField(r"som_coord_est", QVariant.Double), QgsField(r"som_coord_nord", QVariant.Double), QgsField(r"som_representation_plane", QVariant.String), # QgsField(r"date_creation", QVariant.Date) ]) p_edge.addAttributes([ QgsField(r"@id_arc", QVariant.Int), # QgsField(r"@id_noeud_debut", QVariant.Int), # QgsField(r"@id_noeud_fin", QVariant.Int), # QgsField(r"@changeset", QVariant.Int), # QgsField(r"@timestamp", QVariant.Date), QgsField(r"@version", QVariant.Int), QgsField(r"lim_ge_createur", QVariant.String), # QgsField(r"lim_date_creation", QVariant.Date) ]) # Add features from xml tree.. # ..to vertex layer.. fts_vertex = [] for e in tree.findall(r"sommet"): ft_vertex = QgsFeature() ft_vertex.setGeometry(QgsGeometry.fromWkt(e.attrib[r"geometrie"])) _id_noeud = int(e.attrib[r"id_noeud"]) # _changeset = int(e.attrib[r"changeset"]) # _timestamp = QDateTime(datetime.strptime( # e.attrib[r"timestamp"], r"%Y-%m-%d %H:%M:%S.%f")) _version = int(e.attrib[r"version"]) som_ge_createur = unicode(e.find(r"./som_ge_createur").text) som_nature = unicode(e.find(r"./som_nature").text) som_prec_rattcht = int(e.find(r"./som_precision_rattachement").text) som_coord_est = float(e.find(r"./som_coord_est").text) som_coord_nord = float(e.find(r"./som_coord_nord").text) som_repres_plane = unicode(e.find(r"./som_representation_plane").text) # som_date_creation = QDate(datetime.strptime( # e.find(r"./som_date_creation").text, r"%Y-%m-%d").date()) ft_vertex.setAttributes([ _id_noeud, # _changeset, # _timestamp, _version, som_ge_createur, som_nature, som_prec_rattcht, som_coord_est, som_coord_nord, som_repres_plane, # som_date_creation ]) fts_vertex.append(ft_vertex) # ..to edge layer.. fts_edge = [] for e in tree.findall(r"limite"): ft_edge = QgsFeature() ft_edge.setGeometry(QgsGeometry.fromWkt(e.attrib[r"geometrie"])) _id_arc = int(e.attrib[r"id_arc"]) # _id_noeud_debut = int(e.attrib[r"id_noeud_debut"]) # _id_noeud_fin = int(e.attrib[r"id_noeud_fin"]) # _changeset = int(e.attrib[r"changeset"]) # _timestamp = QDateTime(datetime.strptime( # e.attrib[r"timestamp"], r"%Y-%m-%d %H:%M:%S.%f")) _version = int(e.attrib[r"version"]) lim_ge_createur = unicode(e.find(r"./lim_ge_createur").text) # lim_date_creation = QDate(datetime.strptime( # e.find(r"./lim_date_creation").text, r"%Y-%m-%d").date()) ft_edge.setAttributes([ _id_arc, # _id_noeud_debut, # _id_noeud_fin, # _changeset, # _timestamp, _version, lim_ge_createur, # lim_date_creation ]) fts_edge.append(ft_edge) # Add features to layers.. p_vertex.addFeatures(fts_vertex) p_edge.addFeatures(fts_edge) # Update fields.. l_vertex.updateFields() l_edge.updateFields() # Update layer's extent.. l_vertex.updateExtents() l_edge.updateExtents() # Check if valid.. if not l_vertex.isValid() or not l_edge.isValid(): raise Exception(u"Une erreur est survenue lors du chargement de la couche.") # Set labelling... palyr = QgsPalLayerSettings() palyr.enabled = True # palyr.readFromLayer(l_vertex) palyr.fieldName = r"$id" # Expression $id palyr.placement = 1 # ::OverPoint palyr.quadOffset = 2 # ::QuadrantAboveRight palyr.setDataDefinedProperty(80, True, True, r"1", "") # ::OffsetUnits -> ::MM palyr.xOffset = 2.0 palyr.yOffset = -1.0 palyr.writeToLayer(l_vertex) # Then return layers.. return [l_vertex, l_edge]
def showMarkDaSoc(self): try: flag = FlightPlanBaseDlg.btnConstruct_Click(self) # if not flag: # return point3dThr = self.parametersPanel.pnlThrPosition.Point3d point3dFaf = self.parametersPanel.pnlFapPosition.Point3d inboundTrackRad = Unit.ConvertDegToRad(self.parametersPanel.pnlInboundTrack.Value)#MathHelper.getBearing(point3dFaf, point3dThr) inboundTrack180Rad = MathHelper.smethod_4(inboundTrackRad + math.pi) estimatedAltitdeMeters = self.parametersPanel.pnlEstimatedAltitude.Value.Metres thrAltitudeMeters = self.parametersPanel.pnlThrPosition.Altitude().Metres heightLossAltitudeMeters = self.parametersPanel.pnlHeightLoss.Value.Metres rdhAltitudeMeters = self.parametersPanel.pnlRDH.Value.Metres vpa = Unit.ConvertDegToRad(self.getVPA()) xz = self.parametersPanel.pnlDistXz.Value.Metres socThrDistMeters = ((estimatedAltitdeMeters - thrAltitudeMeters - heightLossAltitudeMeters) / math.tan(vpa)) + xz daThrDistMeters = (estimatedAltitdeMeters - thrAltitudeMeters - rdhAltitudeMeters) / math.tan(vpa) sockBearing = inboundTrackRad # if socThrDistMeters < 0: # sockBearing = inboundTrack180Rad # socThrDistMeters = math.fabs(socThrDistMeters) # else: # sockBearing = inboundTrackRad daBearing = inboundTrack180Rad # if daThrDistMeters < 0: # daBearing = inboundTrackRad # daThrDistMeters = math.fabs(daThrDistMeters) # else: # daBearing = inboundTrack180Rad self.socPoint3d = MathHelper.distanceBearingPoint(point3dThr, sockBearing, -socThrDistMeters).smethod_167(self.calcSocAltitude()) self.daPoint3d = MathHelper.distanceBearingPoint(point3dThr, daBearing, daThrDistMeters) daSocLayer = AcadHelper.createVectorLayer("DA_SOC_" + self.surfaceType, QGis.Point) AcadHelper.setGeometryAndAttributesInLayer(daSocLayer, self.socPoint3d, False, {"Caption":"SOC"}) AcadHelper.setGeometryAndAttributesInLayer(daSocLayer, self.daPoint3d, False, {"Caption":"DA"}) QgisHelper.appendToCanvas(define._canvas, [daSocLayer], self.surfaceType) palSetting = QgsPalLayerSettings() palSetting.readFromLayer(daSocLayer) palSetting.enabled = True palSetting.fieldName = "Caption" palSetting.isExpression = True palSetting.placement = QgsPalLayerSettings.AroundPoint palSetting.setDataDefinedProperty(QgsPalLayerSettings.Size, True, True, '8', "") palSetting.writeToLayer(daSocLayer) QgisHelper.zoomToLayers([daSocLayer]) self.resultLayerList = [daSocLayer] # # show SOC Mark # point3d = MathHelper.distanceBearingPoint(self.socPoint3d, Unit.ConvertDegToRad(450) - 0, 100) # point3d1 = MathHelper.distanceBearingPoint(self.socPoint3d, Unit.ConvertDegToRad(450) - math.pi / 2, 100) # point3d2 = MathHelper.distanceBearingPoint(self.socPoint3d, Unit.ConvertDegToRad(450) - math.pi, 100) # point3d3 = MathHelper.distanceBearingPoint(self.socPoint3d, Unit.ConvertDegToRad(450) - (math.pi * 3) / 2 , 100) # # if self.socRubber == None: # self.socRubber = QgsRubberBand(define._canvas, QGis.Line) # self.socRubber.setColor(Qt.yellow) # else: # self.socRubber.reset(QGis.Line) # self.socRubber.addGeometry(QgsGeometry.fromPolyline([point3d, point3d2]), None) # self.socRubber.addGeometry(QgsGeometry.fromPolyline([point3d1, point3d3]), None) # circle = MathHelper.constructCircle(self.socPoint3d, 100, 16) # self.socRubber.addGeometry(QgsGeometry.fromPolyline(circle), None) # self.socRubber.show() # # self.socAnnotation.setMapPosition(self.socPoint3d) # self.socAnnotation.show() # # # show DA Mark # point3d = MathHelper.distanceBearingPoint(self.daPoint3d, Unit.ConvertDegToRad(450) - 0, 100) # point3d1 = MathHelper.distanceBearingPoint(self.daPoint3d, Unit.ConvertDegToRad(450) - math.pi / 2, 100) # point3d2 = MathHelper.distanceBearingPoint(self.daPoint3d, Unit.ConvertDegToRad(450) - math.pi, 100) # point3d3 = MathHelper.distanceBearingPoint(self.daPoint3d, Unit.ConvertDegToRad(450) - (math.pi * 3) / 2 , 100) # # if self.daRubber == None: # self.daRubber = QgsRubberBand(define._canvas, QGis.Line) # self.daRubber.setColor(Qt.yellow) # else: # self.daRubber.reset(QGis.Line) # self.daRubber.addGeometry(QgsGeometry.fromPolyline([point3d, point3d2]), None) # self.daRubber.addGeometry(QgsGeometry.fromPolyline([point3d1, point3d3]), None) # circle = MathHelper.constructCircle(self.daPoint3d, 100, 16) # self.daRubber.addGeometry(QgsGeometry.fromPolyline(circle), None) # self.daRubber.show() # # self.daAnnotation.setMapPosition(self.daPoint3d) # self.daAnnotation.show() self.putDistances() return daSocLayer except: pass