Exemplo n.º 1
0
    def setLabel(self, stateLayer, isInternational):
        '''
        Sets label rules for layer in localization component
        '''
        # Getting base rule
        root = QgsRuleBasedLabeling.Rule(QgsPalLayerSettings())

        # Creating Rule
        settings = QgsPalLayerSettings()
        if isInternational:
            settings.fieldName = 'concat(upper("nome"), \' - \', upper("SIGLA_PAIS"))'
        else:
            settings.fieldName = 'upper("nome")'
        settings.placement = QgsPalLayerSettings.Horizontal
        settings.centroidInside = True
        settings.isExpression = True

        textFormat = QgsTextFormat()
        textFormat.setColor(QColor(0, 0, 0, 255))
        textFormat.setSize(6)
        settings.setFormat(textFormat)

        # Add rule to root and apply to stateLayer
        rule = QgsRuleBasedLabeling.Rule(settings)
        rule.setActive(True)
        root.appendChild(rule)
        rules = QgsRuleBasedLabeling(root)
        stateLayer.setLabeling(rules)
        stateLayer.setLabelsEnabled(True)
        stateLayer.triggerRepaint()
Exemplo n.º 2
0
 def setStyles(self, layerCounty, orderedCountiesByCentroidDistance, orderedCountiesNamesByArea):
     rulesRoot = QgsRuleBasedLabeling.Rule(QgsPalLayerSettings())
     for n in range(len(orderedCountiesNamesByArea)):
         rule = self.createRules(
             f"'{n+1}'",
             f'"{self.nameAttribute}" = \'{orderedCountiesByCentroidDistance[n][self.nameAttribute]}\'')
         rulesRoot.appendChild(rule)
     rules = QgsRuleBasedLabeling(rulesRoot)
     layerCounty.setLabeling(rules)
     layerCounty.setLabelsEnabled(True)
     layerCounty.triggerRepaint()
Exemplo n.º 3
0
    def utmGridlabelPlacer(self, root_rule, grid_spacing, geo_bound_bb, bound_UTM_bb, geo_number_x, geo_number_y, UTM_num_x, UTM_num_y, trUTMLL, trLLUTM, dx, dy, dy0, dy1, fSize, fontType, scale, utmcheck, geo_bb_or):
        xmin_source = float(geo_bound_bb.split()[1])
        ymin_source = float(geo_bound_bb.split()[2])
        xmax_source = float(geo_bound_bb.split()[3])
        ymax_source = float(geo_bound_bb.split()[4])
        xmin_UTM = float(bound_UTM_bb.split()[1])
        ymin_UTM = float(bound_UTM_bb.split()[2])
        xmax_UTM = float(bound_UTM_bb.split()[3])
        ymax_UTM = float(bound_UTM_bb.split()[4])
        px = (xmax_source-xmin_source)/(geo_number_x+1)
        py = (ymax_source-ymin_source)/(geo_number_y+1)

        if grid_spacing > 0:
            # Bottom
            ruletest = QgsRuleBasedLabeling.Rule(QgsPalLayerSettings())
            ruletest = self.utm_grid_labeler (ruletest, xmin_UTM, ymin_UTM, 0, ymin_source, px, py, trUTMLL, trLLUTM, 1, True, 0, dy[1]+0.4*(scale)*fSize/1.5, dy0[1]+0.4*(scale)*fSize/1.5, 0, 'Top', 'Center', 'UTMBotTest', fSize, fontType, grid_spacing, scale, utmcheck, geo_bound_bb, range(1), geo_bb_or)
            rulechild = ruletest.children()[0]
            if rulechild.settings().fieldName == 'fail':
                rangeUD = range(2, UTM_num_x+1)
            else:
                rangeUD = range(1, UTM_num_x+1)

            for u in rangeUD:
                root_rule = self.utm_grid_labeler (root_rule, xmin_UTM, ymin_UTM, 0, ymin_source, px, py, trUTMLL, trLLUTM, u, True, 0, dy[1]+0.4*(scale)*fSize/1.5, dy0[1]+0.4*(scale)*fSize/1.5, 0, 'Top', 'Center', 'UTMBot'+str(u), fSize, fontType, grid_spacing, scale, utmcheck, geo_bound_bb, rangeUD, geo_bb_or)

            # Upper
            rangeUD = range(1, UTM_num_x+1)
            for u in rangeUD:
                root_rule = self.utm_grid_labeler (root_rule, xmin_UTM, ymax_UTM, 0, ymax_source, px, py, trUTMLL, trLLUTM, u, True, 0, dy[0]-1.3*(scale)*fSize/1.5, dy0[0]-1.3*(scale)*fSize/1.5, 0, 'Bottom', 'Center', 'UTMUp'+str(u), fSize, fontType, grid_spacing, scale, utmcheck, geo_bound_bb, rangeUD, geo_bb_or)

            # Left
            ruletest = QgsRuleBasedLabeling.Rule(QgsPalLayerSettings())
            ruletest = self.utm_grid_labeler (ruletest, xmin_UTM, ymin_UTM, xmin_source, 0, px, py, trUTMLL, trLLUTM, 1, False, dx[2]-3.1*scale*fSize/1.5, dy[3], dy0[3], dy1[1], 'Bottom', 'Center', 'UTMLeftTest', fSize, fontType, grid_spacing, scale, utmcheck, geo_bound_bb, range(1), geo_bb_or)
            rulechild = ruletest.children()[0]
            if rulechild.settings().fieldName == 'fail':
                rangeLat = range(2, UTM_num_y+1)
            else:
                rangeLat = range(1, UTM_num_y+1)
            for u in rangeLat:
                if u==min(rangeLat): 
                    extra_dist = -2.0*scale*fSize/1.5
                else:
                    extra_dist = 0
                root_rule = self.utm_grid_labeler (root_rule, xmin_UTM, ymin_UTM, xmin_source, 0, px, py, trUTMLL, trLLUTM, u, False, dx[2]+extra_dist, dy[3], dy0[3], dy1[1], 'Bottom', 'Center', 'UTMLeft'+str(u), fSize, fontType, grid_spacing, scale, utmcheck, geo_bound_bb, rangeLat, geo_bb_or)

            # Right
            rangeLat = range(1, UTM_num_y+1)
            for u in rangeLat:
                root_rule = self.utm_grid_labeler (root_rule, xmax_UTM, ymin_UTM, xmax_source, 0, px, py, trUTMLL, trLLUTM, u, False, dx[3], dy[3], dy0[3], dy1[1], '', 'Center', 'UTMRight'+str(1), fSize, fontType, grid_spacing, scale, utmcheck, geo_bound_bb, rangeLat, geo_bb_or)

        return root_rule
Exemplo n.º 4
0
 def reset(self, layer):
     layer_rst = layer
     properties = {'color': 'black'}
     grid_symb = QgsFillSymbol.createSimple(properties)
     symb_out = QgsSimpleFillSymbolLayer()
     symb_out.setFillColor(QColor('white'))
     grid_symb.changeSymbolLayer(0, symb_out)
     render_base = QgsSingleSymbolRenderer(grid_symb)
     layer_rst.setRenderer(render_base)
     root_rule = QgsRuleBasedLabeling.Rule(QgsPalLayerSettings())
     rules = QgsRuleBasedLabeling(root_rule)
     layer_rst.setLabeling(rules)
     layer_rst.setLabelsEnabled(False)
     layer_rst.triggerRepaint()
     return
Exemplo n.º 5
0
    def geoGridlabelPlacer(self, geo_bound_bb, geo_number_x, geo_number_y, dx, dy, fSize, LLfontType, trLLUTM, trUTMLL, llcolor, utmcheck, scale):
        xmin_source = float(geo_bound_bb.split()[1])
        ymin_source = float(geo_bound_bb.split()[2])
        xmax_source = float(geo_bound_bb.split()[3])
        ymax_source = float(geo_bound_bb.split()[4])

        px = (xmax_source-xmin_source)/(geo_number_x+1)
        py = (ymax_source-ymin_source)/(geo_number_y+1)

        root_rule = QgsRuleBasedLabeling.Rule(QgsPalLayerSettings())

        #Upper
        for u in range(0, geo_number_x+2):
            if u ==0:
                ruletemp = self.grid_labeler (xmin_source, ymax_source, px, py, u, 0, dx[2], dy[0], '', 'Center', 'Up '+str(u+1), fSize, LLfontType, str(self.conv_dec_gms(xmin_source, px, u, 'W', 'E'))+'+\'. GREENWICH\'', trLLUTM, trUTMLL, llcolor, utmcheck, scale)
                root_rule.appendChild(ruletemp)
            else:
                ruletemp = self.grid_labeler (xmin_source, ymax_source, px, py, u, 0, 0, dy[0], '', 'Center', 'Up '+str(u+1), fSize, LLfontType, self.conv_dec_gms(xmin_source, px, u, 'W', 'E'), trLLUTM, trUTMLL, llcolor, utmcheck, scale)
                root_rule.appendChild(ruletemp)
        #Bottom
        for b in range(0, geo_number_x+2):
            ruletemp = self.grid_labeler (xmin_source, ymin_source, px, py, b, 0, 0, dy[1], '', 'Center', 'Bot '+str(b+1), fSize, LLfontType, self.conv_dec_gms(xmin_source, px, b, 'W', 'E'), trLLUTM, trUTMLL, llcolor,  utmcheck, scale)
            root_rule.appendChild(ruletemp)
        #Right
        for r in range(0, geo_number_y+2):
            ruletemp = self.grid_labeler (xmax_source, ymin_source, px, py, 0, r, dx[0], 0, 'Half', '', 'Right '+str(r+1), fSize, LLfontType, self.conv_dec_gms(ymin_source, py, r, 'S', 'N'), trLLUTM, trUTMLL, llcolor, utmcheck, scale)
            root_rule.appendChild(ruletemp)
        #Left
        for l in range(0, geo_number_y+2):
            ruletemp = self.grid_labeler (xmin_source, ymin_source, px, py, 0, l, dx[1], 0, 'Half', '', 'Left '+str(l+1), fSize, LLfontType, self.conv_dec_gms(ymin_source, py, l, 'S', 'N'), trLLUTM, trUTMLL, llcolor, utmcheck, scale)
            root_rule.appendChild(ruletemp)

        return root_rule
Exemplo n.º 6
0
    def convert_annotation_collection(
            collection: AnnotateLayerPropertiesCollection,
            dest_layer: QgsVectorLayer, context):
        """
        Converts an annotation collection to QGIS labeling
        """
        if collection is None:
            return

        if len(collection.properties
               ) == 1 and not collection.properties[0].class_filter:
            # one label class, use simple labeling
            properties = collection.properties[0]
            label_settings = LabelConverter.convert_label_engine_layer_properties(
                properties,
                layer_geometry_type=dest_layer.geometryType(),
                context=context)
            label_settings.drawLabels = properties.label_features

            labeling = QgsVectorLayerSimpleLabeling(label_settings)
            dest_layer.setLabeling(labeling)
        else:
            # multiple classes, use rule-based labeling
            root_rule = QgsRuleBasedLabeling.Rule(None)
            for p in collection.properties:
                label_settings = LabelConverter.convert_label_engine_layer_properties(
                    p,
                    layer_geometry_type=dest_layer.geometryType(),
                    context=context)

                zoom_max = p.scale_range_min
                zoom_min = p.scale_range_max
                if zoom_max and zoom_min and zoom_max > zoom_min:
                    zoom_min, zoom_max = zoom_max, zoom_min

                rule = QgsRuleBasedLabeling.Rule(
                    label_settings, zoom_max, zoom_min,
                    ExpressionConverter.convert_esri_sql(p.class_filter),
                    p.class_name)
                rule.setActive(p.label_features)
                root_rule.appendChild(rule)
            labeling = QgsRuleBasedLabeling(root_rule)
            dest_layer.setLabeling(labeling)
Exemplo n.º 7
0
    def geoGridlabelPlacer(self, extentsGeo, px, py, geo_number_x,
                           geo_number_y, dx, dy, fSize, LLfontType, trLLUTM,
                           llcolor, scale, layer_bound, trUTMLL):
        root_rule = QgsRuleBasedLabeling.Rule(QgsPalLayerSettings())

        #Upper
        for u in range(0, geo_number_x + 2):
            if u == 0:
                ruletemp = self.grid_labeler(
                    extentsGeo[0], extentsGeo[3], px, py, u, 0, dx[2], dy[0],
                    'Up ' + str(u + 1), fSize, LLfontType,
                    str(
                        self.conv_dec_gms(extentsGeo[0], u, 'W', 'E',
                                          extentsGeo, True, geo_number_x,
                                          geo_number_y)) + '+\'. GREENWICH\'',
                    trLLUTM, llcolor, layer_bound, trUTMLL)
                root_rule.appendChild(ruletemp)
            else:
                ruletemp = self.grid_labeler(
                    extentsGeo[0], extentsGeo[3], px, py, u, 0, dx[3], dy[0],
                    'Up ' + str(u + 1), fSize, LLfontType,
                    self.conv_dec_gms(extentsGeo[0], u, 'W', 'E', extentsGeo,
                                      True, geo_number_x, geo_number_y),
                    trLLUTM, llcolor, layer_bound, trUTMLL)
                root_rule.appendChild(ruletemp)
        #Bottom
        for b in range(0, geo_number_x + 2):
            ruletemp = self.grid_labeler(
                extentsGeo[0], extentsGeo[1], px, py, b, 0, dx[3], dy[1],
                'Bot ' + str(b + 1), fSize, LLfontType,
                self.conv_dec_gms(extentsGeo[0], b, 'W', 'E', extentsGeo, True,
                                  geo_number_x, geo_number_y), trLLUTM,
                llcolor, layer_bound, trUTMLL)
            root_rule.appendChild(ruletemp)
        #Right
        for r in range(0, geo_number_y + 2):
            ruletemp = self.grid_labeler(
                extentsGeo[2], extentsGeo[1], px, py, 0, r, dx[0], dy[2],
                'Right ' + str(r + 1), fSize, LLfontType,
                self.conv_dec_gms(extentsGeo[1], r, 'S', 'N', extentsGeo,
                                  False, geo_number_x, geo_number_y), trLLUTM,
                llcolor, layer_bound, trUTMLL)
            root_rule.appendChild(ruletemp)
        #Left
        for l in range(0, geo_number_y + 2):
            ruletemp = self.grid_labeler(
                extentsGeo[0], extentsGeo[1], px, py, 0, l, dx[1], dy[3],
                'Left ' + str(l + 1), fSize, LLfontType,
                self.conv_dec_gms(extentsGeo[1], l, 'S', 'N', extentsGeo,
                                  False, geo_number_x, geo_number_y), trLLUTM,
                llcolor, layer_bound, trUTMLL)
            root_rule.appendChild(ruletemp)

        return root_rule
Exemplo n.º 8
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
Exemplo n.º 9
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
Exemplo n.º 10
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
Exemplo n.º 11
0
    def styleCreator(self, feature_geometry, layer_bound, utmSRID, id_attr,
                     id_value, spacing, crossX, crossY, scale, fontSize, font,
                     fontLL, llcolor, linwidth_geo, linwidth_utm,
                     linwidth_buffer_geo, linwidth_buffer_utm, geo_grid_color,
                     utm_grid_color, geo_grid_buffer_color,
                     utm_grid_buffer_color, masks_check):
        """Getting Input Data For Grid Generation"""
        linwidth_buffer_utm += linwidth_utm
        linwidth_buffer_geo += linwidth_geo
        grid_spacing = spacing
        geo_number_x = crossX
        geo_number_y = crossY
        fSize = fontSize
        fontType = font
        LLfontType = fontLL

        #Defining CRSs Transformations
        trLLUTM = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem('EPSG:4326'),
            QgsCoordinateReferenceSystem('EPSG:' + str(utmSRID)),
            QgsProject.instance())
        trUTMLL = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem('EPSG:' + str(utmSRID)),
            QgsCoordinateReferenceSystem('EPSG:4326'), QgsProject.instance())

        #Transforming to Geographic and defining bounding boxes
        feature_bbox = feature_geometry.boundingBox()
        bound_UTM_bb = str(feature_bbox).replace(',', '').replace('>', '')
        feature_geometry.transform(trUTMLL)
        feature_geo_bbox = feature_geometry.boundingBox()
        feature_bbox_or = feature_geometry.orientedMinimumBoundingBox()
        geo_bound_bb = str(feature_geo_bbox).replace(',', '').replace('>', '')
        oriented_geo_bb = str(feature_bbox_or).replace(',', '').replace(
            '>', '').replace('((', '').replace('))', '')

        #Defining UTM Grid Symbology Type
        properties = {'color': 'black'}
        grid_symb = QgsFillSymbol.createSimple(properties)
        """ Creating UTM Grid """
        extentsUTM = (float(bound_UTM_bb.split()[1]),
                      float(bound_UTM_bb.split()[2]),
                      float(bound_UTM_bb.split()[3]),
                      float(bound_UTM_bb.split()[4]))
        extentsGeo = (float(geo_bound_bb.split()[1]),
                      float(geo_bound_bb.split()[2]),
                      float(geo_bound_bb.split()[3]),
                      float(geo_bound_bb.split()[4]))
        if grid_spacing > 0:
            UTM_num_x = floor(extentsUTM[2] / grid_spacing) - floor(
                extentsUTM[0] / grid_spacing)
            UTM_num_y = floor(extentsUTM[3] / grid_spacing) - floor(
                extentsUTM[1] / grid_spacing)

            if linwidth_buffer_utm != linwidth_utm:
                #Generating Buffer Vertical Lines
                for x in range(1, UTM_num_x + 1):
                    grid_symb = self.utm_Symb_Generator(
                        utmSRID, grid_spacing, trUTMLL, trLLUTM, grid_symb,
                        properties, UTM_num_x, UTM_num_y, x, 0, extentsGeo,
                        extentsUTM, linwidth_buffer_utm, utm_grid_buffer_color)

                #Generating Buffer Horizontal Lines
                for y in range(1, UTM_num_y + 1):
                    grid_symb = self.utm_Symb_Generator(
                        utmSRID, grid_spacing, trUTMLL, trLLUTM, grid_symb,
                        properties, UTM_num_x, UTM_num_y, 0, y, extentsGeo,
                        extentsUTM, linwidth_buffer_utm, utm_grid_buffer_color)

            #Generating Vertical Lines
            for x in range(1, UTM_num_x + 1):
                grid_symb = self.utm_Symb_Generator(
                    utmSRID, grid_spacing, trUTMLL, trLLUTM, grid_symb,
                    properties, UTM_num_x, UTM_num_y, x, 0, extentsGeo,
                    extentsUTM, linwidth_utm, utm_grid_color)

            #Generating Horizontal Lines
            for y in range(1, UTM_num_y + 1):
                grid_symb = self.utm_Symb_Generator(
                    utmSRID, grid_spacing, trUTMLL, trLLUTM, grid_symb,
                    properties, UTM_num_x, UTM_num_y, 0, y, extentsGeo,
                    extentsUTM, linwidth_utm, utm_grid_color)
        """ Creating Geo Grid """
        px = (round(extentsGeo[2], 6) -
              round(extentsGeo[0], 6)) / (geo_number_x + 1)
        py = (round(extentsGeo[3], 6) -
              round(extentsGeo[1], 6)) / (geo_number_y + 1)
        if linwidth_buffer_geo != linwidth_geo:
            grid_symb = self.geoGridcreator(utmSRID, grid_symb, extentsGeo, px,
                                            py, geo_number_x, geo_number_y,
                                            scale, trLLUTM,
                                            linwidth_buffer_geo,
                                            geo_grid_buffer_color)
        grid_symb = self.geoGridcreator(utmSRID, grid_symb, extentsGeo, px, py,
                                        geo_number_x, geo_number_y, scale,
                                        trLLUTM, linwidth_geo, geo_grid_color)
        """ Rendering UTM and Geographic Grid """
        #Changing UTM Grid Color
        grid_symb.deleteSymbolLayer(0)

        #Creating Rule Based Renderer (Rule For The Selected Feature, Root Rule)
        symb_new = QgsRuleBasedRenderer.Rule(grid_symb)
        symb_new.setFilterExpression('\"' + str(id_attr) + '\" = ' +
                                     str(id_value))
        symb_new.setLabel('layer')

        #Appending rules to symbol root rule
        root_symbol_rule = QgsRuleBasedRenderer.Rule(None)
        root_symbol_rule.setFilterExpression('')
        root_symbol_rule.appendChild(symb_new)

        #Applying New Renderer
        render_base = QgsRuleBasedRenderer(root_symbol_rule)
        layer_bound.setRenderer(render_base)
        """Rendering outside area"""
        #Duplicating original layer
        layers_names = [
            i.name() for i in QgsProject.instance().mapLayers().values()
        ]
        if (layer_bound.name() + "_outside") not in layers_names:
            outside_bound_layer = QgsVectorLayer(
                layer_bound.source(),
                layer_bound.name() + "_outside", layer_bound.providerType())
            if layer_bound.providerType() == 'memory':
                feats = [feat for feat in layer_bound.getFeatures()]
                outside_bound_layer_data = outside_bound_layer.dataProvider()
                outside_bound_layer_data.addFeatures(feats)
            QgsProject.instance().addMapLayer(outside_bound_layer)
        else:
            outside_bound_layer = QgsProject.instance().mapLayersByName(
                layer_bound.name() + "_outside")[0]

        #Creating Rule Based Renderer (Rule For The Other Features)
        properties = {'color': 'white'}
        ext_grid_symb = QgsFillSymbol.createSimple(properties)
        symb_out = QgsSimpleFillSymbolLayer()
        symb_out.setFillColor(QColor('white'))
        symb_out.setStrokeWidth(linwidth_utm)
        ext_grid_symb.changeSymbolLayer(0, symb_out)
        rule_out = QgsRuleBasedRenderer.Rule(ext_grid_symb)
        rule_out.setFilterExpression('\"' + str(id_attr) + '\" = ' +
                                     str(id_value))
        rule_out.setLabel('outside')

        root_symbol_rule_out = QgsRuleBasedRenderer.Rule(None)
        root_symbol_rule_out.appendChild(rule_out)

        render_base_out = QgsRuleBasedRenderer(root_symbol_rule_out)
        new_renderer = QgsInvertedPolygonRenderer.convertFromRenderer(
            render_base_out)
        outside_bound_layer.setRenderer(new_renderer)
        """ Labeling Geo Grid """
        dx = [2.0, -11.0, -8.0, -3.6]
        dx = [i * scale * fSize / 1.5 for i in dx]
        dy = [1.7, -3.8, -0.8, -0.8]
        dy = [i * scale * fSize / 1.5 for i in dy]

        root_rule = self.geoGridlabelPlacer(extentsGeo, px, py, geo_number_x,
                                            geo_number_y, dx, dy, fSize,
                                            LLfontType, trLLUTM, llcolor,
                                            scale, layer_bound, trUTMLL)
        """ Labeling UTM Grid"""
        dx = [-2.9, -2.9, -8.9, 2.0]
        dx = [i * scale * fSize / 1.5 for i in dx]
        dy = [1.4, -4.6, -0.5, -1.5]
        dy = [i * scale * fSize / 1.5 for i in dy]
        dy0 = [5.0, -7.2, -3.2, -4.2]
        dy0 = [i * scale * fSize / 1.5 for i in dy0]
        dy1 = [2.15, 1.2]
        dy1 = [i * scale * fSize / 1.5 for i in dy1]

        root_rule = self.utmGridlabelPlacer(root_rule, grid_spacing,
                                            extentsGeo, extentsUTM, px, py,
                                            UTM_num_x, UTM_num_y, trUTMLL,
                                            trLLUTM, dx, dy, dy0, dy1, fSize,
                                            fontType, scale, oriented_geo_bb,
                                            layer_bound)
        """ Activating Labels """
        rules = QgsRuleBasedLabeling(root_rule)
        layer_bound.setLabeling(rules)
        layer_bound.setLabelsEnabled(True)

        if masks_check:
            self.apply_masks(layer_bound)

        layer_bound.triggerRepaint()

        return
Exemplo n.º 12
0
    def utmGridlabelPlacer(self, root_rule, grid_spacing, extentsGeo,
                           extentsUTM, px, py, UTM_num_x, UTM_num_y, trUTMLL,
                           trLLUTM, dx, dy, dy0, dy1, fSize, fontType, scale,
                           geo_bb_or, layer_bound):
        if grid_spacing > 0:
            # Bottom
            ruletest = QgsRuleBasedLabeling.Rule(QgsPalLayerSettings())
            ruletest = self.utm_grid_labeler(
                ruletest, extentsUTM[0], extentsUTM[1], 0, extentsGeo[1],
                extentsGeo[0], extentsGeo[1], px, py, trUTMLL, trLLUTM, 1,
                True, dx[0], dy[1], dy0[1], 0, 'UTMBotTest', fSize, fontType,
                grid_spacing, scale, range(1), geo_bb_or, layer_bound)
            rulechild = ruletest.children()[0]
            if rulechild.settings().fieldName == 'fail':
                rangeUD = range(2, UTM_num_x + 1)
            else:
                rangeUD = range(1, UTM_num_x + 1)

            for u in rangeUD:
                root_rule = self.utm_grid_labeler(
                    root_rule, extentsUTM[0], extentsUTM[1], 0, extentsGeo[1],
                    extentsGeo[0], extentsGeo[1], px, py, trUTMLL, trLLUTM, u,
                    True, dx[0], dy[1], dy0[1] + 0.4 * (scale) * fSize / 1.5,
                    0, 'UTMBot' + str(u), fSize, fontType, grid_spacing, scale,
                    rangeUD, geo_bb_or, layer_bound)

            # Upper
            rangeUD = range(1, UTM_num_x + 1)
            for u in rangeUD:
                root_rule = self.utm_grid_labeler(
                    root_rule, extentsUTM[0], extentsUTM[3], 0, extentsGeo[3],
                    extentsGeo[0], extentsGeo[1], px, py, trUTMLL, trLLUTM, u,
                    True, dx[1], dy[0], dy0[0] - 1.3 * (scale) * fSize / 1.5,
                    0, 'UTMUp' + str(u), fSize, fontType, grid_spacing, scale,
                    rangeUD, geo_bb_or, layer_bound)

            # Left
            ruletest = QgsRuleBasedLabeling.Rule(QgsPalLayerSettings())
            ruletest = self.utm_grid_labeler(
                ruletest, extentsUTM[0], extentsUTM[1], extentsGeo[0], 0,
                extentsGeo[0], extentsGeo[1], px, py, trUTMLL, trLLUTM, 1,
                False, dx[2], dy[3], dy0[3],
                dy1[1], 'UTMLeftTest', fSize, fontType, grid_spacing, scale,
                range(1), geo_bb_or, layer_bound)
            rulechild = ruletest.children()[0]
            if rulechild.settings().fieldName == 'fail':
                rangeLat = range(2, UTM_num_y + 1)
            else:
                rangeLat = range(1, UTM_num_y + 1)
            for u in rangeLat:
                if u == min(rangeLat):
                    extra_dist = -3.2 * scale * fSize / 1.5
                else:
                    extra_dist = 0
                root_rule = self.utm_grid_labeler(
                    root_rule, extentsUTM[0], extentsUTM[1], extentsGeo[0], 0,
                    extentsGeo[0], extentsGeo[1], px, py, trUTMLL, trLLUTM, u,
                    False, dx[2] + extra_dist, dy[3], dy0[3], dy1[1],
                    'UTMLeft' + str(u), fSize, fontType, grid_spacing, scale,
                    rangeLat, geo_bb_or, layer_bound)

            # Right
            rangeLat = range(1, UTM_num_y + 1)
            for u in rangeLat:
                root_rule = self.utm_grid_labeler(
                    root_rule, extentsUTM[2], extentsUTM[1], extentsGeo[2], 0,
                    extentsGeo[0], extentsGeo[1], px, py, trUTMLL, trLLUTM, u,
                    False, dx[3], dy[3], dy0[3], dy1[1], 'UTMRight' + str(1),
                    fSize, fontType, grid_spacing, scale, rangeLat, geo_bb_or,
                    layer_bound)

        return root_rule
Exemplo n.º 13
0
    def styleCreator(self, layer, index, id_attr, id_value, spacing, crossX,
                     crossY, scale, color, fontSize, font, fontLL, llcolor,
                     utmcheck):
        """Getting Input Data For Grid Generation"""
        grid_spacing = spacing
        geo_number_x = crossX
        geo_number_y = crossY
        fSize = fontSize
        fontType = font
        LLfontType = fontLL

        #Loading feature
        layer_bound = layer
        query = '"' + str(id_attr) + '"=' + str(id_value)
        layer_bound.selectByExpression(query, QgsVectorLayer.SelectBehavior(0))
        feature_bound = layer_bound.selectedFeatures()[0]
        layer_bound.removeSelection()

        #Getting Feature Source CRS and Geometry
        if utmcheck:
            feature_geometry = feature_bound.geometry()
            bound_UTM = layer_bound.crs().authid()
            feature_bbox = feature_geometry.boundingBox()
            bound_UTM_bb = str(feature_bbox).replace(',', '').replace('>', '')
            # Transforming to Geographic
            transform_feature = QgsCoordinateTransform(
                QgsCoordinateReferenceSystem(bound_UTM),
                QgsCoordinateReferenceSystem('EPSG:4674'),
                QgsProject.instance())
            feature_geometry.transform(transform_feature)
            bound_sourcecrs = 'EPSG:4674'
            feature_bbox = feature_geometry.boundingBox()
            feature_bbox_or = feature_geometry.orientedMinimumBoundingBox()
        else:
            feature_geometry = feature_bound.geometry()
            bound_sourcecrs = layer_bound.crs().authid()
            feature_bbox = feature_geometry.boundingBox()
            feature_bbox_or = feature_geometry.orientedMinimumBoundingBox()
        geo_bound_bb = str(feature_bbox).replace(',', '').replace('>', '')
        oriented_geo_bb = str(feature_bbox_or).replace(',', '').replace(
            '>', '').replace('((', '').replace('))', '')

        #Defining CRSs Transformations
        inom = feature_bound[index]
        if inom[0] == 'N':
            bound_UTM = 'EPSG:319' + str(72 + int(inom[3:5]) - 18)
        elif inom[0] == 'S':
            bound_UTM = 'EPSG:319' + str(78 + int(inom[3:5]) - 18)
        else:
            iface.messageBar().pushMessage("Error",
                                           "Invalid index attribute",
                                           level=Qgis.Critical)
            return
        trLLUTM = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem(bound_sourcecrs),
            QgsCoordinateReferenceSystem(bound_UTM), QgsProject.instance())
        trUTMLL = QgsCoordinateTransform(
            QgsCoordinateReferenceSystem(bound_UTM),
            QgsCoordinateReferenceSystem(bound_sourcecrs),
            QgsProject.instance())

        #Defining UTM Grid Symbology Type
        renderer = layer.renderer()
        properties = {'color': 'black'}
        grid_symb = QgsFillSymbol.createSimple(properties)
        symb_out = QgsSimpleFillSymbolLayer()
        symb_out.setStrokeColor(QColor('black'))
        symb_out.setFillColor(QColor('white'))
        symb_out.setStrokeWidth(0.05)
        """ Creating UTM Grid """
        if not utmcheck:
            geo_UTM = feature_bound.geometry()
            geo_UTM.transform(trLLUTM)
            bound_UTM_bb = str(geo_UTM.boundingBox()).replace(',', '').replace(
                '>', '')
        xmin_UTM = float(bound_UTM_bb.split()[1])
        ymin_UTM = float(bound_UTM_bb.split()[2])
        xmax_UTM = float(bound_UTM_bb.split()[3])
        ymax_UTM = float(bound_UTM_bb.split()[4])

        if grid_spacing > 0:
            UTM_num_x = floor(xmax_UTM / grid_spacing) - floor(
                xmin_UTM / grid_spacing)
            UTM_num_y = floor(ymax_UTM / grid_spacing) - floor(
                ymin_UTM / grid_spacing)
            #Generating Vertical Lines
            for x in range(1, UTM_num_x + 1):
                grid_symb = self.utm_symb_generator(
                    grid_spacing, trUTMLL, trLLUTM, grid_symb, properties,
                    geo_number_x, geo_number_y, UTM_num_x, UTM_num_y, x, 0,
                    geo_bound_bb, bound_UTM_bb, utmcheck)
            #Generating Horizontal Lines
            for y in range(1, UTM_num_y + 1):
                grid_symb = self.utm_symb_generator(
                    grid_spacing, trUTMLL, trLLUTM, grid_symb, properties,
                    geo_number_x, geo_number_y, UTM_num_x, UTM_num_y, 0, y,
                    geo_bound_bb, bound_UTM_bb, utmcheck)
        """ Creating Geo Grid """
        grid_symb = self.geoGridcreator(grid_symb, geo_bound_bb, geo_number_x,
                                        geo_number_y, scale, utmcheck, trLLUTM)
        """ Rendering UTM and Geographic Grid """
        #Changing UTM Grid Color
        grid_symb.setColor(color)
        grid_symb.changeSymbolLayer(0, symb_out)
        #Creating Rule Based Renderer (Rule For The Other Features)
        properties = {'color': 'white'}
        ext_grid_symb = QgsFillSymbol.createSimple(properties)
        symb_ot = QgsRuleBasedRenderer.Rule(ext_grid_symb)
        symb_ot.setFilterExpression('\"' + str(id_attr) + '\" <> ' +
                                    str(id_value))
        symb_ot.setLabel('other')
        #Creating Rule Based Renderer (Rule For The Selected Feature, Root Rule)
        symb_new = QgsRuleBasedRenderer.Rule(grid_symb)
        symb_new.setFilterExpression('\"' + str(id_attr) + '\" = ' +
                                     str(id_value))
        symb_new.setLabel('layer')
        symb_new.appendChild(symb_ot)
        #Applying New Renderer
        render_base = QgsRuleBasedRenderer(symb_new)
        new_renderer = QgsInvertedPolygonRenderer.convertFromRenderer(
            render_base)
        layer_bound.setRenderer(new_renderer)
        """ Labeling Geo Grid """
        if utmcheck:
            dx = [
                2 * scale * fSize / 1.5, -13.6 * scale * fSize / 1.5,
                6 * scale * fSize / 1.5
            ]
            dy = [1.7 * scale * fSize / 1.5, -3.8 * scale * fSize / 1.5]
        else:
            dx = [0.000018 * scale, -0.000120 * scale, 0.00005 * scale]
            dy = [0.000015 * scale, -0.000040 * scale]

        root_rule = self.geoGridlabelPlacer(geo_bound_bb, geo_number_x,
                                            geo_number_y, dx, dy, fSize,
                                            LLfontType, trLLUTM, trUTMLL,
                                            llcolor, utmcheck, scale)
        """ Labeling UTM Grid"""
        if utmcheck:
            dx = [-2.7, -9.7, -6.2, 5.4]
            dx = [i * scale * fSize / 1.5 for i in dx]
            dy = [2.5, -1.7, -0.5, -1.5]
            dy = [i * scale * fSize / 1.5 for i in dy]
            dy0 = [5.45, -4.8, -3.2, -4.2]
            dy0 = [i * scale * fSize / 1.5 for i in dy0]
            dy1 = [2.15, 1.2]
            dy1 = [i * scale * fSize / 1.5 for i in dy1]
        else:
            dx = [-0.00003, -0.000107, -0.000070, 0.000060]
            dx = [i * scale * fSize / 1.5 for i in dx]
            dy = [0.000027, 0.000016, -0.000041, -0.000052]
            dy = [i * scale * fSize / 1.5 for i in dy]
            dy0 = [0.0000644, 0.000053, -0.000076, -0.000087]
            dy0 = [i * scale * fSize / 1.5 for i in dy0]
            dy1 = [0.000032, 0.000020]
            dy1 = [i * scale * fSize / 1.5 for i in dy1]

        root_rule = self.utmGridlabelPlacer(
            root_rule, grid_spacing, geo_bound_bb, bound_UTM_bb, geo_number_x,
            geo_number_y, UTM_num_x, UTM_num_y, trUTMLL, trLLUTM, dx, dy, dy0,
            dy1, fSize, fontType, scale, utmcheck, oriented_geo_bb)
        """ Activating Labels """
        rules = QgsRuleBasedLabeling(root_rule)
        layer.setLabeling(rules)
        layer.setLabelsEnabled(True)
        layer.triggerRepaint()
        return
Exemplo n.º 14
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)