def getPoint(self, mapPoint):
        self.set_rad.setEnabled(True)
        # change tool so you don't get more than one POI
        self.canvas.unsetMapTool(self.emitPoint)
        self.canvas.setMapTool(self.userTool)
        # Get the click
        if mapPoint:
            self.atk_pt = QgsPoint(mapPoint)
            self.distance()
            # Specify the geometry type
            layer = QgsVectorLayer('Point?crs=epsg:28992', 'Attack Point',
                                   'memory')

            style = "style_attack.qml"
            qml_path = self.plugin_dir + "/data/" + style
            layer.loadNamedStyle(qml_path)
            layer.triggerRepaint()

            # Set the provider to accept the data source
            prov = layer.dataProvider()

            # Add a new feature and assign the geometry
            feat = QgsFeature()
            feat.setGeometry(QgsGeometry.fromPoint(mapPoint))
            prov.addFeatures([feat])

            # Update extent of the layer
            layer.updateExtents()

            # Add the layer to the Layers panel
            QgsMapLayerRegistry.instance().addMapLayers([layer])
Пример #2
0
    def draw_layer(self, layer_name):

        displayed = layer_name in self.layers
        if displayed:
            if self.layers[layer_name].isValid():
                self.layers[layer_name].setCacheImage(None)
                self.layers[layer_name].triggerRepaint()
            return

        # Specify the view and the column to use for the layer
        self.uri.setDataSource('public', 'measure_formated', layer_name)
        # Specify the primary key of the entries. For the record, the only unique column is measure_id
        self.uri.setKeyColumn('measure_id')
        # Create a layer based on the information previously specified (database and column). The layer is
        # not yet added to the UI. The layer is a Postgres type
        layer = QgsVectorLayer(self.uri.uri(), layer_name, 'postgres')
        # Check if the Layer is valid or not (in case of the column/table/... does not exist
        if not layer.isValid():
            # print("Erreur au chargement de " + layer_name)
            return
        # Save the layer into the layer list (reminder: the layer list is useful to refresh all layers when
        # a notification is received)
        # Add the created layer to the QGIS project
        QgsMapLayerRegistry.instance().addMapLayer(layer)

        self.layers[layer_name] = layer
        # refresh the layer
        layer.setCacheImage(None)
        layer.triggerRepaint()
    def evacuateThis(self):
        # Write to log
        time = strftime("%d-%m-%Y %H:%M:%S", localtime())
        evac_type = self.to_evac_info.item(0, 0).text()
        to_evac = self.to_evac_info.item(1, 0).text()
        adr = self.to_evac_info.item(2, 0).text()
        pop = int(self.to_evac_info.item(3, 0).text())
        log_str = time + ":" + "\nBuilding selected for evacuation." \
                               "\nType:\t%s\nName:\t%s\nAddress:\t%s\nPredicted pop:\t%d\n" %(evac_type, to_evac, adr, pop)
        self.log.append(log_str)

        evac_type = self.shelter_info.item(0, 0).text()
        to_evac = self.shelter_info.item(1, 0).text()
        adr = self.shelter_info.item(2, 0).text()
        log_str = "Evacuate to:\nType:\t%s\nName:\t%s\nAddress:\t%s\n" % (
            evac_type, to_evac, adr)
        self.log.append(log_str)

        # Mark things as DONE
        if not (uf.getLegendLayerByName(self.iface, "Done")):
            done = QgsVectorLayer('Point?crs=epsg:28992', 'Done', 'memory')
            QgsMapLayerRegistry.instance().addMapLayers([done])
            style = "style for green marks.qml"
            qml_path = self.plugin_dir + "/data/" + style
            done.loadNamedStyle(qml_path)
            done.triggerRepaint()
        prov = uf.getLegendLayerByName(self.iface, "Done").dataProvider()
        prov.addFeatures([self.evac_feat])
        self.refreshCanvas(uf.getLegendLayerByName(self.iface, "Done"))

        # Store Selected Routes
        lay1 = uf.getLegendLayerByName(self.iface, "Selected Routes")
        if not (lay1):
            selected = QgsVectorLayer('LINESTRING?crs=epsg:28992',
                                      'Selected Routes', 'memory')
            QgsMapLayerRegistry.instance().addMapLayers([selected])
            style = "style_blue_routes.qml"
            qml_path = self.plugin_dir + "/data/" + style
            selected.loadNamedStyle(qml_path)
            selected.triggerRepaint()
            iface.legendInterface().setLayerVisible(selected, False)
        prov = uf.getLegendLayerByName(self.iface,
                                       "Selected Routes").dataProvider()
        if uf.getLegendLayerByName(self.iface, "Routes"):
            route_layer = uf.getLegendLayerByName(self.iface, "Routes")
            feats = route_layer.getFeatures()
        for feat in feats:
            prov.addFeatures([feat])
        self.refreshCanvas(
            uf.getLegendLayerByName(self.iface, "Selected Routes"))

        uf.addFields(lay1, ['number'], [QVariant.Int])
        uf.updateField(lay1, 'number', 'rand(1,100)')

        # Lower capacity of shelter
        layer = uf.getLegendLayerByName(self.iface, "Shelters")
        layer.startEditing()
        cap = int(self.shelter_info.item(3, 0).text())
        m = cap - pop
        if m > 0:
            layer.changeAttributeValue(self.shel_feat.id(), 8, cap - pop)
        else:
            layer.changeAttributeValue(self.shel_feat.id(), 8, 0)
        layer.commitChanges()

        # Change Number of Buildings to Evacuate
        build = uf.getLegendLayerByName(iface, "Buildings to evacuate")
        buildings = build.getFeatures()
        n = 0
        for building in buildings:
            if building.attributes()[2] != 'police' and building.attributes(
            )[2] != 'fire_station':
                n += 1

        ev = uf.getLegendLayerByName(iface, "Selected Routes")
        evacs = ev.getFeatures()
        m = 0
        for evac in evacs:
            m += 1

        self.buildings.clear()
        if n - m > 0:
            self.buildings.append('%s' % (n - m))
        else:
            self.buildings.append('0')

        # Display confirmation message
        self.sent_msg.setVisible(True)
        QTimer.singleShot(3000, lambda: (self.sent_msg.setVisible(False)))

        # Clear selections to start picking new targets
        self.deleteEvac()
Пример #4
0
    def drawCurva(self):
        if not hasattr(self.c, "dados"):
            self.c.dados = []
            self.comboCurva: QtWidgets.QComboBox
            layer = QgsVectorLayer(
                'LineString?crs=%s' % (QgsProject.instance().crs().authid()),
                "Curva: " + str(self.comboCurva.currentText()), "memory")
            layer.setCrs(
                QgsCoordinateReferenceSystem(QgsProject.instance().crs()))
            layer.renderer().symbol().setWidth(.5)
            layer.renderer().symbol().setColor(QtGui.QColor("#0f16d0"))
            layer.triggerRepaint()
            fields = layerFields()
            layer.dataProvider().addAttributes(fields)
            layer.updateFields()
            QgsProject.instance().addMapLayer(layer, False)
            QgsProject.instance().layerTreeRoot().insertLayer(0, layer)
            self.c.layer = layer

        layer = self.c.layer
        layer.dataProvider().deleteFeatures(
            [f.id() for f in layer.getFeatures()])

        vmax = 0
        k = 0
        i = -1
        data = None

        try:
            if hasattr(self, "justStarted") and self.justStarted:
                for tipo, index, state in self.c.readData():
                    i += 1
                    if tipo == "C":
                        data = circleArc2(layer, state, index, self.layer,
                                          self.next_index)
                        k = 0
                        vmax = "120 km/h"

                    elif tipo == "EC":
                        data = polyTransCircle(layer, state, index, self.layer,
                                               self.next_index,
                                               self.current_index)
                        k = 0
                        vmax = "120 km/h"

                    elif tipo == "EE":
                        data = inSpiral2(layer, state, index, self.layer,
                                         self.next_index)
                        k = 0
                        vmax = "120 km/h"

                    elif tipo == "ES":
                        data = outSpiral2(layer, state, index, self.layer,
                                          self.next_index)
                        k = 0
                        vmax = "120 km/h"

                    elif tipo == "T":
                        data = tangent2(layer, state, index, self.layer,
                                        self.next_index)
                        k = 0
                        vmax = "120 km/h"
                    else:
                        continue

                    if len(self.c.dados) - 1 < i:
                        self.c.dados.append(None)

                    self.c.dados[i] = tipo, data

            else:
                for tipo, index, state in self.c.readData():
                    i += 1
                    if tipo == "C":
                        data = circleArc(layer, state, index, self.layer,
                                         self.next_index, self.current_index)
                        k = 0
                        vmax = "120 km/h"

                    elif tipo == "EC":
                        data = polyTransCircle(layer, state, index, self.layer,
                                               self.next_index,
                                               self.current_index)
                        k = 0
                        vmax = "120 km/h"

                    elif tipo == "EE":
                        data = inSpiral(layer, state, index, self.layer,
                                        self.next_index)
                        k = 0
                        vmax = "120 km/h"

                    elif tipo == "ES":
                        data = outSpiral(layer, state, index, self.layer,
                                         self.next_index)
                        k = 0
                        vmax = "120 km/h"

                    elif tipo == "T":
                        data = tangent(layer, state, index, self.layer,
                                       self.next_index)
                        k = 0
                        vmax = "120 km/h"
                    else:
                        continue

                    if len(self.c.dados) - 1 < i:
                        self.c.dados.append(None)

                    self.c.dados[i] = tipo, data

        except Exception as e:
            messageDialog(title="Erro",
                          message="Não foi possível definir a geometria",
                          info="Provavelmente houve a interseção de curvas")
            msgLog(str(traceback.format_exception(None, e, e.__traceback__)))
            self.curvaFailed = True

        refreshCanvas(self.iface, layer)

        #TODO compute vmax and k

        if self.c.lastWidget and data:
            self.c.lastWidget.fill(data, k=k, vmax=vmax)