Esempio n. 1
0
    def __init__(self, iface, layer_name, svg_size, attributes, svg_resource, group=None, visible=True):
        "..."
        self.svg_path = os.path.dirname(__file__) + "/icons/"
        WGS84Layer.__init__(self, iface, layer_name, "Point", visible, group)

        symbol = QgsSymbol.defaultSymbol(self.layer.geometryType())
        svgStyle = {}
        svgStyle['name'] = self.svg_path + svg_resource
        svgStyle['outline'] = '#00000'
        svgStyle['outline-width'] = '0'
        svgStyle['size'] = svg_size
        symbol_layer = QgsSvgMarkerSymbolLayer.create(svgStyle)

        # Rotate the svg to reflect the orientation of a landmark
        # admap uses a counter-clockwise orientation with radians, qgis a clockwise and degrees
        dataDefinedAngle = QgsProperty.fromExpression('(-("Orientation" * 180 / pi()) - 90) % 360', True)
        symbol_layer.setDataDefinedProperty(QgsSymbolLayer.PropertyAngle, dataDefinedAngle)

        # Make the SVG size scalable with the zoom level of the map
        # i.e. less zoom, smaller SVG
        dataDefinedSize = QgsProperty.fromExpression(
            'CASE WHEN @map_scale < 500 THEN 1000 / @map_scale ELSE 2 END', True)
        symbol_layer.setDataDefinedProperty(QgsSymbolLayer.PropertySize, dataDefinedSize)

        if symbol_layer is not None:
            symbols = self.layer.renderer().symbols(QgsRenderContext())
            sym = symbols[0]
            sym.changeSymbolLayer(0, symbol_layer)

        self.layer.triggerRepaint()
        WGS84Layer.refresh_legend(self)
        self.set_attributes(attributes)
Esempio n. 2
0
    def make_svg_link_sym_renderer(self, icon_name, svg_size=7, line_width=0.2):

        symbol = QgsLineSymbol().createSimple({})
        symbol.deleteSymbolLayer(0)

        # Line
        line_sym_lay = QgsSimpleLineSymbolLayer()
        line_sym_lay.setWidth(line_width)
        symbol.appendSymbolLayer(line_sym_lay)

        # Symbol
        self.marker_sym = QgsMarkerSymbol.createSimple({})
        self.marker_sym.deleteSymbolLayer(0)

        # marker_sym_lay = QgsSimpleMarkerSymbolLayerV2()
        current_dir = os.path.dirname(__file__)
        svg_props = dict()
        svg_props['name'] = os.path.join(current_dir, icon_name)
        svg_props['size'] = str(svg_size)
        marker_sym_lay = QgsSvgMarkerSymbolLayer.create(svg_props)
        self.marker_sym.appendSymbolLayer(marker_sym_lay)

        marker_line_sym_lay = QgsMarkerLineSymbolLayer()
        marker_line_sym_lay.setSubSymbol(self.marker_sym)  # Causes crash !!!
        marker_line_sym_lay.setPlacement(QgsMarkerLineSymbolLayer.CentralPoint)

        symbol.appendSymbolLayer(marker_line_sym_lay)

        renderer = QgsSingleSymbolRenderer(symbol)
        return renderer
Esempio n. 3
0
 def setStyleIcon(self, svg):
     #Dato il path di un'icona svg la setta come stile per le sole features selezionate nel layer dei beni
     vlayer = self.getLayerBeni()
     if len(vlayer.selectedFeatures()) == 1:
         svgStyle = {
             "name": svg,
             "outline": "#000000",
             "size": "15",
         }
         svgLayer = QgsSvgMarkerSymbolLayer.create(svgStyle)
         svgSymbol = QgsMarkerSymbol()
         svgSymbol.changeSymbolLayer(0, svgLayer)
         symbol = QgsSymbol.defaultSymbol(vlayer.geometryType())
         symbol.setColor(QColor("Blue"))
         centroid = QgsCentroidFillSymbolLayer()
         centroid.setSubSymbol(svgSymbol)
         selectedSymbol = QgsFillSymbol()
         selectedSymbol.changeSymbolLayer(0, centroid)
         renderer = QgsRuleBasedRenderer(symbol)
         rule = QgsRuleBasedRenderer.Rule(selectedSymbol,
                                          label="Selected",
                                          filterExp="is_selected()")
         renderer.rootRule().appendChild(rule)
         vlayer.setRenderer(renderer)
         vlayer.triggerRepaint()
Esempio n. 4
0
def SetDefaultPlatformStyle(layer):
    ''' Platform Symbol '''
    svgStyle = {}
    svgStyle['name'] = ":/imgFMV/images/platform.svg"
    svgStyle['outline'] = '#FFFFFF'
    svgStyle['outline-width'] = '1'
    svgStyle['size'] = '18'
    symbol_layer = QgsSvgMarkerSymbolLayer.create(svgStyle)
    layer.renderer().symbol().changeSymbolLayer(0, symbol_layer)
    return
Esempio n. 5
0
def SetDefaultPlatformStyle(layer, platform="DEFAULT"):
    """ Platform Symbol """
    style = S.getPlatform(platform)

    svgStyle = {}
    svgStyle["name"] = style["NAME"]
    svgStyle["outline"] = style["OUTLINE"]
    svgStyle["outline-width"] = style["OUTLINE_WIDTH"]
    svgStyle["size"] = style["SIZE"]

    symbol_layer = QgsSvgMarkerSymbolLayer.create(svgStyle)
    layer.renderer().symbol().changeSymbolLayer(0, symbol_layer)
Esempio n. 6
0
def SetDefaultPlatformStyle(layer, platform='DEFAULT'):
    ''' Platform Symbol '''
    style = S.getPlatform(platform)

    svgStyle = {}
    svgStyle['name'] = style["NAME"]
    svgStyle['outline'] = style["OUTLINE"]
    svgStyle['outline-width'] = style["OUTLINE_WIDTH"]
    svgStyle['size'] = style["SIZE"]

    symbol_layer = QgsSvgMarkerSymbolLayer.create(svgStyle)
    layer.renderer().symbol().changeSymbolLayer(0, symbol_layer)
Esempio n. 7
0
    def make_svg_node_sym_renderer(self, vlay, icon_name, size):

        current_dir = os.path.dirname(__file__)

        svg_style = dict()
        svg_style['name'] = os.path.join(current_dir, icon_name)
        svg_style['size'] = str(size)
        symbol_layer = QgsSvgMarkerSymbolLayer.create(svg_style)
        symbol = QgsSymbol.defaultSymbol(vlay.geometryType())
        symbol.changeSymbolLayer(0, symbol_layer)
        renderer = QgsSingleSymbolRenderer(symbol)

        return renderer
 def ned_origin_renderer(self):
     symbol = QgsSymbol.defaultSymbol(self.ned_origin_layer.geometryType())
     svg_style = {
         'fill': '# 0000ff',
         'name': ':/resources/Star2.svg',
         'outline': '#000000',
         'outline - width': '6.8',
         'size': '6'
     }
     # create svg symbol layer
     sym_lyr1 = QgsSvgMarkerSymbolLayer.create(svg_style)
     # Replace the default layer with our custom layer
     symbol.deleteSymbolLayer(0)
     symbol.appendSymbolLayer(sym_lyr1)
     # Replace the renderer of the current layer
     renderer = QgsSingleSymbolRenderer(symbol)
     return renderer
Esempio n. 9
0
    def setStyle(self, layer, name):
        if name == "":
            return
        stylePath = os.path.join(os.path.dirname(os.path.dirname(__file__)),
                                 "layerStyles")

        # user style
        qmlPath = os.path.join(stylePath, name + "_user.qml")
        if os.path.exists(qmlPath):
            layer.loadNamedStyle(qmlPath)
            return

        # default style
        qmlPath = os.path.join(stylePath, name + ".qml.bak")
        if os.path.exists(qmlPath):
            layer.loadNamedStyle(qmlPath)
        svgPath = os.path.join(stylePath, name + ".svg")
        if os.path.exists(svgPath):
            if layer.geometryType() == 0:  # Point
                svg_style = dict()
                svg_style['name'] = svgPath
                svg_style['size'] = str(7)
                if name == "demands":
                    svg_style['fill'] = '#9a1313'
                symbol_layer = QgsSvgMarkerSymbolLayer.create(svg_style)
                symbol = QgsSymbol.defaultSymbol(layer.geometryType())
                symbol.changeSymbolLayer(0, symbol_layer)
                renderer = QgsSingleSymbolRenderer(symbol)
            else:  # Line
                symbol = QgsLineSymbol().createSimple({})
                symbol.deleteSymbolLayer(0)
                # Line
                lineSymbol = QgsSimpleLineSymbolLayer()
                lineSymbol.setWidthUnit(2)  # Pixels
                lineSymbol.setWidth(1.5)
                if name == "pipes":
                    lineSymbol.setColor(QColor("#0f1291"))
                symbol.appendSymbolLayer(lineSymbol)
                # Symbol
                marker = QgsMarkerSymbol.createSimple({})
                marker.deleteSymbolLayer(0)
                svg_props = dict()
                svg_props['name'] = svgPath
                size = 5
                if name == "pipes":
                    size = 0
                svg_props['size'] = str(size)
                svg_props['offset'] = '-0.5,-0.5'
                svg_props['offset_unit'] = 'Pixel'
                markerSymbol = QgsSvgMarkerSymbolLayer.create(svg_props)
                marker.appendSymbolLayer(markerSymbol)
                # Final Symbol
                finalMarker = QgsMarkerLineSymbolLayer()
                finalMarker.setSubSymbol(marker)
                finalMarker.setPlacement(QgsMarkerLineSymbolLayer.CentralPoint)
                symbol.appendSymbolLayer(finalMarker)
                if name == "pipes":
                    prop = QgsProperty()
                    prop.setExpressionString(
                        "if(IniStatus is NULL, 0,if(IniStatus !='CV', 0,5))")
                    symbol.symbolLayer(1).setDataDefinedProperty(
                        9, prop)  # 9 = PropertyWidth
                renderer = QgsSingleSymbolRenderer(symbol)

            layer.setRenderer(renderer)
Esempio n. 10
0
    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 = HealthSIGDialog()

        # Clear the contents of the comboBox from previous runs
        self.dlg.comboBox.clear()
        # Populate the comboBox
        self.dlg.comboBox.addItems(["Hospitais", "ACES", "Farmácias"])
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()

        # See if OK was pressed and check index
        index = self.dlg.comboBox.currentIndex()

        # file directory for relative paths
        dirn = os.path.dirname(__file__)

        # escolheu unidades de saude
        if result and index == 1:
            # create layer
            vl = QgsVectorLayer("Point?crs=epsg:3763&index=yes", "aces",
                                "memory")
            pr = vl.dataProvider()

            # Enter editing mode
            vl.startEditing()

            # add fields
            pr.addAttributes([
                QgsField("ACES", QVariant.String),
                QgsField("ARS", QVariant.String),
                QgsField("Coord_X", QVariant.Double),
                QgsField("Coord_Y", QVariant.Double),
                QgsField("Num_USF", QVariant.Int)
            ])
            vl.updateFields(
            )  # tell the vector layer to fetch changes from the provider

            # add features ---> IR BUSCAR AO JSON....
            filename = os.path.join(dirn, 'unidades_saude.json')
            #with open("/home/skywalker/.local/share/QGIS/QGIS3/profiles/default/python/plugins/health_sig/unidades_saude.json",
            #          "r") as read_file:
            with open(filename, "r") as read_file:
                json_file = json.load(read_file)

            # transformar coordenadas gps para as pretendidas
            crsSrc = QgsCoordinateReferenceSystem(4326)  # gps
            crsDest = QgsCoordinateReferenceSystem(3763)  # pt
            xform = QgsCoordinateTransform(crsSrc, crsDest,
                                           QgsProject.instance())

            # addfeatures
            for entry in json_file:
                if entry["fields"]["tempo"] == "2019-01":  # valores recentes
                    x_coord = float(entry["geometry"]["coordinates"][0])
                    y_coord = float(entry["geometry"]["coordinates"][1])
                    num_usf = int(
                        entry["fields"]
                        ["total_usf"])  #numero de unidades de saude familiares
                    entidade = entry["fields"]["entidade"]
                    ars = entry["fields"]["ars"]
                    fet = QgsFeature()
                    fet.setGeometry(QgsGeometry().buffer(
                        distance=num_usf * 10, segments=100).fromPointXY(
                            xform.transform(QgsPointXY(x_coord, y_coord))))
                    fet.setAttributes([
                        QVariant(entidade),
                        QVariant(ars),
                        QVariant(x_coord),
                        QVariant(y_coord),
                        QVariant(num_usf)
                    ])
                    pr.addFeatures([fet])

            vl.updateExtents()
            vl.commitChanges()

            # fazer render categorizado
            features = vl.getFeatures()

            categories = []

            for feat in features:

                f = feat.attributes()[4]  # num_usf
                entidade = feat.attributes()[0]  # entidade
                symbol = QgsSymbol.defaultSymbol(vl.geometryType())
                svgStyle = {}
                path_uni = os.path.join(dirn, 'medicine.svg')
                svgStyle['name'] = path_uni
                svgStyle['size'] = str((f / 10) + 1)

                symbol_layer = QgsSvgMarkerSymbolLayer.create(svgStyle)

                if symbol_layer is not None:
                    symbol.changeSymbolLayer(0, symbol_layer)

                # create renderer object
                category = QgsRendererCategory(f, symbol, str(entidade))
                # entry for the list of category items
                categories.append(category)

                # create renderer object
            renderer = QgsCategorizedSymbolRenderer('Num_USF', categories)

            # assign the created renderer to the layer
            if renderer is not None:
                vl.setRenderer(renderer)

            vl.triggerRepaint()

            QgsProject.instance().addMapLayer(vl)

        # hospitais
        elif result and index == 0:
            vl = QgsVectorLayer("Point?crs=epsg:3763&index=yes", "hospitais",
                                "memory")
            pr = vl.dataProvider()

            # Enter editing mode
            vl.startEditing()

            # add fields
            pr.addAttributes([
                QgsField("Hospital", QVariant.String),
                QgsField("Morada", QVariant.String),
                QgsField("Coord_X", QVariant.Double),
                QgsField("Coord_Y", QVariant.Double)
            ])
            vl.updateFields(
            )  # tell the vector layer to fetch changes from the provider

            # add features ---> IR BUSCAR AO JSON....
            filename = os.path.join(dirn, 'hospitais.json')

            with open(filename, "r") as read_file:
                json_file = json.load(read_file)

            # transformar coordenadas gps para as pretendidas
            crsSrc = QgsCoordinateReferenceSystem(4326)  # gps
            crsDest = QgsCoordinateReferenceSystem(3763)  # pt
            xform = QgsCoordinateTransform(crsSrc, crsDest,
                                           QgsProject.instance())

            # addfeatures
            for entry in json_file.keys():

                x_coord = float(json_file[entry][1][1])
                y_coord = float(json_file[entry][1][0])
                morada = json_file[entry][0]
                fet = QgsFeature()
                fet.setGeometry(QgsGeometry().fromPointXY(
                    xform.transform(QgsPointXY(x_coord, y_coord))))
                fet.setAttributes([
                    QVariant(entry),
                    QVariant(morada),
                    QVariant(x_coord),
                    QVariant(y_coord)
                ])
                pr.addFeatures([fet])

            vl.updateExtents()
            vl.commitChanges()

            #symbol = QgsMarkerSymbol.createSimple({'name': 'square', 'color': 'red'})
            svgStyle = {}
            path_hosp = os.path.join(dirn, 'hospital.svg')
            svgStyle['name'] = path_hosp
            svgStyle['size'] = '6'

            symbol_layer = QgsSvgMarkerSymbolLayer.create(svgStyle)
            symbol = QgsSymbol.defaultSymbol(vl.geometryType())
            #vl.renderer().setSymbol(symbol)
            symbol.changeSymbolLayer(0, symbol_layer)
            vl.renderer().setSymbol(symbol)

            # show the change
            vl.triggerRepaint()

            QgsProject.instance().addMapLayer(vl)

        # farmacias
        elif result and index == 2:
            vl = QgsVectorLayer("Point?crs=epsg:3763&index=yes", "farmacias",
                                "memory")
            pr = vl.dataProvider()

            # Enter editing mode
            vl.startEditing()

            # add fields
            pr.addAttributes([
                QgsField("Farmácia", QVariant.String),
                QgsField("Morada", QVariant.String),
                QgsField("Coord_X", QVariant.Double),
                QgsField("Coord_Y", QVariant.Double)
            ])
            vl.updateFields(
            )  # tell the vector layer to fetch changes from the provider

            # add features ---> IR BUSCAR AO JSON....
            filename = os.path.join(dirn, 'farmacias.json')

            with open(filename, "r") as read_file:
                json_file = json.load(read_file)

            # transformar coordenadas gps para as pretendidas
            crsSrc = QgsCoordinateReferenceSystem(4326)  # gps
            crsDest = QgsCoordinateReferenceSystem(3763)  # pt
            xform = QgsCoordinateTransform(crsSrc, crsDest,
                                           QgsProject.instance())

            # addfeatures
            for entry in json_file.keys():
                x_coord = float(json_file[entry][1][1])
                y_coord = float(json_file[entry][1][0])
                morada = json_file[entry][0]
                fet = QgsFeature()
                fet.setGeometry(QgsGeometry().fromPointXY(
                    xform.transform(QgsPointXY(x_coord, y_coord))))
                fet.setAttributes([
                    QVariant(entry),
                    QVariant(morada),
                    QVariant(x_coord),
                    QVariant(y_coord)
                ])
                pr.addFeatures([fet])

            vl.updateExtents()
            vl.commitChanges()

            #symbol = QgsMarkerSymbol.createSimple({'name': 'square', 'color': 'purplet'})
            #vl.renderer().setSymbol(symbol)
            svgStyle = {}
            path_farm = os.path.join(dirn, 'pharmacy.svg')
            svgStyle['name'] = path_farm
            svgStyle['size'] = '4'
            symbol_layer = QgsSvgMarkerSymbolLayer.create(svgStyle)
            symbol = QgsSymbol.defaultSymbol(vl.geometryType())
            # vl.renderer().setSymbol(symbol)
            symbol.changeSymbolLayer(0, symbol_layer)
            vl.renderer().setSymbol(symbol)

            # show the change
            vl.triggerRepaint()

            QgsProject.instance().addMapLayer(vl)