Ejemplo n.º 1
2
    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())
Ejemplo n.º 2
1
    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()
Ejemplo n.º 3
0
    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 defaultSettings(self):
     lyr = QgsPalLayerSettings()
     lyr.enabled = True
     lyr.fieldName = 'text'  # default in data sources
     lyr.textFont = self._TestFont
     lyr.textNamedStyle = 'Medium'
     return lyr
Ejemplo n.º 5
0
    def checkLabeledLayerWithBlendModesCannotBeCached(self, job_type):
        """ any labeled layer utilising blending modes cannot be cached"""
        layer = QgsVectorLayer("Point?field=fldtxt:string",
                               "layer1", "memory")

        labelSettings = QgsPalLayerSettings()
        labelSettings.fieldName = "fldtxt"
        layer.setLabeling(QgsVectorLayerSimpleLabeling(labelSettings))
        layer.setLabelsEnabled(True)

        layer2 = QgsVectorLayer("Point?field=fldtxt:string",
                                "layer2", "memory")
        labelSettings2 = QgsPalLayerSettings()
        labelSettings2.fieldName = "fldtxt"
        format2 = QgsTextFormat()
        format2.setBlendMode(QPainter.CompositionMode_SourceIn)
        labelSettings2.setFormat(format2)
        layer2.setLabeling(QgsVectorLayerSimpleLabeling(labelSettings2))
        layer2.setLabelsEnabled(True)

        settings = QgsMapSettings()
        settings.setExtent(QgsRectangle(5, 25, 25, 45))
        settings.setOutputSize(QSize(600, 400))
        settings.setLayers([layer, layer2])

        # with cache - cache should not be populated!
        cache = QgsMapRendererCache()
        job = job_type(settings)
        job.setCache(cache)
        job.start()
        job.waitForFinished()
        self.assertFalse(job.usedCachedLabels())
        self.assertFalse(cache.hasCacheImage('_labels_'))
        self.assertTrue(job.takeLabelingResults())

        # second job should also not be able to use label cache
        job = job_type(settings)
        job.setCache(cache)
        job.start()
        job.waitForFinished()
        # shouldn't use cache
        self.assertFalse(job.usedCachedLabels())
        # and results should not have been cached
        self.assertFalse(cache.hasCacheImage('_labels_'))
        self.assertTrue(job.takeLabelingResults())
Ejemplo n.º 6
0
 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
Ejemplo n.º 7
0
 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
Ejemplo n.º 8
0
 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
Ejemplo n.º 9
0
 def defaultLayerSettings(self):
     lyr = QgsPalLayerSettings()
     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
Ejemplo n.º 10
0
    def checkRemovingLabeledLayerInvalidatesLabelCache(self, job_type):
        """ removing a previously labeled layer should invalidate any previous label caches"""
        layer = QgsVectorLayer("Point?field=fldtxt:string",
                               "layer1", "memory")

        labelSettings = QgsPalLayerSettings()
        labelSettings.fieldName = "fldtxt"
        layer.setLabeling(QgsVectorLayerSimpleLabeling(labelSettings))
        layer.setLabelsEnabled(True)

        layer2 = QgsVectorLayer("Point?field=fldtxt:string",
                                "layer2", "memory")
        layer2.setLabeling(QgsVectorLayerSimpleLabeling(labelSettings))
        layer2.setLabelsEnabled(True)

        settings = QgsMapSettings()
        settings.setExtent(QgsRectangle(5, 25, 25, 45))
        settings.setOutputSize(QSize(600, 400))
        settings.setLayers([layer, layer2])

        # with cache - first run should populate cache
        cache = QgsMapRendererCache()
        job = job_type(settings)
        job.setCache(cache)
        job.start()
        job.waitForFinished()
        self.assertFalse(job.usedCachedLabels())
        self.assertTrue(cache.hasCacheImage('_labels_'))
        self.assertTrue(job.takeLabelingResults())

        self.assertEqual(set(cache.dependentLayers('_labels_')), {layer, layer2})

        # remove a previously labeled layer
        settings.setLayers([layer2])

        # second job should not be able to use label cache, since a labeled layer was removed
        job = job_type(settings)
        job.setCache(cache)
        job.start()
        job.waitForFinished()
        # shouldn't use cache
        self.assertFalse(job.usedCachedLabels())
        # but results should have been cached
        self.assertTrue(cache.hasCacheImage('_labels_'))
        self.assertEqual(set(cache.dependentLayers('_labels_')), {layer2})
        self.assertTrue(job.takeLabelingResults())
Ejemplo n.º 11
0
 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))
Ejemplo n.º 12
0
    def checkAddingNewNonLabeledLayerKeepsLabelCache(self, job_type):
        """ adding a new non-labeled layer should keep any previous label caches"""
        layer = QgsVectorLayer("Point?field=fldtxt:string",
                               "layer1", "memory")

        labelSettings = QgsPalLayerSettings()
        labelSettings.fieldName = "fldtxt"
        layer.setLabeling(QgsVectorLayerSimpleLabeling(labelSettings))
        layer.setLabelsEnabled(True)

        settings = QgsMapSettings()
        settings.setExtent(QgsRectangle(5, 25, 25, 45))
        settings.setOutputSize(QSize(600, 400))
        settings.setLayers([layer])

        # with cache - first run should populate cache
        cache = QgsMapRendererCache()
        job = job_type(settings)
        job.setCache(cache)
        job.start()
        job.waitForFinished()
        self.assertFalse(job.usedCachedLabels())
        self.assertTrue(cache.hasCacheImage('_labels_'))
        self.assertTrue(job.takeLabelingResults())

        self.assertEqual(cache.dependentLayers('_labels_'), [layer])

        # add another, non-labeled layer
        layer2 = QgsVectorLayer("Point?field=fldtxt:string",
                                "layer2", "memory")
        settings.setLayers([layer, layer2])

        # second job should use label cache, since new layer was not labeled
        job = job_type(settings)
        job.setCache(cache)
        job.start()
        job.waitForFinished()
        # should use cache
        self.assertTrue(job.usedCachedLabels())
        # results should have been cached
        self.assertTrue(cache.hasCacheImage('_labels_'))
        self.assertEqual(set(cache.dependentLayers('_labels_')), {layer})
        self.assertTrue(job.takeLabelingResults())
Ejemplo n.º 13
0
    def createLayer(self):
        '''Create a memory layer from the zoom to locations'''
        rowcnt = self.resultsTable.rowCount()
        if rowcnt == 0:
            return
        attr = []
        for item, label in enumerate(LABELS[0:self.numCol]):
            label = label.lower()
            if item <= 1:
                attr.append(QgsField(label, QVariant.Double))
            else:
                attr.append(QgsField(label, QVariant.String))
        ptLayer = QgsVectorLayer("Point?crs=epsg:4326", u"Lat Lon Locations",
                                 "memory")
        provider = ptLayer.dataProvider()
        provider.addAttributes(attr)
        ptLayer.updateFields()

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

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

        QgsProject.instance().addMapLayer(ptLayer)
    def saveToLayer(self):
        units = self.unitDesignator()
        canvasCrs = self.canvas.mapSettings().destinationCrs()
        fields = QgsFields()
        fields.append(QgsField("label", QVariant.String))
        fields.append(QgsField("value", QVariant.Double))
        fields.append(QgsField("units", QVariant.String))
        fields.append(QgsField("heading_to", QVariant.Double))
        fields.append(QgsField("heading_from", QVariant.Double))

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

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

        label = QgsPalLayerSettings()
        label.fieldName = 'label'
        label.placement = QgsPalLayerSettings.AboveLine
        labeling = QgsVectorLayerSimpleLabeling(label)
        layer.setLabeling(labeling)
        layer.setLabelsEnabled(True)

        layer.updateExtents()
        QgsProject.instance().addMapLayer(layer)
Ejemplo n.º 15
0
    def checkAddingNewNonLabeledLayerKeepsLabelCache(self, job_type):
        """ adding a new non-labeled layer should keep any previous label caches"""
        layer = QgsVectorLayer("Point?field=fldtxt:string", "layer1", "memory")

        labelSettings = QgsPalLayerSettings()
        labelSettings.fieldName = "fldtxt"
        layer.setLabeling(QgsVectorLayerSimpleLabeling(labelSettings))
        layer.setLabelsEnabled(True)

        settings = QgsMapSettings()
        settings.setExtent(QgsRectangle(5, 25, 25, 45))
        settings.setOutputSize(QSize(600, 400))
        settings.setLayers([layer])

        # with cache - first run should populate cache
        cache = QgsMapRendererCache()
        job = job_type(settings)
        job.setCache(cache)
        job.start()
        job.waitForFinished()
        self.assertFalse(job.usedCachedLabels())
        self.assertTrue(cache.hasCacheImage('_labels_'))
        self.assertTrue(job.takeLabelingResults())

        self.assertEqual(cache.dependentLayers('_labels_'), [layer])

        # add another, non-labeled layer
        layer2 = QgsVectorLayer("Point?field=fldtxt:string", "layer2",
                                "memory")
        settings.setLayers([layer, layer2])

        # second job should use label cache, since new layer was not labeled
        job = job_type(settings)
        job.setCache(cache)
        job.start()
        job.waitForFinished()
        # should use cache
        self.assertTrue(job.usedCachedLabels())
        # results should have been cached
        self.assertTrue(cache.hasCacheImage('_labels_'))
        self.assertEqual(set(cache.dependentLayers('_labels_')), {layer})
        self.assertTrue(job.takeLabelingResults())
Ejemplo n.º 16
0
 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))
Ejemplo n.º 17
0
    def grid_labeler(self, coord_base_x, coord_base_y, px, py, u, t, dx, dy,
                     vAlign, hAlign, desc, fSize, fontType, expression_str,
                     trLLUTM, trUTMLL, llcolor, utmcheck, scale):
        if utmcheck:
            pgrid = QgsPoint(coord_base_x + px * u, coord_base_y + py * t)
            pgrid.transform(trLLUTM)
            pgrid = QgsPoint(pgrid.x() + dx, pgrid.y() + dy)
        else:
            pgrid = QgsPoint(coord_base_x + px * u + dx,
                             coord_base_y + py * t + dy)

        #Label Format Settings
        settings = QgsPalLayerSettings()
        settings.Placement = QgsPalLayerSettings.Free
        settings.isExpression = True
        textprop = QgsTextFormat()
        textprop.setColor(llcolor)
        textprop.setSizeUnit(1)
        textprop.setSize(fSize * scale * 1.324)
        textprop.setFont(QFont(fontType))
        textprop.setLineHeight(1)
        settings.setFormat(textprop)
        settings.fieldName = expression_str

        #Label Name and Position
        datadefined = QgsPropertyCollection()
        datadefined.setProperty(9, pgrid.x())
        datadefined.setProperty(10, pgrid.y())
        if not (hAlign == ''):
            datadefined.setProperty(11, hAlign)
        if not (vAlign == ''):
            datadefined.setProperty(12, vAlign)
        datadefined.setProperty(20, 1)

        #Creating and Activating Labeling Rule
        settings.setDataDefinedProperties(datadefined)
        rule = QgsRuleBasedLabeling.Rule(settings)
        rule.setDescription(desc)
        rule.setActive(True)

        return rule
Ejemplo n.º 18
0
    def grid_labeler(self, coord_base_x, coord_base_y, px, py, u, t, dx, dy,
                     desc, fSize, fontType, expression_str, trLLUTM, llcolor,
                     layer_bound, trUTMLL):
        pgrid = QgsPoint(coord_base_x + px * u, coord_base_y + py * t)
        pgrid.transform(trLLUTM)
        pgrid = QgsPoint(pgrid.x() + dx, pgrid.y() + dy)
        if layer_bound.crs().isGeographic() == True:
            pgrid.transform(trUTMLL)
        #Label Format Settings
        settings = QgsPalLayerSettings()
        settings.placement = 1
        settings.isExpression = True
        textprop = QgsTextFormat()
        textprop.setColor(llcolor)
        textprop.setSizeUnit(4)
        textprop.setSize(fSize * 2.8346)
        textprop.setFont(QFont(fontType))
        textprop.setLineHeight(1)
        settings.setFormat(textprop)
        settings.fieldName = expression_str

        #Label Position
        settings.geometryGeneratorEnabled = True
        settings.geometryGenerator = ("make_point({}, {})".format(
            pgrid.x(), pgrid.y()))
        datadefined = QgsPropertyCollection()
        datadefined.property(20).setExpressionString('True')
        datadefined.property(20).setActive(True)
        datadefined.property(15).setExpressionString('True')
        datadefined.property(15).setActive(True)
        datadefined.property(77).setExpressionString('2')
        datadefined.property(77).setActive(True)

        #Creating and Activating Labeling Rule
        settings.setDataDefinedProperties(datadefined)
        rule = QgsRuleBasedLabeling.Rule(settings)
        rule.setDescription(desc)
        rule.setActive(True)

        return rule
Ejemplo n.º 19
0
    def checkRepaintLabeledLayerInvalidatesLabelCache(self, job_type):
        layer = QgsVectorLayer("Point?field=fldtxt:string",
                               "layer1", "memory")

        labelSettings = QgsPalLayerSettings()
        labelSettings.fieldName = "fldtxt"
        layer.setLabeling(QgsVectorLayerSimpleLabeling(labelSettings))
        layer.setLabelsEnabled(True)

        settings = QgsMapSettings()
        settings.setExtent(QgsRectangle(5, 25, 25, 45))
        settings.setOutputSize(QSize(600, 400))
        settings.setLayers([layer])

        # with cache - first run should populate cache
        cache = QgsMapRendererCache()
        job = job_type(settings)
        job.setCache(cache)
        job.start()
        job.waitForFinished()
        self.assertFalse(job.usedCachedLabels())
        self.assertTrue(cache.hasCacheImage('_labels_'))
        self.assertTrue(job.takeLabelingResults())

        self.assertEqual(cache.dependentLayers('_labels_'), [layer])

        # trigger repaint on layer - should invalidate cache and block use of cached labels
        layer.triggerRepaint()
        self.assertFalse(cache.hasCacheImage('_labels_'))

        # second job should not use label cache, since layer was repainted
        job = job_type(settings)
        job.setCache(cache)
        job.start()
        job.waitForFinished()
        # shouldn't use cache
        self.assertFalse(job.usedCachedLabels())
        # but results should have been cached
        self.assertTrue(cache.hasCacheImage('_labels_'))
        self.assertTrue(job.takeLabelingResults())
Ejemplo n.º 20
0
    def checkRepaintLabeledLayerInvalidatesLabelCache(self, job_type):
        layer = QgsVectorLayer("Point?field=fldtxt:string",
                               "layer1", "memory")

        labelSettings = QgsPalLayerSettings()
        labelSettings.fieldName = "fldtxt"
        layer.setLabeling(QgsVectorLayerSimpleLabeling(labelSettings))
        layer.setLabelsEnabled(True)

        settings = QgsMapSettings()
        settings.setExtent(QgsRectangle(5, 25, 25, 45))
        settings.setOutputSize(QSize(600, 400))
        settings.setLayers([layer])

        # with cache - first run should populate cache
        cache = QgsMapRendererCache()
        job = job_type(settings)
        job.setCache(cache)
        job.start()
        job.waitForFinished()
        self.assertFalse(job.usedCachedLabels())
        self.assertTrue(cache.hasCacheImage('_labels_'))
        self.assertTrue(job.takeLabelingResults())

        self.assertEqual(cache.dependentLayers('_labels_'), [layer])

        # trigger repaint on layer - should invalidate cache and block use of cached labels
        layer.triggerRepaint()
        self.assertFalse(cache.hasCacheImage('_labels_'))

        # second job should not use label cache, since layer was repainted
        job = job_type(settings)
        job.setCache(cache)
        job.start()
        job.waitForFinished()
        # shouldn't use cache
        self.assertFalse(job.usedCachedLabels())
        # but results should have been cached
        self.assertTrue(cache.hasCacheImage('_labels_'))
        self.assertTrue(job.takeLabelingResults())
 def createLayer(self):
     '''Create a memory layer from the zoom to locations'''
     rowcnt = self.resultsTable.rowCount()
     if rowcnt == 0:
         return
     attr = []
     for item, label in enumerate(LABELS[0:self.numCol]):
         label = label.lower()
         if item <= 1:
             attr.append(QgsField(label, QVariant.Double))
         else:
             attr.append(QgsField(label, QVariant.String))
     ptLayer = QgsVectorLayer("Point?crs=epsg:4326", u"Lat Lon Locations", "memory")
     provider = ptLayer.dataProvider()
     provider.addAttributes(attr)
     ptLayer.updateFields()
     
     for id in range(rowcnt):
         item = self.resultsTable.item(id, 0).data(Qt.UserRole)
         feature = QgsFeature()
         feature.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(item.lon, item.lat)))
         attr = [item.lat, item.lon, item.label]
         for i in range(3, self.numCol):
             attr.append(item.data[i-3])
         feature.setAttributes(attr)
         provider.addFeatures([feature])
     
     ptLayer.updateExtents()
     if self.settings.multiZoomStyleID == 1:
         settings = QgsPalLayerSettings()
         settings.fieldName = 'label'
         settings.placement = QgsPalLayerSettings.AroundPoint
         labeling = QgsVectorLayerSimpleLabeling(settings)
         ptLayer.setLabeling(labeling)
         ptLayer.setLabelsEnabled(True)
     elif self.settings.multiZoomStyleID == 2 and os.path.isfile(self.settings.customQMLFile()):
         ptLayer.loadNamedStyle(self.settings.customQMLFile())
         
     QgsProject.instance().addMapLayer(ptLayer)
Ejemplo n.º 22
0
    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()
Ejemplo n.º 23
0
    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)
Ejemplo n.º 24
0
 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)
Ejemplo n.º 25
0
    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()
Ejemplo n.º 26
0
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)

    return
Ejemplo n.º 27
0
    def createRules(self, label, expression):
        '''
        Returns a QgsRuleBasedLabeling based on label and expression
        '''
        settings = QgsPalLayerSettings()
        settings.fieldName = label
        settings.Placement = QgsPalLayerSettings.OverPoint
        settings.centroidInside = True
        settings.isExpression = True
        textFormat = QgsTextFormat()
        textFormat.setColor(QColor(0, 0, 0, 255))
        textFormat.setSize(6)

        textBuffer = QgsTextBufferSettings()
        textBuffer.setColor(QColor(255, 255, 255, 255))
        textBuffer.setSize(0.4)
        textBuffer.setEnabled(True)
        textFormat.setBuffer(textBuffer)
        settings.setFormat(textFormat)

        rule = QgsRuleBasedLabeling.Rule(settings)
        rule.setFilterExpression(expression)
        rule.setActive(True)
        return rule
Ejemplo n.º 28
0
    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)
Ejemplo n.º 29
0
    def convert_label_engine_layer_properties(
            properties: LabelEngineLayerProperties, layer_geometry_type,
            context) -> QgsPalLayerSettings:
        """
        Converts LabelEngineLayerProperties to QGIS equivalent
        """
        label_settings = QgsPalLayerSettings()
        label_settings.drawLabels = properties.label_features

        LabelConverter.convert_label_text_symbol(properties.text_symbol,
                                                 label_settings, context)

        label_settings.fieldName = ExpressionConverter.convert(
            properties.expression, properties.expression_parser,
            properties.advanced_expression, context)
        label_settings.isExpression = True

        LabelConverter.convert_overposter(properties.overposter,
                                          layer_geometry_type, label_settings,
                                          context)

        label_settings.scaleVisibility = properties.scale_range_max or properties.scale_range_min
        # layer.zoom_max = "don't show when zoomed out beyond"
        zoom_max = properties.scale_range_max
        # layer.zoom_min = "don't show when zoomed in beyond"
        zoom_min = properties.scale_range_min
        if zoom_max and zoom_min and zoom_min > zoom_max:
            # inconsistent scale range -- zoom_max should be bigger number than zoom_min
            zoom_min, zoom_max = zoom_max, zoom_min

        # qgis maximum scale = don't show when zoomed in beyond, i.e. ArcGIS zoom_min
        label_settings.maximumScale = zoom_min
        # qgis minimum scale = don't show when zoomed out beyond, i.e. ArcGIS zoom_max
        label_settings.minimumScale = zoom_max

        return label_settings
Ejemplo n.º 30
0
    def testLabelMargin(self):
        """
        Test rendering map item with a label margin set
        """
        format = QgsTextFormat()
        format.setFont(QgsFontUtils.getStandardTestFont("Bold"))
        format.setSize(20)
        format.setNamedStyle("Bold")
        format.setColor(QColor(0, 0, 0))
        settings = QgsPalLayerSettings()
        settings.setFormat(format)
        settings.fieldName = "'X'"
        settings.isExpression = True
        settings.placement = QgsPalLayerSettings.OverPoint

        vl = QgsVectorLayer("Point?crs=epsg:4326&field=id:integer", "vl",
                            "memory")
        vl.setRenderer(QgsNullSymbolRenderer())
        f = QgsFeature(vl.fields(), 1)
        for x in range(15):
            for y in range(15):
                f.setGeometry(QgsPoint(x, y))
                vl.dataProvider().addFeature(f)

        vl.setLabeling(QgsVectorLayerSimpleLabeling(settings))
        vl.setLabelsEnabled(True)

        p = QgsProject()

        engine_settings = QgsLabelingEngineSettings()
        engine_settings.setFlag(QgsLabelingEngineSettings.UsePartialCandidates,
                                False)
        engine_settings.setFlag(QgsLabelingEngineSettings.DrawLabelRectOnly,
                                True)
        p.setLabelingEngineSettings(engine_settings)

        p.addMapLayer(vl)
        layout = QgsLayout(p)
        layout.initializeDefaults()
        p.setCrs(QgsCoordinateReferenceSystem('EPSG:4326'))
        map = QgsLayoutItemMap(layout)
        map.attemptSetSceneRect(QRectF(10, 10, 180, 180))
        map.setFrameEnabled(True)
        map.zoomToExtent(vl.extent())
        map.setLayers([vl])
        layout.addLayoutItem(map)

        checker = QgsLayoutChecker('composermap_label_nomargin', layout)
        checker.setControlPathPrefix("composer_map")
        result, message = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(result, message)

        map.setLabelMargin(
            QgsLayoutMeasurement(15, QgsUnitTypes.LayoutMillimeters))
        checker = QgsLayoutChecker('composermap_label_margin', layout)
        checker.setControlPathPrefix("composer_map")
        result, message = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(result, message)

        map.setLabelMargin(
            QgsLayoutMeasurement(3, QgsUnitTypes.LayoutCentimeters))
        checker = QgsLayoutChecker('composermap_label_cm_margin', layout)
        checker.setControlPathPrefix("composer_map")
        result, message = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(result, message)

        map.setMapRotation(45)
        map.zoomToExtent(vl.extent())
        map.setScale(map.scale() * 1.2)
        checker = QgsLayoutChecker('composermap_rotated_label_margin', layout)
        checker.setControlPathPrefix("composer_map")
        result, message = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(result, message)

        # data defined
        map.setMapRotation(0)
        map.zoomToExtent(vl.extent())
        map.dataDefinedProperties().setProperty(
            QgsLayoutObject.MapLabelMargin, QgsProperty.fromExpression('1+3'))
        map.refresh()
        checker = QgsLayoutChecker('composermap_dd_label_margin', layout)
        checker.setControlPathPrefix("composer_map")
        result, message = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(result, message)
Ejemplo n.º 31
0
    def testBlockingItems(self):
        """
        Test rendering map item with blocking items
        """
        format = QgsTextFormat()
        format.setFont(QgsFontUtils.getStandardTestFont("Bold"))
        format.setSize(20)
        format.setNamedStyle("Bold")
        format.setColor(QColor(0, 0, 0))
        settings = QgsPalLayerSettings()
        settings.setFormat(format)
        settings.fieldName = "'X'"
        settings.isExpression = True
        settings.placement = QgsPalLayerSettings.OverPoint

        vl = QgsVectorLayer("Point?crs=epsg:4326&field=id:integer", "vl", "memory")
        vl.setRenderer(QgsNullSymbolRenderer())
        f = QgsFeature(vl.fields(), 1)
        for x in range(15):
            for y in range(15):
                f.setGeometry(QgsPoint(x, y))
                vl.dataProvider().addFeature(f)

        vl.setLabeling(QgsVectorLayerSimpleLabeling(settings))
        vl.setLabelsEnabled(True)

        p = QgsProject()

        engine_settings = QgsLabelingEngineSettings()
        engine_settings.setFlag(QgsLabelingEngineSettings.DrawLabelRectOnly, True)
        p.setLabelingEngineSettings(engine_settings)

        p.addMapLayer(vl)
        layout = QgsLayout(p)
        layout.initializeDefaults()
        p.setCrs(QgsCoordinateReferenceSystem('EPSG:4326'))
        map = QgsLayoutItemMap(layout)
        map.attemptSetSceneRect(QRectF(10, 10, 180, 180))
        map.setFrameEnabled(True)
        map.zoomToExtent(vl.extent())
        map.setLayers([vl])
        map.setId('map')
        layout.addLayoutItem(map)

        map2 = QgsLayoutItemMap(layout)
        map2.attemptSetSceneRect(QRectF(0, 5, 50, 80))
        map2.setFrameEnabled(True)
        map2.setBackgroundEnabled(False)
        map2.setId('map2')
        layout.addLayoutItem(map2)

        map3 = QgsLayoutItemMap(layout)
        map3.attemptSetSceneRect(QRectF(150, 160, 50, 50))
        map3.setFrameEnabled(True)
        map3.setBackgroundEnabled(False)
        map3.setId('map3')
        layout.addLayoutItem(map3)

        map.addLabelBlockingItem(map2)
        map.addLabelBlockingItem(map3)
        map.setMapFlags(QgsLayoutItemMap.MapItemFlags())
        checker = QgsLayoutChecker('composermap_label_blockers', layout)
        checker.setControlPathPrefix("composer_map")
        result, message = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(result, message)

        doc = QDomDocument("testdoc")
        elem = layout.writeXml(doc, QgsReadWriteContext())

        l2 = QgsLayout(p)
        self.assertTrue(l2.readXml(elem, doc, QgsReadWriteContext()))
        map_restore = [i for i in l2.items() if isinstance(i, QgsLayoutItemMap) and i.id() == 'map'][0]
        map2_restore = [i for i in l2.items() if isinstance(i, QgsLayoutItemMap) and i.id() == 'map2'][0]
        map3_restore = [i for i in l2.items() if isinstance(i, QgsLayoutItemMap) and i.id() == 'map3'][0]
        self.assertTrue(map_restore.isLabelBlockingItem(map2_restore))
        self.assertTrue(map_restore.isLabelBlockingItem(map3_restore))
Ejemplo n.º 32
0
    def testPartialLabels(self):
        """
        Test rendering map item with a show partial labels flag
        """
        format = QgsTextFormat()
        format.setFont(QgsFontUtils.getStandardTestFont("Bold"))
        format.setSize(20)
        format.setNamedStyle("Bold")
        format.setColor(QColor(0, 0, 0))
        settings = QgsPalLayerSettings()
        settings.setFormat(format)
        settings.fieldName = "'X'"
        settings.isExpression = True
        settings.placement = QgsPalLayerSettings.OverPoint

        vl = QgsVectorLayer("Point?crs=epsg:4326&field=id:integer", "vl", "memory")
        vl.setRenderer(QgsNullSymbolRenderer())
        f = QgsFeature(vl.fields(), 1)
        for x in range(15):
            for y in range(15):
                f.setGeometry(QgsPoint(x, y))
                vl.dataProvider().addFeature(f)

        vl.setLabeling(QgsVectorLayerSimpleLabeling(settings))
        vl.setLabelsEnabled(True)

        p = QgsProject()

        engine_settings = QgsLabelingEngineSettings()
        engine_settings.setFlag(QgsLabelingEngineSettings.UsePartialCandidates, False)
        engine_settings.setFlag(QgsLabelingEngineSettings.DrawLabelRectOnly, True)
        p.setLabelingEngineSettings(engine_settings)

        p.addMapLayer(vl)
        layout = QgsLayout(p)
        layout.initializeDefaults()
        p.setCrs(QgsCoordinateReferenceSystem('EPSG:4326'))
        map = QgsLayoutItemMap(layout)
        map.attemptSetSceneRect(QRectF(10, 10, 180, 180))
        map.setFrameEnabled(True)
        map.zoomToExtent(vl.extent())
        map.setLayers([vl])
        layout.addLayoutItem(map)

        # default should always be to hide partial labels
        self.assertFalse(map.mapFlags() & QgsLayoutItemMap.ShowPartialLabels)

        # hiding partial labels (the default)
        map.setMapFlags(QgsLayoutItemMap.MapItemFlags())
        checker = QgsLayoutChecker('composermap_label_nomargin', layout)
        checker.setControlPathPrefix("composer_map")
        result, message = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(result, message)

        # showing partial labels
        map.setMapFlags(QgsLayoutItemMap.ShowPartialLabels)
        checker = QgsLayoutChecker('composermap_show_partial_labels', layout)
        checker.setControlPathPrefix("composer_map")
        result, message = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(result, message)
Ejemplo n.º 33
0
    def testLabelMargin(self):
        """
        Test rendering map item with a label margin set
        """
        format = QgsTextFormat()
        format.setFont(QgsFontUtils.getStandardTestFont("Bold"))
        format.setSize(20)
        format.setNamedStyle("Bold")
        format.setColor(QColor(0, 0, 0))
        settings = QgsPalLayerSettings()
        settings.setFormat(format)
        settings.fieldName = "'X'"
        settings.isExpression = True
        settings.placement = QgsPalLayerSettings.OverPoint

        vl = QgsVectorLayer("Point?crs=epsg:4326&field=id:integer", "vl", "memory")
        vl.setRenderer(QgsNullSymbolRenderer())
        f = QgsFeature(vl.fields(), 1)
        for x in range(15):
            for y in range(15):
                f.setGeometry(QgsPoint(x, y))
                vl.dataProvider().addFeature(f)

        vl.setLabeling(QgsVectorLayerSimpleLabeling(settings))
        vl.setLabelsEnabled(True)

        p = QgsProject()

        engine_settings = QgsLabelingEngineSettings()
        engine_settings.setFlag(QgsLabelingEngineSettings.UsePartialCandidates, False)
        engine_settings.setFlag(QgsLabelingEngineSettings.DrawLabelRectOnly, True)
        p.setLabelingEngineSettings(engine_settings)

        p.addMapLayer(vl)
        layout = QgsLayout(p)
        layout.initializeDefaults()
        p.setCrs(QgsCoordinateReferenceSystem('EPSG:4326'))
        map = QgsLayoutItemMap(layout)
        map.attemptSetSceneRect(QRectF(10, 10, 180, 180))
        map.setFrameEnabled(True)
        map.zoomToExtent(vl.extent())
        map.setLayers([vl])
        layout.addLayoutItem(map)

        checker = QgsLayoutChecker('composermap_label_nomargin', layout)
        checker.setControlPathPrefix("composer_map")
        result, message = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(result, message)

        map.setLabelMargin(QgsLayoutMeasurement(15, QgsUnitTypes.LayoutMillimeters))
        checker = QgsLayoutChecker('composermap_label_margin', layout)
        checker.setControlPathPrefix("composer_map")
        result, message = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(result, message)

        map.setLabelMargin(QgsLayoutMeasurement(3, QgsUnitTypes.LayoutCentimeters))
        checker = QgsLayoutChecker('composermap_label_cm_margin', layout)
        checker.setControlPathPrefix("composer_map")
        result, message = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(result, message)

        map.setMapRotation(45)
        map.zoomToExtent(vl.extent())
        map.setScale(map.scale() * 1.2)
        checker = QgsLayoutChecker('composermap_rotated_label_margin', layout)
        checker.setControlPathPrefix("composer_map")
        result, message = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(result, message)

        # data defined
        map.setMapRotation(0)
        map.zoomToExtent(vl.extent())
        map.dataDefinedProperties().setProperty(QgsLayoutObject.MapLabelMargin, QgsProperty.fromExpression('1+3'))
        map.refresh()
        checker = QgsLayoutChecker('composermap_dd_label_margin', layout)
        checker.setControlPathPrefix("composer_map")
        result, message = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(result, message)
Ejemplo n.º 34
0
    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()
Ejemplo n.º 35
0
    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()
Ejemplo n.º 36
0
    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]
Ejemplo n.º 37
0
    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 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 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)
Ejemplo n.º 40
0
    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())
Ejemplo n.º 41
0
    def testClippingHideClipSource(self):
        """
        When an item is set to be the clip source, it shouldn't render anything itself
        """
        format = QgsTextFormat()
        format.setFont(QgsFontUtils.getStandardTestFont("Bold"))
        format.setSize(30)
        format.setNamedStyle("Bold")
        format.setColor(QColor(0, 0, 0))
        settings = QgsPalLayerSettings()
        settings.setFormat(format)
        settings.fieldName = "'XXXX'"
        settings.isExpression = True
        settings.placement = QgsPalLayerSettings.OverPoint

        vl = QgsVectorLayer("Polygon?crs=epsg:4326&field=id:integer", "vl",
                            "memory")

        props = {
            "color": "127,255,127",
            'outline_style': 'solid',
            'outline_width': '1',
            'outline_color': '0,0,255'
        }
        fillSymbol = QgsFillSymbol.createSimple(props)
        renderer = QgsSingleSymbolRenderer(fillSymbol)
        vl.setRenderer(renderer)

        f = QgsFeature(vl.fields(), 1)
        for x in range(0, 15, 3):
            for y in range(0, 15, 3):
                f.setGeometry(QgsGeometry(QgsPoint(x, y)).buffer(1, 3))
                vl.dataProvider().addFeature(f)

        vl.setLabeling(QgsVectorLayerSimpleLabeling(settings))
        vl.setLabelsEnabled(True)

        p = QgsProject()

        p.addMapLayer(vl)
        layout = QgsLayout(p)
        layout.initializeDefaults()
        p.setCrs(QgsCoordinateReferenceSystem('EPSG:4326'))
        map = QgsLayoutItemMap(layout)
        map.attemptSetSceneRect(QRectF(10, 10, 180, 180))
        map.setFrameEnabled(False)
        map.zoomToExtent(vl.extent())
        map.setLayers([vl])
        layout.addLayoutItem(map)

        shape = QgsLayoutItemShape(layout)
        layout.addLayoutItem(shape)
        shape.setShapeType(QgsLayoutItemShape.Ellipse)
        shape.attemptSetSceneRect(QRectF(10, 10, 180, 180))

        map.itemClippingSettings().setEnabled(True)
        map.itemClippingSettings().setSourceItem(shape)
        map.itemClippingSettings().setForceLabelsInsideClipPath(False)
        map.itemClippingSettings().setFeatureClippingType(
            QgsMapClippingRegion.FeatureClippingType.ClipToIntersection)

        checker = QgsLayoutChecker('composermap_itemclip_nodrawsource', layout)
        checker.setControlPathPrefix("composer_map")
        result, message = checker.testLayout()
        TestQgsLayoutMap.report += checker.report()
        self.assertTrue(result, message)
Ejemplo n.º 42
0
    def testPartialLabels(self):
        """
        Test rendering map item with a show partial labels flag
        """
        format = QgsTextFormat()
        format.setFont(QgsFontUtils.getStandardTestFont("Bold"))
        format.setSize(20)
        format.setNamedStyle("Bold")
        format.setColor(QColor(0, 0, 0))
        settings = QgsPalLayerSettings()
        settings.setFormat(format)
        settings.fieldName = "'X'"
        settings.isExpression = True
        settings.placement = QgsPalLayerSettings.OverPoint

        vl = QgsVectorLayer("Point?crs=epsg:4326&field=id:integer", "vl",
                            "memory")
        vl.setRenderer(QgsNullSymbolRenderer())
        f = QgsFeature(vl.fields(), 1)
        for x in range(15):
            for y in range(15):
                f.setGeometry(QgsPoint(x, y))
                vl.dataProvider().addFeature(f)

        vl.setLabeling(QgsVectorLayerSimpleLabeling(settings))
        vl.setLabelsEnabled(True)

        p = QgsProject()

        engine_settings = QgsLabelingEngineSettings()
        engine_settings.setFlag(QgsLabelingEngineSettings.UsePartialCandidates,
                                False)
        engine_settings.setFlag(QgsLabelingEngineSettings.DrawLabelRectOnly,
                                True)
        p.setLabelingEngineSettings(engine_settings)

        p.addMapLayer(vl)
        layout = QgsLayout(p)
        layout.initializeDefaults()
        p.setCrs(QgsCoordinateReferenceSystem('EPSG:4326'))
        map = QgsLayoutItemMap(layout)
        map.attemptSetSceneRect(QRectF(10, 10, 180, 180))
        map.setFrameEnabled(True)
        map.zoomToExtent(vl.extent())
        map.setLayers([vl])
        layout.addLayoutItem(map)

        # default should always be to hide partial labels
        self.assertFalse(map.mapFlags() & QgsLayoutItemMap.ShowPartialLabels)

        # hiding partial labels (the default)
        map.setMapFlags(QgsLayoutItemMap.MapItemFlags())
        checker = QgsLayoutChecker('composermap_label_nomargin', layout)
        checker.setControlPathPrefix("composer_map")
        result, message = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(result, message)

        # showing partial labels
        map.setMapFlags(QgsLayoutItemMap.ShowPartialLabels)
        checker = QgsLayoutChecker('composermap_show_partial_labels', layout)
        checker.setControlPathPrefix("composer_map")
        result, message = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(result, message)
Ejemplo n.º 43
0
    def run(self):

        #coloco el puntero arriba del todo
        #QgsProject.instance().layerTreeRegistryBridge().setLayerInsertionPoint( QgsProject.instance().layerTreeRoot(), 0 )
        #genero una lista con los campos de la capa selecionada
        layer = iface.activeLayer()
        if layer is None:
            iface.messageBar().pushMessage("ATENCION",
                                           "Selecciona una capa de puntos",
                                           duration=10)
        if layer.wkbType() == 1 or layer.wkbType() == 1001:
            prov = layer.dataProvider()
            field_names = [field.name() for field in prov.fields()]
            self.dlg.mycomboBox.clear()
            for element in field_names:
                self.dlg.mycomboBox.addItem(element)
            """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

            # show the dialog
            self.dlg.show()
            # Run the dialog event loop
            result = self.dlg.exec_()
            # See if OK was pressed

            if result:
                global index_campo_seleccionado
                distanciaminima = int(self.dlg.lineEdit_distancia.text())
                # "layer" is a QgsVectorLayer instance
                layer = iface.activeLayer()
                idx = layer.fields().indexFromName("distanc")
                if idx == -1:
                    print("ya existe")
                    res = layer.dataProvider().addAttributes(
                        [QgsField("distanc", QVariant.String)])
                #layer.addAttribute(QgsField("valido", QVariant.String))
                layer.updateFields()
                features = layer.getFeatures()

                for feature in features:
                    # retrieve every feature with its geometry and attributes
                    #print("Feature ID: ", feature.id())
                    # fetch geometry
                    # show some information about the feature geometry
                    geom = feature.geometry()
                    geomSingleType = QgsWkbTypes.isSingleType(geom.wkbType())
                    if geom.type() == QgsWkbTypes.PointGeometry:
                        punto = geom.asPoint()
                        x = punto.x()
                        y = punto.y()
                        #print("analizo los puntos",x,y)
                        features2 = layer.getFeatures()
                        for feature2 in features2:
                            geom2 = feature2.geometry()
                            punto2 = geom2.asPoint()
                            x3 = punto2.x()
                            y3 = punto2.y()
                            d = ((x3 - x)**2 + (y3 - y)**2)**0.5
                            if d < distanciaminima:
                                if feature2.id() == feature.id():
                                    pass
                                else:
                                    layer.startEditing()
                                    feature.setAttribute("distanc", 'no')
                                    print(feature2.id())
                                    layer.updateFeature(feature)
                                    #Call commit to save the changes
                                    layer.commitChanges()

                categorias = []
                sym = QgsMarkerSymbol.createSimple({
                    'name': 'circle',
                    'color': 'red',
                    'size': '3'
                })
                categoria = QgsRendererCategory("no", sym, "No cumple")
                categorias.append(categoria)
                sym = QgsMarkerSymbol.createSimple({
                    'name': 'circle',
                    'color': 'blue',
                    'size': '2'
                })
                categoria = QgsRendererCategory("", sym, "Cumple")
                categorias.append(categoria)
                renderer = QgsCategorizedSymbolRenderer("distanc", categorias)
                layer.setRenderer(renderer)
                # update layer's extent when new features have been added
                # because change of extent in provider is not propagated to the layer

                #Configure label settings
                settings = QgsPalLayerSettings()
                settings.fieldName = field_names[
                    index_campo_seleccionado]  #'name'
                textFormat = QgsTextFormat()
                textFormat.setSize(10)
                settings.setFormat(textFormat)
                #create and append a new rule
                root = QgsRuleBasedLabeling.Rule(QgsPalLayerSettings())
                rule = QgsRuleBasedLabeling.Rule(settings)
                #rule.setDescription(fieldName)
                rule.setFilterExpression(''' "distanc" = 'no' ''')
                root.appendChild(rule)
                #Apply label configuration
                rules = QgsRuleBasedLabeling(root)
                layer.setLabeling(rules)
                layer.setLabelsEnabled(True)
                layer.triggerRepaint()

        else:
            iface.messageBar().pushMessage("ATENCION",
                                           "Selecciona una capa de puntos",
                                           duration=10)
Ejemplo n.º 44
0
    def testBlockingItems(self):
        """
        Test rendering map item with blocking items
        """
        format = QgsTextFormat()
        format.setFont(QgsFontUtils.getStandardTestFont("Bold"))
        format.setSize(20)
        format.setNamedStyle("Bold")
        format.setColor(QColor(0, 0, 0))
        settings = QgsPalLayerSettings()
        settings.setFormat(format)
        settings.fieldName = "'X'"
        settings.isExpression = True
        settings.placement = QgsPalLayerSettings.OverPoint

        vl = QgsVectorLayer("Point?crs=epsg:4326&field=id:integer", "vl",
                            "memory")
        vl.setRenderer(QgsNullSymbolRenderer())
        f = QgsFeature(vl.fields(), 1)
        for x in range(15):
            for y in range(15):
                f.setGeometry(QgsPoint(x, y))
                vl.dataProvider().addFeature(f)

        vl.setLabeling(QgsVectorLayerSimpleLabeling(settings))
        vl.setLabelsEnabled(True)

        p = QgsProject()

        engine_settings = QgsLabelingEngineSettings()
        engine_settings.setFlag(QgsLabelingEngineSettings.DrawLabelRectOnly,
                                True)
        p.setLabelingEngineSettings(engine_settings)

        p.addMapLayer(vl)
        layout = QgsLayout(p)
        layout.initializeDefaults()
        p.setCrs(QgsCoordinateReferenceSystem('EPSG:4326'))
        map = QgsLayoutItemMap(layout)
        map.attemptSetSceneRect(QRectF(10, 10, 180, 180))
        map.setFrameEnabled(True)
        map.zoomToExtent(vl.extent())
        map.setLayers([vl])
        map.setId('map')
        layout.addLayoutItem(map)

        map2 = QgsLayoutItemMap(layout)
        map2.attemptSetSceneRect(QRectF(0, 5, 50, 80))
        map2.setFrameEnabled(True)
        map2.setBackgroundEnabled(False)
        map2.setId('map2')
        layout.addLayoutItem(map2)

        map3 = QgsLayoutItemMap(layout)
        map3.attemptSetSceneRect(QRectF(150, 160, 50, 50))
        map3.setFrameEnabled(True)
        map3.setBackgroundEnabled(False)
        map3.setId('map3')
        layout.addLayoutItem(map3)

        map.addLabelBlockingItem(map2)
        map.addLabelBlockingItem(map3)
        map.setMapFlags(QgsLayoutItemMap.MapItemFlags())
        checker = QgsLayoutChecker('composermap_label_blockers', layout)
        checker.setControlPathPrefix("composer_map")
        result, message = checker.testLayout()
        self.report += checker.report()
        self.assertTrue(result, message)

        doc = QDomDocument("testdoc")
        elem = layout.writeXml(doc, QgsReadWriteContext())

        l2 = QgsLayout(p)
        self.assertTrue(l2.readXml(elem, doc, QgsReadWriteContext()))
        map_restore = [
            i for i in l2.items()
            if isinstance(i, QgsLayoutItemMap) and i.id() == 'map'
        ][0]
        map2_restore = [
            i for i in l2.items()
            if isinstance(i, QgsLayoutItemMap) and i.id() == 'map2'
        ][0]
        map3_restore = [
            i for i in l2.items()
            if isinstance(i, QgsLayoutItemMap) and i.id() == 'map3'
        ][0]
        self.assertTrue(map_restore.isLabelBlockingItem(map2_restore))
        self.assertTrue(map_restore.isLabelBlockingItem(map3_restore))
Ejemplo n.º 45
0
def parse_symbol_layer(json_layer):

    json_layout = json_layer['layout']
    json_paint = json_layer['paint']

    dd_properties = {}

    TEXT_SIZE_MULTIPLIER = 2  # *2 because of high-res screen?

    text_size = 16
    if 'text-size' in json_layout:
        json_text_size = json_layout['text-size']
        if isinstance(json_text_size, (float, int)):
            text_size = json_text_size
        elif isinstance(json_text_size, dict):
            dd_properties[
                QgsPalLayerSettings.Size] = parse_interpolate_by_zoom(
                    json_text_size, TEXT_SIZE_MULTIPLIER)
        else:
            print("skipping non-float text-size", json_text_size)

    # TODO: text-font

    text_color = Qt.black
    if 'text-color' in json_paint:
        json_text_color = json_paint['text-color']
        if isinstance(json_text_color, str):
            text_color = parse_color(json_text_color)
        else:
            print("skipping non-string text-color", json_text_color)

    buffer_color = QColor(0, 0, 0, 0)
    if 'text-halo-color' in json_paint:
        json_text_halo_color = json_paint['text-halo-color']
        if isinstance(json_text_halo_color, str):
            buffer_color = parse_color(json_text_halo_color)
        else:
            print("skipping non-string text-halo-color", json_text_halo_color)

    buffer_size = 0
    if 'text-halo-width' in json_paint:
        json_text_halo_width = json_paint['text-halo-width']
        if isinstance(json_text_halo_width, (float, int)):
            buffer_size = json_text_halo_width
        else:
            print("skipping non-float text-halo-width", json_text_halo_width)

    format = QgsTextFormat()
    format.setColor(text_color)
    format.setSize(text_size * TEXT_SIZE_MULTIPLIER)
    format.setSizeUnit(QgsUnitTypes.RenderPixels)
    #format.setFont(font)

    if buffer_size > 0:
        buffer_settings = QgsTextBufferSettings()
        buffer_settings.setEnabled(True)
        buffer_settings.setSize(buffer_size * PX_TO_MM * TEXT_SIZE_MULTIPLIER)
        buffer_settings.setColor(buffer_color)
        format.setBuffer(buffer_settings)

    label_settings = QgsPalLayerSettings()
    label_settings.fieldName = '"name:latin"'  # TODO: parse field name
    label_settings.isExpression = True
    label_settings.placement = QgsPalLayerSettings.OverPoint
    label_settings.priority = min(text_size / 3., 10.)
    label_settings.setFormat(format)

    if dd_properties:
        for dd_key, dd_expression in dd_properties.items():
            prop_collection = QgsPropertyCollection()
            prop_collection.setProperty(
                dd_key, QgsProperty.fromExpression(dd_expression))
        label_settings.setDataDefinedProperties(prop_collection)

    lb = QgsVectorTileBasicLabelingStyle()
    lb.setGeometryType(QgsWkbTypes.PointGeometry)
    lb.setLabelSettings(label_settings)
    return lb
Ejemplo n.º 46
0
    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
    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_()
Ejemplo n.º 48
0
    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
Ejemplo n.º 49
0
    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]