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])
 def dup_layer(self, crs, names):
     for name in names:
         layer = uf.getLegendLayerByName(self.iface, "POI_Evacu8")
         layer_type = {'0': 'Point', '1': 'LineString', '2': 'Polygon'}
         mem_layer = QgsVectorLayer(
             layer_type[str(layer.geometryType())] + "?crs=epsg:" +
             str(crs), name, "memory")
         feats = [feat for feat in layer.getFeatures()]
         mem_layer_data = mem_layer.dataProvider()
         attr = layer.dataProvider().fields().toList()
         mem_layer_data.addAttributes(attr)
         mem_layer.updateFields()
         mem_layer_data.addFeatures(feats)
         QgsMapLayerRegistry.instance().addMapLayer(mem_layer)
Пример #3
0
def getArchaelogicalLayer():
    testfile_dir = os.path.join(tm_dir(), testcfg.TEST_DATA_DIR)
    fn = os.path.join(testfile_dir, "archaelogical.txt")
    uri = "{}?type=csv&xField={}&yField={}&spatialIndex=no&subsetIndex=no&watchFile=no" \
          "".format(fn, "lon", "lat")
    layer = QgsVectorLayer(uri, "ancient_points", 'delimitedtext')
    return layer
Пример #4
0
    def create_point(self, p1, name):
        layer = QgsVectorLayer('Point?crs=%s' % int(self.crs), name, "memory")
        mycrs = QgsCoordinateReferenceSystem(int(self.crs), 0)
        self.reprojectgeographic = QgsCoordinateTransform(
            self.iface.mapCanvas().mapRenderer().destinationCrs(), mycrs)
        pr = layer.dataProvider()
        point = QgsFeature()
        point.setGeometry(
            QgsGeometry.fromPoint(self.reprojectgeographic.transform(p1)))
        pr.addFeatures([point])
        #layer.setCrs(QgsCoordinateReferenceSystem(int(self.crs), 0))
        layer.updateExtents()

        QgsMapLayerRegistry.instance().addMapLayer(layer)

        return p1
Пример #5
0
    def handle(self, **kwargs):
        self.logger.debug('>>> Handler: 7...')
        __config = load_config()
        params = __config[PLUGIN_CRITICIDADE]

        criticidade_layer = kwargs['criticidade_layer']
        output_vector = kwargs['output_criticidade_vector']

        try:
            save_file(criticidade_layer, output_vector)

            layers = [kwargs['criticidade_layer']]
            remove_layers(layers)

            output_layer = QgsVectorLayer(output_vector, 'criticidade', 'ogr')
            QgsMapLayerRegistry.instance().addMapLayers([output_layer])

            style = params['style']
            set_layer_style(output_layer, PLUGIN_CRITICIDADE,
                            style['criticidade'])

            self.next(**kwargs)

        except Exception as e:
            raise RuntimeError(str(e))
Пример #6
0
def getTweetsLayer():
    tm_dir = os.path.join(QgsApplication.qgisSettingsDirPath(), "python",
                          "plugins", "timemanager")
    testfile_dir = os.path.join(tm_dir, testcfg.TEST_DATA_DIR)
    tweets = QgsVectorLayer(os.path.join(testfile_dir, 'tweets.shp'), 'tweets',
                            'ogr')
    return tweets
Пример #7
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()
Пример #8
0
def createMemLayer(line, breaksList):
    '''
    create memory layer storing all reaches
    :return:
    '''
    # create layer
    vl = QgsVectorLayer("LineString", "sinuosity_river", "memory")
    pr = vl.dataProvider()
    # add fields
    pr.addAttributes([
        QgsField("reach", QVariant.Int),
        QgsField("sinuosity", QVariant.Double),
        QgsField("Length", QVariant.Double)
    ])
    vl.updateFields()
    # create breaks with initial and final
    bk = sorted(breaksList)
    bk.insert(0, 0)
    bk.append(line.length())
    for breack in range(1, len(bk)):
        ptInt = line.interpolate(bk[breack - 1])
        ptFin = line.interpolate(bk[breack])
        reach = splitLine(line, ptInt, ptFin)
        # sinuosity calc
        dist = qgisdist(ptInt, ptFin)
        lenReach = bk[breack] - bk[breack - 1]
        # add a feature
        fet = QgsFeature()
        fet.setGeometry(QgsGeometry.fromPolylineXY(reach))
        fet.setAttributes([breack, lenReach / dist, str(lenReach)])
        pr.addFeatures([fet])
    #vl.updateExtents()
    vl.commitChanges()
    return vl
Пример #9
0
class Create_vlayer(object):
    '''creation of a virtual layer'''
    def __init__(self, nom, type):
        self.type = type
        self.name = nom
        self.layer = QgsVectorLayer(self.type, self.name, "memory")
        self.pr = self.layer.dataProvider()

    def create_point(self, geometry):
        # add point to the layer
        self.seg = QgsFeature()
        self.seg.setGeometry(QgsGeometry.fromPoint(geometry))
        self.pr.addFeatures([self.seg])
        self.layer.updateExtents()

    @property
    def display_layer(self):
        #end of layer and display layer
        QgsProject.instance().addMapLayers([self.layer])
Пример #10
0
    def createLayer(self, mtype, directory=''):
        layerName = ''  # 图层名称
        layerType = ''  # 图层类型
        landus = []  # Symbol分类
        if mtype == LayerType.SITE:
            layerName = u'基站'
            layerType = QGis.WKBPoint
            landus = SiteSymbol
        elif mtype == LayerType.CELL:
            layerName = u'小区'
            layerType = QGis.WKBPolygon
            landus = CellSymbol

        else:
            layerName = u'相邻小区'
            layerType = QGis.WKBLineString
            landus = ServingCellSymbol

        # 删除原有图层文件
        deleteShapefile(directory, layerName)
        shapPath = os.path.join(directory, layerName + u".shp")
        fileds = self.createAttributesByType(mtype)

        # 创建出Shap文件
        # 数据源编码模式为GBK2312(否则中文字段会乱码)
        wr = QgsVectorFileWriter(shapPath, "GBK2312", fileds, layerType, None,
                                 "ESRI Shapefile")
        # 如果保存的时候没有错误
        if wr.hasError() == QgsVectorFileWriter.NoError:
            pass
        else:
            print wr.hasError()
            raise Exception, wr.errorMessage()  # 发生错误,抛出异常交给外面的方法处理异常
        del wr  # 使添加的字段生效

        layer = QgsVectorLayer(shapPath, layerName, 'ogr')

        # 只有当Symbol分类规则不为空时才设置
        if landus != None and len(landus) > 0:

            myLandus = {}
            for i, (color, lab) in landus.items():
                if i == u'移动':
                    myLandus[i] = (self.ydcolor, lab)
                elif i == u'联通':
                    myLandus[i] = (self.ltcolor, lab)
                elif i == u'电信':
                    myLandus[i] = (self.dxcolor, lab)
                else:
                    myLandus[i] = (self.ttcolor, lab)

            self.initSymbol(myLandus, layer, mtype)

        QgsMapLayerRegistry.instance().addMapLayer(layer)
Пример #11
0
    def loadCsvFiles(self):
        # 清除画布上的所有图层
        # QgsMapLayerRegistry.instance().removeAllMapLayers()

        # 图标样式,圆,大小设为1
        # symbol = QgsMarkerSymbolV2.createSimple({'name':'circle', 'size':'1'})

        filepath = self.dlg.lineEdit.text()

        # 获取文件夹中的所有文件,并过滤不是csv格式的文件
        files = os.listdir(filepath)
        for file in files:
            if not os.path.isdir(file) and os.path.splitext(
                    file)[1] == '.csv' and not file.startswith('.'):
                uri = "file:///" + filepath + "/" + file + "?delimiter=%s&crs=epsg:4326&xField=%s&yField=%s" % (
                    ",", "longitude", "latitude")
                vlayer = QgsVectorLayer(uri,
                                        os.path.splitext(file)[0],
                                        "delimitedtext")
                vlayer.rendererV2().symbol().setSize(1.3)
                if vlayer.isValid():
                    QgsMapLayerRegistry.instance().addMapLayer(vlayer)
Пример #12
0
    def run(self):
        QgsMessageLog.logMessage(f'Started task {self.description()}',
                                 'TracingCAJ', Qgis.Info)

        epsg = self.__hidrometers.crs().postgisSrid()
        uri = "LineString?crs=epsg:" + str(
            epsg
        ) + "&field=id:integer" "&field=distance:double(20,2)&index=yes"
        dist = QgsVectorLayer(uri, 'dist', 'memory')

        QgsProject.instance().addMapLayer(dist)
        prov = dist.dataProvider()
        points_features = [
            point_feature
            for point_feature in self.__hidrometers.getFeatures()
        ]

        feats = []
        if len(points_features) > 0:
            for p in points_features:
                nearest_pipe = self.find_nearest_pipelines(p.geometry())
                try:
                    minDistPoint = nearest_pipe.closestSegmentWithContext(
                        p.geometry().asPoint())[1]
                    feat = QgsFeature()
                    feat.setGeometry(
                        QgsGeometry.fromPolylineXY(
                            [p.geometry().asPoint(), minDistPoint]))
                    feat.setAttributes(
                        [points_features.index(p),
                         feat.geometry().length()])
                    feats.append(feat)
                except Exception as e:
                    print(p.id())

        prov.addFeatures(feats)
    def select(self, point):
        layers = ["Buildings to evacuate", "Shelters"]

        min_dist = QgsDistanceArea()
        min_layer = QgsVectorLayer()
        for layer in layers:
            vl = uf.getLegendLayerByName(self.iface, layer)

            feats = vl.getFeatures()
            for feat in feats:
                geom = feat.geometry()
                pt = geom.asPoint()
                dist = QgsDistanceArea().measureLine(point, pt)
                if dist < min_dist:
                    min_dist = dist
                    min_feat = feat
                    min_id = feat.id()
                    min_layer = vl

        min_layer.select(min_id)
        self.canvas.setSelectionColor(QColor("red"))
        self.canvas.refresh()

        return min_layer, min_feat
Пример #14
0
    def exit_dialog(self, points, crs):
        self.dialog.close()

        layer = QgsVectorLayer('LineString', self.name_tracado, "memory")
        pr = layer.dataProvider()
        print points
        anterior = QgsPoint(points[0])
        fets = []
        for p in points[1:]:
            fet = QgsFeature(layer.pendingFields())
            fet.setGeometry(QgsGeometry.fromPolyline([anterior, QgsPoint(p)]))
            fets.append(fet)
            anterior = QgsPoint(p)
        pr.addFeatures(fets)
        self.crs = crs
        layer.setCrs(QgsCoordinateReferenceSystem(int(crs), 0))
        layer.updateExtents()

        QgsMapLayerRegistry.instance().addMapLayer(layer)
Пример #15
0
    def plotar(self):
        vl = QgsVectorLayer("Point", "temporary_points", "memory")
        pr = vl.dataProvider()

        # Enter editing mode
        vl.startEditing()

        # add fields
        pr.addAttributes([
            QgsField("estaca", QVariant.String),
            QgsField("descrição", QVariant.String),
            QgsField("north", QVariant.String),
            QgsField("este", QVariant.String),
            QgsField("cota", QVariant.String),
            QgsField("azimite", QVariant.String)
        ])
        fets = []

        for r in range(self.tableWidget.rowCount()):
            ident = self.tableWidget.item(r, 0).text()
            if ident in ["", None]: break
            fet = QgsFeature(vl.pendingFields())
            n = 0.0
            e = 0.0
            try:
                es = self.tableWidget.item(r, 0).text()
                d = self.tableWidget.item(r, 1).text()
                n = float(self.tableWidget.item(r, 3).text())
                e = float(self.tableWidget.item(r, 4).text())
                c = float(self.tableWidget.item(r, 5).text())
                a = self.tableWidget.item(r, 6).text()
            except:
                break
            fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(e, n)))
            fet.setAttributes([es, d, n, e, c, a])
            fets.append(fet)
        pr.addFeatures(fets)
        vl.commitChanges()
        QgsMapLayerRegistry.instance().addMapLayer(vl)
Пример #16
0
    def setResultLayer(self, result_list):
        layerName = u'规划基站结果'
        layerType = QGis.WKBPoint
        project_dir = getProjectDir(self.iface)
        # 先判断是否已存在规划基站结果图层
        result_layer = getLayerByName(layerName, self.iface)
        if result_layer:
            #清空数据
            delAllFeatures(result_layer)
        else:
            # 删除原有图层文件
            deleteShapefile(project_dir, layerName)
            shapPath = os.path.join(project_dir, layerName + u".shp")
            # 生成图层
            fileds = self.createFields()
            # 创建出Shap文件
            # 数据源编码模式为GBK2312(否则中文字段会乱码)
            wr = QgsVectorFileWriter(shapPath, "GBK2312", fileds, layerType, None, "ESRI Shapefile")
            # 如果保存的时候没有错误
            if wr.hasError() == QgsVectorFileWriter.NoError:
                pass
            else:
                print wr.hasError()
                raise Exception, wr.errorMessage()  # 发生错误,抛出异常交给外面的方法处理异常
            del wr  # 使添加的字段生效

            result_layer = QgsVectorLayer(shapPath, layerName, 'ogr')
            QgsMapLayerRegistry.instance().addMapLayer(result_layer)

        # 添加数据
        features_list = []
        for result in result_list:
            feature = createABasicPointFeature(QgsPoint(float(result[1]),float(result[2])), result)
            features_list.append(feature)
        importFeaturesToLayer(result_layer, features_list)
        # 合并站点
        mergeNSite = OptimizateNewSite(result_layer, self.parent)
        if mergeNSite.run():
            QMessageBox.information(self.parent, u"自动规划基站", u"自动规划基站成功!")
        else:
            QMessageBox.critical(self.parent, u"自动规划基站", u"自动规划基站失败!")
Пример #17
0
    def generate_and_load_geopackage_layer(self, gpkg_file, crs=None, type="Point", name="source_indicators",
                                           fields=dict(name="unit_name", type=QVariant.String)):
        vl = QgsVectorLayer(type, name, "memory")

        pr = vl.dataProvider()

        for field in fields:
            pr.addAttributes([QgsField(field[0], field[1])])
        vl.updateFields()
        if crs is not None:
            vl.setCrs(crs)

        from mappy.mappy_utils import write_layer_to_gpkg2, add_layer_from_geopackage

        write_layer_to_gpkg2(vl, gpkg_file, name)

        # vector_file = vector_file.as_posix() + f"|layername={vl.name()}"
        # print(vector_file)
        # l = QgsVectorLayer(vector_file)
        # l.setName(vl.name())

        l = add_layer_from_geopackage(gpkg_file, name)

        return l
    def __init__(self, parent=None):
        """Constructor."""
        super(Evacu8DockWidget, self).__init__(parent)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)

        #define globals
        self.iface = iface
        self.canvas = self.iface.mapCanvas()
        self.plugin_dir = os.path.dirname(__file__)
        self.emitPoint = QgsMapToolEmitPoint(self.canvas)
        self.toolPoly = PolyMapTool(self.canvas)
        self.emitEvac = QgsMapToolEmitPoint(self.canvas)
        self.emitShel = QgsMapToolEmitPoint(self.canvas)
        self.emitDel = QgsMapToolEmitPoint(self.canvas)
        self.input_template = self.scen_info.toHtml()

        # set up GUI operation signals
        # data
        self.load_scen.clicked.connect(self.openScenario)
        self.tabs.setTabEnabled(1, False)
        self.set_pt.clicked.connect(self.enterPoi)
        self.emitPoint.canvasClicked.connect(self.getPoint)
        self.set_rad.clicked.connect(self.calculateBuffer)
        self.set_rad.setEnabled(False)
        self.send_notes.clicked.connect(self.sendNotes)
        self.set_danger.clicked.connect(self.setDangerZone)
        self.get_danger.clicked.connect(self.getDangerZone)
        self.del_danger.clicked.connect(self.delDangerZone)
        self.emitDel.canvasClicked.connect(self.get_del)

        # set images and icons
        self.logo.setPixmap(QtGui.QPixmap(':images/Logosmall.jpeg'))
        self.load_scen.setIcon(QtGui.QIcon(':images/Open.png'))
        self.load_scen.setIconSize(QSize(25, 25))
        self.set_danger.setIcon(QtGui.QIcon(':images/Draw1.svg'))
        self.set_danger.setIconSize(QSize(25, 25))
        self.get_danger.setIcon(QtGui.QIcon(':images/Check.png'))
        self.get_danger.setIconSize(QSize(25, 25))
        self.del_danger.setIcon(QtGui.QIcon(':images/Delete.png'))
        self.del_danger.setIconSize(QSize(30, 30))
        self.shortestRouteButton.setIcon(QtGui.QIcon(':images/Route.png'))
        self.shortestRouteButton.setIconSize(QSize(25, 25))
        self.to_wiki1.setIcon(QtGui.QIcon(':images/Info.png'))
        self.to_wiki1.setIconSize(QSize(20, 20))

        # analysis
        self.evac = QgsPoint()
        self.evacId = int()
        self.shel = QgsPoint()
        self.shelId = int()

        self.evac_layer = QgsVectorLayer()
        self.evac_feat = QgsFeature()
        self.shel_layer = QgsVectorLayer()
        self.shel_feat = QgsFeature()

        self.select_POI.clicked.connect(self.enterEvac)
        self.emitEvac.canvasClicked.connect(self.getEvac)
        self.desel_POI.clicked.connect(self.deleteEvac)
        self.select_shelter.setEnabled(False)
        self.select_shelter.clicked.connect(self.enterShel)
        self.emitShel.canvasClicked.connect(self.getShel)
        self.shortestRouteButton.setEnabled(False)
        self.shortestRouteButton.clicked.connect(self.buildNetwork)
        self.shortestRouteButton.clicked.connect(self.calculateRoute)
        self.network_layer = QgsVectorLayer()
        self.tied_points = []
        self.to_evac_info.setVerticalHeaderLabels(
            ["Type", "Name", "Address", "Population", "Dist from Attack(m)"])
        self.shelter_info.setVerticalHeaderLabels(
            ["Type", "Name", "Address", "Capacity", "Route distance (m)"])

        # Open wiki
        self.to_wiki1.clicked.connect(self.open_wiki)

        self.big_button.clicked.connect(self.evacuateThis)
        self.savelog.clicked.connect(self.saveLog)

        self.big_button.setEnabled(False)
        self.warning_msg.setVisible(False)

        self.show_selected.clicked.connect(self.showSelected)
        self.hide_selected.clicked.connect(self.hideSelected)
        self.save_map.pressed.connect(self.showSelected)
        self.save_map.released.connect(self.saveMap)

        self.savelog.clicked.connect(self.timerMessage)
        self.save_map.released.connect(self.timerMessage)
        self.saved_msg.setVisible(False)

        self.sent_msg.setVisible(False)
    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()
Пример #20
0
    def on_webViewProcessingStatus_loadFinished(self):
        """Task done"""
        QgsMessageLog.logMessage('Load results')
        self.dlg.statusBarProcessing2.setValue(60)
        xmlCropRowsResultsProcessing = (os.path.join(
            self.dlg.inputSharedFolderPath.text(), 'results',
            ('results_' + self.dlg.xmlCoreFile.text())))
        #check if result file exists
        QgsMessageLog.logMessage('XML Result File: ' +
                                 str(xmlCropRowsResultsProcessing))
        QgsMessageLog.logMessage('results_' + self.dlg.xmlCoreFile.text())
        self.dlg.statusBarProcessing2.setValue(65)

        if (os.path.exists(xmlCropRowsResultsProcessing) == False):
            #print("No croprows result file found !")
            QgsMessageLog.logMessage('No croprows result file found !')
        else:
            source = open(xmlCropRowsResultsProcessing, 'rb')
            tree = ET.parse(source)
            root = tree.getroot()
            for filexml in root.findall('filename'):
                resultVectorialFile = filexml.find('result').text
                resultVectorialBufferFile = filexml.find('buffer').text
                #print(resultVectorialFile)
                QgsMessageLog.logMessage(str(resultVectorialFile))
                QgsMessageLog.logMessage(str(resultVectorialBufferFile))
                resultTileFile = filexml.find('tile').text
                #print(resultTileFile)
                QgsMessageLog.logMessage(str(resultTileFile))
                self.dlg.statusBarProcessing2.setValue(60)
                #load result into qgis
                temporalPath = self.dlg.inputSharedFolderPath.text().replace(
                    "/", "\\")
                outputFileMaskPath = os.path.join(temporalPath, "results",
                                                  resultVectorialFile)
                outputFileMaskBufferPath = os.path.join(
                    temporalPath, "results", resultVectorialBufferFile)

                maskVectorLayerExported = QgsVectorLayer(
                    outputFileMaskPath, "croprows_lines", "ogr")
                maskVectorLayerBufferExported = QgsVectorLayer(
                    outputFileMaskBufferPath, "croprows_lines_buffer", "ogr")
                self.dlg.statusBarProcessing2.setValue(70)
                #style for croprows lines result shapefile
                styleCropRows = os.path.join(
                    (os.path.dirname(os.path.abspath(__file__))), 'styles',
                    'croprows_style_croplines.qml')
                maskVectorLayerExported.loadNamedStyle(styleCropRows)
                #QgsMapLayerRegistry.instance().addMapLayer(maskVectorLayerExported)
                QgsProject.instance().addMapLayer(maskVectorLayerExported)
                self.dlg.statusBarProcessing2.setValue(80)

                #style for buffer croprows lines result shapefile
                styleCropRowsBuf = os.path.join(
                    (os.path.dirname(os.path.abspath(__file__))), 'styles',
                    'croprows_style_buffer.qml')
                maskVectorLayerBufferExported.loadNamedStyle(styleCropRowsBuf)
                #QgsMapLayerRegistry.instance().addMapLayer(maskVectorLayerBufferExported)
                QgsProject.instance().addMapLayer(
                    maskVectorLayerBufferExported)
                self.dlg.statusBarProcessing2.setValue(85)

                outputFileTilePath = os.path.join(temporalPath, "results",
                                                  resultTileFile)
                maskVectorLayerTileExported = QgsVectorLayer(
                    outputFileTilePath, "croprows_tiles", "ogr")
                self.dlg.statusBarProcessing2.setValue(90)
                #style for croprows tiles geojson
                styleTiles = os.path.join(
                    (os.path.dirname(os.path.abspath(__file__))), 'styles',
                    'croprows_style_tileindex.qml')
                maskVectorLayerTileExported.loadNamedStyle(styleTiles)
                #QgsMapLayerRegistry.instance().addMapLayer(maskVectorLayerTileExported)
                QgsProject.instance().addMapLayer(maskVectorLayerTileExported)

                self.dlg.outputfilename.setText(str(outputFileMaskPath))
            self.dlg.statusBarProcessing2.setValue(100)
            source.close()
            del source
        QApplication.setOverrideCursor(QtCore.Qt.ArrowCursor)
        QMessageBox.information(
            None, 'Message !',
            "Crop Rows Generation Done !<br><b>Check Crop Rows Results ! <b/>",
            QMessageBox.Ok)
        self.dlg.close()
        reloadPlugin('PACropRows')
class Evacu8DockWidget(QtGui.QDockWidget, FORM_CLASS):

    closingPlugin = pyqtSignal()

    def __init__(self, parent=None):
        """Constructor."""
        super(Evacu8DockWidget, self).__init__(parent)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)

        #define globals
        self.iface = iface
        self.canvas = self.iface.mapCanvas()
        self.plugin_dir = os.path.dirname(__file__)
        self.emitPoint = QgsMapToolEmitPoint(self.canvas)
        self.toolPoly = PolyMapTool(self.canvas)
        self.emitEvac = QgsMapToolEmitPoint(self.canvas)
        self.emitShel = QgsMapToolEmitPoint(self.canvas)
        self.emitDel = QgsMapToolEmitPoint(self.canvas)
        self.input_template = self.scen_info.toHtml()

        # set up GUI operation signals
        # data
        self.load_scen.clicked.connect(self.openScenario)
        self.tabs.setTabEnabled(1, False)
        self.set_pt.clicked.connect(self.enterPoi)
        self.emitPoint.canvasClicked.connect(self.getPoint)
        self.set_rad.clicked.connect(self.calculateBuffer)
        self.set_rad.setEnabled(False)
        self.send_notes.clicked.connect(self.sendNotes)
        self.set_danger.clicked.connect(self.setDangerZone)
        self.get_danger.clicked.connect(self.getDangerZone)
        self.del_danger.clicked.connect(self.delDangerZone)
        self.emitDel.canvasClicked.connect(self.get_del)

        # set images and icons
        self.logo.setPixmap(QtGui.QPixmap(':images/Logosmall.jpeg'))
        self.load_scen.setIcon(QtGui.QIcon(':images/Open.png'))
        self.load_scen.setIconSize(QSize(25, 25))
        self.set_danger.setIcon(QtGui.QIcon(':images/Draw1.svg'))
        self.set_danger.setIconSize(QSize(25, 25))
        self.get_danger.setIcon(QtGui.QIcon(':images/Check.png'))
        self.get_danger.setIconSize(QSize(25, 25))
        self.del_danger.setIcon(QtGui.QIcon(':images/Delete.png'))
        self.del_danger.setIconSize(QSize(30, 30))
        self.shortestRouteButton.setIcon(QtGui.QIcon(':images/Route.png'))
        self.shortestRouteButton.setIconSize(QSize(25, 25))
        self.to_wiki1.setIcon(QtGui.QIcon(':images/Info.png'))
        self.to_wiki1.setIconSize(QSize(20, 20))

        # analysis
        self.evac = QgsPoint()
        self.evacId = int()
        self.shel = QgsPoint()
        self.shelId = int()

        self.evac_layer = QgsVectorLayer()
        self.evac_feat = QgsFeature()
        self.shel_layer = QgsVectorLayer()
        self.shel_feat = QgsFeature()

        self.select_POI.clicked.connect(self.enterEvac)
        self.emitEvac.canvasClicked.connect(self.getEvac)
        self.desel_POI.clicked.connect(self.deleteEvac)
        self.select_shelter.setEnabled(False)
        self.select_shelter.clicked.connect(self.enterShel)
        self.emitShel.canvasClicked.connect(self.getShel)
        self.shortestRouteButton.setEnabled(False)
        self.shortestRouteButton.clicked.connect(self.buildNetwork)
        self.shortestRouteButton.clicked.connect(self.calculateRoute)
        self.network_layer = QgsVectorLayer()
        self.tied_points = []
        self.to_evac_info.setVerticalHeaderLabels(
            ["Type", "Name", "Address", "Population", "Dist from Attack(m)"])
        self.shelter_info.setVerticalHeaderLabels(
            ["Type", "Name", "Address", "Capacity", "Route distance (m)"])

        # Open wiki
        self.to_wiki1.clicked.connect(self.open_wiki)

        self.big_button.clicked.connect(self.evacuateThis)
        self.savelog.clicked.connect(self.saveLog)

        self.big_button.setEnabled(False)
        self.warning_msg.setVisible(False)

        self.show_selected.clicked.connect(self.showSelected)
        self.hide_selected.clicked.connect(self.hideSelected)
        self.save_map.pressed.connect(self.showSelected)
        self.save_map.released.connect(self.saveMap)

        self.savelog.clicked.connect(self.timerMessage)
        self.save_map.released.connect(self.timerMessage)
        self.saved_msg.setVisible(False)

        self.sent_msg.setVisible(False)

    def closeEvent(self, event):
        # disconnect interface signal
        self.closingPlugin.emit()
        event.accept()

    ##Functions##

    #Open Scenario
    def openScenario(self, filename=""):
        self.iface.addProject(
            unicode(self.plugin_dir + "/data/Evacu8_dataset_new.qgs"))
        self.set_rad.setEnabled(False)
        self.tabs.setTabEnabled(1, False)
        self.scen_info.clear()
        self.scen_info.insertHtml(self.input_template)
        self.buildings.clear()
        self.log.clear()

    # Attack Point
    def enterPoi(self):
        if not (QgsMapLayerRegistry.instance().mapLayersByName('Attack Point')
                ):
            # remember currently selected tool
            self.userTool = self.canvas.mapTool()
            # activate coordinate capture tool
            self.canvas.setMapTool(self.emitPoint)

    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])

    # Add distance from point to Attack Point as attribute
    def distance(self):
        layers = ["POI_Evacu8"]
        for layer in layers:
            vl = uf.getLegendLayerByName(self.iface, layer)
            uf.addFields(vl, ['distance'], [QVariant.Double])
            index = vl.fieldNameIndex('distance')

            feats = vl.getFeatures()
            dist = QgsDistanceArea()
            vl.startEditing()
            for feat in feats:
                geom = feat.geometry()
                pt = geom.asPoint()
                m = dist.measureLine(self.atk_pt, pt) // 1
                vl.changeAttributeValue(feat.id(), index, m)
            vl.commitChanges()

    # Duplicate POI layer
    def dup_layer(self, crs, names):
        for name in names:
            layer = uf.getLegendLayerByName(self.iface, "POI_Evacu8")
            layer_type = {'0': 'Point', '1': 'LineString', '2': 'Polygon'}
            mem_layer = QgsVectorLayer(
                layer_type[str(layer.geometryType())] + "?crs=epsg:" +
                str(crs), name, "memory")
            feats = [feat for feat in layer.getFeatures()]
            mem_layer_data = mem_layer.dataProvider()
            attr = layer.dataProvider().fields().toList()
            mem_layer_data.addAttributes(attr)
            mem_layer.updateFields()
            mem_layer_data.addFeatures(feats)
            QgsMapLayerRegistry.instance().addMapLayer(mem_layer)

    # Load style
    def load_style(self, names, styles):
        for name, style in zip(names, styles):
            layer = uf.getLegendLayerByName(self.iface, name)
            qml_path = self.plugin_dir + "/data/" + style
            layer.loadNamedStyle(qml_path)
            layer.triggerRepaint()

    # Select and delete
    def intersectANDdelete(self):
        lay1 = uf.getLegendLayerByName(self.iface, "Perimeter")
        lay2 = uf.getLegendLayerByName(self.iface, "Shelters")
        lay3 = uf.getLegendLayerByName(self.iface, "Buildings to evacuate")
        if lay1 and lay2:
            to_delete = uf.getFeaturesByIntersection(lay2, lay1, True)

            lay2.startEditing()
            for feat in to_delete:
                lay2.deleteFeature(feat.id())
            lay2.commitChanges()

        if lay1 and lay3:
            to_delete2 = uf.getFeaturesByIntersection(lay3, lay1, False)

            lay3.startEditing()
            for feat in to_delete2:
                lay3.deleteFeature(feat.id())
            lay3.commitChanges()

    # Get inserted buffer
    def getBufferCutoff(self):
        buffer = self.buff_area.text()
        if uf.isNumeric(buffer):
            return uf.convertNumeric(buffer)
        else:
            return 0

    # Make buffer layer
    def calculateBuffer(self):
        layer = uf.getLegendLayerByName(self.iface, "Attack Point")
        origins = layer.getFeatures()
        if origins > 0:
            cutoff_distance = self.getBufferCutoff()
            if cutoff_distance:
                if (QgsMapLayerRegistry.instance().mapLayersByName("Perimeter")
                    ):
                    buffer_layer = uf.getLegendLayerByName(
                        self.iface, "Perimeter")
                    QgsMapLayerRegistry.instance().removeMapLayer(
                        buffer_layer.id())
                buffers = {}
                for point in origins:
                    geom = point.geometry()
                    buffers[point.id()] = geom.buffer(cutoff_distance,
                                                      12).asPolygon()
                # store the buffer results in temporary layer called "Perimeter"
                buffer_layer = uf.getLegendLayerByName(self.iface, "Perimeter")
                # Create one if it doesn't exist
                if not buffer_layer:
                    attribs = ['id', 'distance']
                    types = [QtCore.QVariant.String, QtCore.QVariant.Double]
                    buffer_layer = uf.createTempLayer(
                        'Perimeter', 'POLYGON',
                        layer.crs().postgisSrid(), attribs, types, 70)
                    uf.loadTempLayer(buffer_layer)
                    buffer_layer.setLayerName('Perimeter')
                    symbols = buffer_layer.rendererV2().symbols()
                    symbol = symbols[0]
                    symbol.setColor(QColor.fromRgb(220, 220, 0))
                # Insert buffer polygons
                geoms = []
                values = []
                for buffer in buffers.iteritems():
                    # Each buffer has an id and a geometry
                    geoms.append(buffer[1])
                    # In the case of values, it expects a list of multiple values in each item - list of lists
                    values.append([buffer[0], cutoff_distance])
                uf.insertTempFeatures(buffer_layer, geoms, values)
                self.refreshCanvas(buffer_layer)

                extent = buffer_layer.extent()
                self.canvas.setExtent(extent)

                layers = ["road_net"]
                for layer in layers:
                    vl = uf.getLegendLayerByName(self.iface, layer)
                    iface.legendInterface().setLayerVisible(vl, True)

                # Make half transparent Open Street Map
                rlayer = uf.getLegendLayerByName(self.iface, "OpenStreetMap")
                rlayer.renderer().setOpacity(0.5)  # 0.5 = 50%; 0.1 = 90%...
                rlayer.triggerRepaint()

                # Jump to tab 2
                self.tabs.setTabEnabled(1, True)
                self.tabs.setCurrentIndex(1)
                self.scrollArea.verticalScrollBar().setValue(0)

                # If POIs in and out already exist, remove them
                check_layer = uf.getLegendLayerByName(self.iface,
                                                      "Buildings to evacuate")
                check_layer2 = uf.getLegendLayerByName(self.iface, "Shelters")
                if check_layer:
                    QgsMapLayerRegistry.instance().removeMapLayer(
                        check_layer.id())
                    QgsMapLayerRegistry.instance().removeMapLayer(
                        check_layer2.id())
                    self.buildings.clear()
                if buffer_layer:
                    names = ["Buildings to evacuate", "Shelters"]
                    styles = ["style.qml", "style2.qml"]
                    self.dup_layer(28992, names)
                    self.load_style(names, styles)
                    self.intersectANDdelete()

                    build = uf.getLegendLayerByName(iface,
                                                    "Buildings to evacuate")
                    feats = build.getFeatures()
                    n = 0
                    for feat in feats:
                        if feat.attributes(
                        )[2] != 'police' and feat.attributes(
                        )[2] != 'fire_station':
                            n += 1
                    self.buildings.append('%s' % n)

    # Making notes and sending to livechat
    def getNotes(self):
        notes = self.scen_info.toHtml()
        return notes

    def sendNotes(self):
        input_data = self.getNotes()
        if len(input_data) == 1042:
            return
        time = strftime("%d-%m-%Y %H:%M:%S", localtime())
        new_notes = time + ": " + input_data + "\n"
        old_notes = self.live_chat.toHtml()
        self.live_chat.clear()
        self.live_chat.insertHtml(new_notes)
        self.live_chat.append("\n")
        self.live_chat.insertHtml(old_notes)
        self.live_chat.moveCursor(QtGui.QTextCursor.Start)

    # Set danger polygon
    def setDangerZone(self):
        self.canvas.setMapTool(self.toolPoly)

    def getDangerZone(self):
        self.canvas.unsetMapTool(self.toolPoly)

    def delDangerZone(self):
        self.canvas.unsetMapTool(self.toolPoly)
        self.canvas.setMapTool(self.emitDel)

    def get_del(self, delete):
        self.canvas.unsetMapTool(self.emitDel)

        if delete:
            layer = "Danger Zones"

            min_dist = QgsDistanceArea()
            vl = uf.getLegendLayerByName(self.iface, layer)
            point = QgsPoint(delete)
            feats = vl.getFeatures()
            for feat in feats:
                geom = feat.geometry()
                pt = geom.centroid().asPoint()
                dist = QgsDistanceArea().measureLine(point, pt)
                if dist < min_dist:
                    min_dist = dist
                    fid = feat.id()

            vl.startEditing()
            vl.deleteFeature(fid)
            vl.commitChanges()

    # Picking to_evac buildings and shelters
    def enterEvac(self):
        self.canvas.setMapTool(self.emitEvac)

    def getEvac(self, evac):
        self.canvas.unsetMapTool(self.emitEvac)
        self.select_POI.setEnabled(False)
        self.select_shelter.setEnabled(True)

        if evac:
            self.evac = QgsPoint(evac)
            self.evac_layer, self.evac_feat = self.select(self.evac)
            self.to_evac_table()

    def select(self, point):
        layers = ["Buildings to evacuate", "Shelters"]

        min_dist = QgsDistanceArea()
        min_layer = QgsVectorLayer()
        for layer in layers:
            vl = uf.getLegendLayerByName(self.iface, layer)

            feats = vl.getFeatures()
            for feat in feats:
                geom = feat.geometry()
                pt = geom.asPoint()
                dist = QgsDistanceArea().measureLine(point, pt)
                if dist < min_dist:
                    min_dist = dist
                    min_feat = feat
                    min_id = feat.id()
                    min_layer = vl

        min_layer.select(min_id)
        self.canvas.setSelectionColor(QColor("red"))
        self.canvas.refresh()

        return min_layer, min_feat

    def enterShel(self):
        self.shortestRouteButton.setEnabled(False)
        routes_layer = uf.getLegendLayerByName(self.iface, "Routes")
        if routes_layer:
            QgsMapLayerRegistry.instance().removeMapLayer(routes_layer.id())
        if self.shel_layer:
            self.shel_layer.deselect(self.shel_feat.id())
        lineLayer = uf.getLegendLayerByName(iface, "road_net")
        lineLayer.deselect(self.shelId)
        self.canvas.setMapTool(self.emitShel)

    def getShel(self, shel):
        self.canvas.unsetMapTool(self.emitShel)

        if shel:
            self.shel = QgsPoint(shel)
            self.shel_layer, self.shel_feat = self.select(self.shel)
            self.shelter_table()
        if self.evac and self.shel:
            self.shortestRouteButton.setEnabled(True)

    # Clear selection of to_evac and shelters
    def deleteEvac(self):
        routes_layer = uf.getLegendLayerByName(self.iface, "Routes")
        if routes_layer:
            QgsMapLayerRegistry.instance().removeMapLayer(routes_layer.id())
        lineLayer = uf.getLegendLayerByName(iface, "road_net")
        lineLayer.removeSelection()

        layers = ["Buildings to evacuate", "Shelters"]
        for layer in layers:
            uf.getLegendLayerByName(self.iface, layer).removeSelection()
        self.refreshCanvas(lineLayer)

        item = ''
        for i in range(5):
            # i is the table row, items must be added as QTableWidgetItems
            self.to_evac_info.setItem(i, 0,
                                      QtGui.QTableWidgetItem(unicode(item)))
            self.shelter_info.setItem(i, 0,
                                      QtGui.QTableWidgetItem(unicode(item)))

        self.select_POI.setEnabled(True)
        self.select_shelter.setEnabled(False)
        self.shortestRouteButton.setEnabled(False)
        self.warning_msg.setVisible(False)
        self.big_button.setEnabled(False)

    # Route functions
    def getNetwork(self):
        roads_layer = uf.getLegendLayerByName(self.iface, "road_net")
        if roads_layer:
            # see if there is an obstacles layer to subtract roads from the network
            obstacles_layer = uf.getLegendLayerByName(self.iface,
                                                      "Danger Zones")
            if obstacles_layer:
                # retrieve roads outside obstacles (inside = False)
                features = uf.getFeaturesByIntersection(
                    roads_layer, obstacles_layer, False)
                # add these roads to a new temporary layer
                road_network = uf.createTempLayer(
                    'Temp_Network', 'LINESTRING',
                    roads_layer.crs().postgisSrid(), [], [])
                road_network.dataProvider().addFeatures(features)
            else:
                road_network = roads_layer
            return road_network
        else:
            return

    def buildNetwork(self):
        self.network_layer = self.getNetwork()
        if self.network_layer:
            # get the points to be used as origin and destination
            # in this case gets the centroid of the selected features
            selected_sources = uf.getLegendLayerByName(
                self.iface, "road_net").selectedFeatures()
            source_points = [self.evac, self.shel]
            # build the graph including these points
            if len(source_points) > 1:
                self.graph, self.tied_points = uf.makeUndirectedGraph(
                    self.network_layer, source_points)
                # the tied points are the new source_points on the graph
                if self.graph and self.tied_points:
                    text = "network is built for %s points" % len(
                        self.tied_points)

        return

    def calculateRoute(self):
        # origin and destination must be in the set of tied_points
        options = len(self.tied_points)
        if options > 1:
            # origin and destination are given as an index in the tied_points list
            origin = 0
            destination = random.randint(1, options - 1)
            # calculate the shortest path for the given origin and destination
            path = uf.calculateRouteDijkstra(self.graph, self.tied_points,
                                             origin, destination)
            # store the route results in temporary layer called "Routes"
            routes_layer = uf.getLegendLayerByName(self.iface, "Routes")
            # create one if it doesn't exist
            if not routes_layer:
                attribs = ['id']
                types = [QtCore.QVariant.String]
                routes_layer = uf.createTempLayer(
                    'Routes', 'LINESTRING',
                    self.network_layer.crs().postgisSrid(), attribs, types)

                style = "style_red_routes.qml"
                qml_path = self.plugin_dir + "/data/" + style
                routes_layer.loadNamedStyle(qml_path)
                routes_layer.triggerRepaint()

                uf.loadTempLayer(routes_layer)
            # calculate route length
            d = 0
            for i in range(len(path) - 1):
                pt1 = path[i]
                pt2 = path[i + 1]
                dx = pt2[0] - pt1[0]
                dy = pt2[1] - pt1[1]
                d += ((dx**2 + dy**2)**0.5) // 1
            uf.insertTempFeatures(routes_layer, [path], [['testing']])
            self.refreshCanvas(routes_layer)
            self.shelter_info.setItem(4, 0, QtGui.QTableWidgetItem(unicode(d)))

            lineLayer = uf.getLegendLayerByName(iface, "road_net")
            lineLayer.deselect(self.shelId)
            self.refreshCanvas(lineLayer)
            self.big_button.setEnabled(True)

            # Set ROUTE text color Red
            self.shelter_info.item(4, 0).setTextColor(QColor(255, 0, 0))

    # After adding features to layers, needs a refresh (sometimes)
    def refreshCanvas(self, layer):
        if self.canvas.isCachingEnabled():
            layer.setCacheImage(None)
        else:
            self.canvas.refresh()

    # Displaying POI information
    def to_evac_table(self):
        tent_values = self.evac_feat.attributes()
        indices = [2, 3, 7, 8, 9]
        values = [tent_values[i] for i in indices]
        # takes a list of label / value pairs, can be tuples or lists. not dictionaries to control order
        for i, item in enumerate(values):
            # i is the table row, items must be added as QTableWidgetItems
            self.to_evac_info.setItem(i, 0,
                                      QtGui.QTableWidgetItem(unicode(item)))

    def shelter_table(self):
        tent_values = self.shel_feat.attributes()
        indices = [2, 3, 7, 8]
        values = [tent_values[i] for i in indices]

        # takes a list of label / value pairs, can be tuples or lists. not dictionaries to control order
        for i, item in enumerate(values):
            # i is the table row, items must tbe added as QTableWidgetItems
            self.shelter_info.setItem(i, 0,
                                      QtGui.QTableWidgetItem(unicode(item)))
        cap = values[3]
        pop = int(self.to_evac_info.item(3, 0).text())
        if cap - pop < 0:
            self.warning_msg.setVisible(True)
        else:
            self.warning_msg.setVisible(False)

    # Open the wiki
    def open_wiki(self):
        webbrowser.open(
            'https://github.com/fhb1990/GEO1005_2017-18_group3/wiki/06.-Plugin-manual'
        )

    # Combine toEvacuate building and shelter
    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()

    # Save the log to desktop
    def saveLog(self):
        log_text = self.log.toPlainText()
        # path = 'C:/Users/'+os.getenv('USERNAME')+'/Desktop/Evacu8_log.txt'
        path1 = os.path.join(os.path.expanduser('~'),
                             'Desktop') + '/Evacu8_log.txt'
        print path1
        with open(path1, "w") as fh:
            fh.write("%s" % (log_text))

    # Show all the chosen routes on the map
    def showSelected(self):
        selected = uf.getLegendLayerByName(self.iface, "Selected Routes")
        if selected:
            iface.legendInterface().setLayerVisible(selected, True)

    # Hide all the chosen routes on the map
    def hideSelected(self):
        selected = uf.getLegendLayerByName(self.iface, "Selected Routes")
        if selected:
            iface.legendInterface().setLayerVisible(selected, False)

    # Save the shown canvas to desktop
    def saveMap(self):
        #filename = 'C:/Users/' + os.getenv('USERNAME') + '/Desktop/Evacu8_log.png'
        filename1 = os.path.join(os.path.expanduser('~'),
                                 'Desktop') + '/Evacu8_log.png'
        self.showSelected()
        if filename1 != '':
            self.canvas.saveAsImage(filename1, None, "PNG")

    # Show "saved to desktop" message for 2 seconds
    def timerMessage(self):
        self.saved_msg.setVisible(True)
        QTimer.singleShot(2000, lambda: (self.saved_msg.setVisible(False)))
Пример #22
0
    def painting(self, data, fileType):
        currentInputCRS = self.dlg.inputCRS.text().replace(" ", "")
        table = data.sheets()[0]
        nrows = table.nrows
        if fileType == '4G':
            vl = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"4G基础信息图层", "memory")
            vlLabel = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"4G基础信息标签层", "memory")
        elif fileType == '3G':
            vl = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"3G基础信息图层", "memory")
            vlLabel = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"3G基础信息标签层", "memory")
        elif fileType == '2G':
            vl = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"2G基础信息图层", "memory")
            vlLabel = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"2G基础信息标签层", "memory")

        pr = vl.dataProvider()
        vlLabelPr = vlLabel.dataProvider()

        attrs = self.createAttributesTable(fileType)

        pr.addAttributes(attrs)
        vlLabelPr.addAttributes(attrs)
        vl.updateFields()
        vlLabel.updateFields()

        fet = QgsFeature()
        self.dlg.progressBar.setVisible(True)
        '''开始读取到内存'''
        list = [[] for row in range(nrows-1)]
        for i in range(nrows):
            if i > 0:
                try:
                    if fileType == '4G':
                        for j in range(21):
                             list[i - 1].append(table.cell(i, j).value)
                             if j == 20:
                                 list[i - 1].append(table.cell(i, 13).value % 3)
                    if fileType == '3G':
                        for j in range(73):
                             list[i - 1].append(table.cell(i, j).value)
                             if j == 72:
                                 list[i - 1].append(int(table.cell(i, 5).value) % 3)
                    if fileType =='2G':
                        for j in range(67):
                             list[i - 1].append(table.cell(i, j).value)
                             if j == 66:
                                 list[i - 1].append(int(table.cell(i, 2).value) % 3)
                except:
                    self.showErrorDialog(u'文档读取出错', u'文档可能存在错误或格式不符合规范')
                    self.dlg.progressBar.setVisible(False)
                    return
        '''完成读取到内存'''

        PCI_Types = {
            '0': ('#F49ECC', 'Mod3=0'),
            '1': ('#65F0FF', 'Mod3=1'),
            '2': ('#00FF00', 'Mod3=2'),
            '3': ('#000', u'未知值'),
        }
        categories = []
        for pci_type, (color, label) in PCI_Types.items():
            symbol = QgsSymbolV2.defaultSymbol(vl.geometryType())
            # symbol = QgsFillSymbolV2.createSimple({'color': color, 'color_border': color, 'width_border': '2'})
            symbol.setColor(QColor(color))
            # symbol.symbolLayer(0).setOutlineColor(QColor('#75263b'))
            category = QgsRendererCategoryV2(pci_type, symbol, label)
            categories.append(category)

        for i in range(len(list)):
            fetAttrs =[]
            if fileType == '4G':
                for j in range(22):
                    fetAttrs.append(list[i][j])
            elif fileType == '3G':
                for j in range(74):
                    fetAttrs.append(list[i][j])
            elif fileType == '2G':
                for j in range(68):
                    fetAttrs.append(list[i][j])
            fet.setAttributes(fetAttrs)
            if fileType == '4G':
                Longitude = 11
                Latitude = 12
                Azimuth = list[i][14]
            elif fileType == '3G':
                Longitude = 12
                Latitude = 13
                Azimuth = list[i][15]
            elif fileType == '2G':
                Longitude = 15
                Latitude = 16
                Azimuth = list[i][5]

            points = [QgsPoint(list[i][Longitude], list[i][Latitude])]  # start point
            startAngle = -20
            endAngle = 20
            while startAngle <= endAngle:
                # midway points
                points.append(QgsPoint(list[i][Longitude] + 0.001 * math.sin(math.radians(Azimuth + startAngle)),
                                       list[i][Latitude] + 0.001 * math.cos(math.radians(Azimuth + startAngle))))
                startAngle += 2
            points.append(QgsPoint(list[i][Longitude], list[i][Latitude]))  # end point

            # create the renderer and assign it to a layer
            expression = 'Mod3'  # field name
            renderer = QgsCategorizedSymbolRendererV2(expression, categories)
            vl.setRendererV2(renderer)

            fet.setGeometry(QgsGeometry.fromPolygon([points]))
            pr.addFeatures([fet])

            # fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(Longitude, Latitude)))
            vlLabelPr.addFeatures([fet])

            vlLabel.setLayerTransparency(100)

            vl.updateExtents()
            vlLabel.updateExtents()
            vl.commitChanges()
            vlLabel.commitChanges()
            vl.updateFields()
            vlLabel.updateFields()
            if i % 200 == 0:
                print 'progress:', float(pr.featureCount()) / nrows * 100
                self.dlg.progressBar.setValue(float(pr.featureCount()) / nrows * 100.0)

            palyr = QgsPalLayerSettings()
            # palyr.readFromLayer(vl)
            palyr.enabled = True
            palyr.fieldName = 'CellName'
            if fileType =='2G':
                palyr.fieldName = 'CELL_NAME'
            palyr.placement = QgsPalLayerSettings.OverPoint
            # palyr.setDataDefinedProperty(QgsPalLayerSettings.Size,False,False,'','')
            palyr.writeToLayer(vlLabel)
            QgsMapLayerRegistry.instance().addMapLayer(vl)
            QgsMapLayerRegistry.instance().addMapLayer(vlLabel)
        print 'progress:', 100
        self.dlg.progressBar.setValue(0)
        self.dlg.progressBar.setVisible(False)
        self.iface.messageBar().clearWidgets()
        qgis.utils.iface.setActiveLayer(vl)
        self.saveEPSGChange()
        self.dlg.close()
Пример #23
0
    def gsmfsOKBtn(self):

        currentInputCRS = self.dlg.inputCRS.text().replace(" ", "")

        inputFreq = self.gsmfsdlg.inputFreq.text()
        try:
            sourceLayer = QgsMapLayerRegistry.instance().mapLayersByName(u'2G基础信息图层')[0]
        except:
            self.showErrorDialog(u'未找到图层', u'请检查是否已加载“2G基础信息图层”')
            return

        # 隐藏之前的同名图层
        try:
            sameLayer = QgsMapLayerRegistry.instance().mapLayersByName(u'2G图层频点查找')
            for oneLayer in sameLayer:
                qgis.utils.iface.legendInterface().setLayerVisible(oneLayer, False)
        except:
            pass
        gsmfsLayer = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"2G图层频点查找", "memory")
        gsmfsPr = gsmfsLayer.dataProvider()
        gsmfsPr.addAttributes(self.createAttributesTable('2GFreqSearch'))
        gsmfsLayer.updateFields()

        # QgsMapLayerRegistry.instance().addMapLayer(gsmfsLayer)
        qgis.utils.iface.legendInterface().setLayerVisible(sourceLayer, False)
        gsmfsFet = QgsFeature()
        try:
            inputFreq.replace(" ", "")
            B = int(inputFreq)
        except:
            self.showErrorDialog(u'错误的输入', u'请输入数字')
            return
        A = B - 1
        C = B + 1
        PCI_Types = {
            A: ('#FF63F2', u'频点='+ str(A)),
            B: ('#FFFF00', u'指定频点='+ str(B)),
            C: ('#01FF8D', u'频点='+ str(C)),
            '-1': ('#eeeeee', u'无关频点')
        }
        categories = []
        for pci_type, (color, label) in PCI_Types.items():
            symbol = QgsSymbolV2.defaultSymbol(gsmfsLayer.geometryType())
            symbol.setColor(QColor(color))
            category = QgsRendererCategoryV2(pci_type, symbol, label)
            categories.append(category)

        # 创建属性表
        fetAttrs = []
        relatedAttrs = []
        Longitude, Latitude, Azimuth = 15, 16, 5
        for feature in sourceLayer.getFeatures():
            attrs = feature.attributes()
            if (int(inputFreq) == attrs[3]):
                temp = []
                for j in range(67):
                    temp.append(attrs[j])
                temp.append(B)
                relatedAttrs.append(temp)
            elif int(inputFreq) == int(attrs[3]) - 1:
                temp = []
                for j in range(67):
                    temp.append(attrs[j])
                temp.append(A)
                relatedAttrs.append(temp)
            elif int(inputFreq) == int(attrs[3]) + 1:
                temp = []
                for j in range(67):
                    temp.append(attrs[j])
                temp.append(C)
                relatedAttrs.append(temp)
            else:
                temp = []
                for j in range(67):
                    temp.append(attrs[j])
                    if j == 66:
                        if (int(inputFreq) != attrs[3]) & (int(inputFreq) != int(attrs[3])-1) & (int(inputFreq) != int(attrs[3])+1):
                            temp.append('-1')
                fetAttrs.append(temp)
        for one in relatedAttrs:
            fetAttrs.append(one)
        for fetAttr in fetAttrs:
            gsmfsFet.setAttributes(fetAttr)
            #开始画图
            points = [QgsPoint(fetAttr[Longitude], fetAttr[Latitude])]  # start point
            startAngle = -20
            endAngle = 20
            while startAngle <= endAngle:
                points.append(QgsPoint(fetAttr[Longitude] + 0.001 * math.sin(math.radians(fetAttr[Azimuth] + startAngle)),
                                       fetAttr[Latitude] + 0.001 * math.cos(math.radians(fetAttr[Azimuth] + startAngle))))
                startAngle += 2
            points.append(QgsPoint(fetAttr[Longitude], fetAttr[Latitude]))  # end point
            gsmfsFet.setGeometry(QgsGeometry.fromPolygon([points]))
            gsmfsPr.addFeatures([gsmfsFet])
            #根据字段值渲染颜色
            expression = 'Condition'  # field name
            renderer = QgsCategorizedSymbolRendererV2(expression, categories)
            gsmfsLayer.setRendererV2(renderer)

            gsmfsLayer.updateExtents()
            gsmfsLayer.commitChanges()
            gsmfsLayer.updateFields()
            QgsMapLayerRegistry.instance().addMapLayer(gsmfsLayer)
        self.gsmfsdlg.close()
        self.saveEPSGChange()
        self.dlg.close()
Пример #24
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)
Пример #25
0
def getTimeSpansLayer():
    testfile_dir = os.path.join(tm_dir(), testcfg.TEST_DATA_DIR)
    timespans = QgsVectorLayer(os.path.join(testfile_dir, 'timespans.shp'),
                               'timespans', 'ogr')
    return timespans
Пример #26
0
    def carregacarta(self, model):
        # create Qt widget
        canvas = self.iface.mapCanvas()
        #canvas.setCanvasColor(Qt.black)

        # enable this for smooth rendering
        canvas.enableAntiAliasing(True)

        # not updated US6SP10M files from ENC_ROOT
        source_dir = QtGui.QFileDialog.getExistingDirectory(
            None, 'Select a folder:', '', QtGui.QFileDialog.ShowDirsOnly)
        if source_dir in [None, '']: return
        # source_dir = "/home/lucas/python_work/TopoGraph"
        canvas_layers = []
        extent = QgsRectangle()
        extent.setMinimal()

        # load vector layers
        registry = QgsMapLayerRegistry.instance()

        try:
            os.mkdir(r"%s/tmp" % (source_dir))
        except:
            pass

        for files in os.listdir(source_dir):

            # load only the shapefiles
            if files.endswith(".dxf") or files.endswith(
                    ".shp") or files.endswith(".dgn"):
                vlayer = QgsVectorLayer(source_dir + "/" + files, files, "ogr")

                # add layer to the registry
                #registry.addMapLayer(vlayer)
                #extent.combineExtentWith(vlayer.extent())
                #canvas_layers.append(QgsMapCanvasLayer(vlayer))

                writer = QgsVectorFileWriter.writeAsVectorFormat(
                    vlayer, r"%s/tmp/%s.shp" % (source_dir, files), "utf-8",
                    None, "ESRI Shapefile")

                vlayer = QgsVectorLayer(r"%s/tmp/%s.shp" % (source_dir, files),
                                        files, "ogr")

                attr = {}
                vlayerUser = vlayer.crs().toProj4()
                for elem in vlayerUser.strip().split('+'):
                    key_value = elem.strip().split('=')
                    if len(key_value) > 1:
                        attr[key_value[0]] = key_value[1]
                    else:
                        attr[key_value[0]] = None
                attr['units'] = Config.UNITS
                string_proj = ''
                for a in attr:
                    if a == '':
                        continue
                    if attr[a] is None:
                        string_proj += '+%s ' % a
                    else:
                        string_proj += '+%s=%s ' % (a, attr[a])
                crs = QgsCoordinateReferenceSystem()
                crs.createFromProj4(string_proj)
                vlayer.setCrs(crs)
                registry.addMapLayer(vlayer)
                extent.combineExtentWith(vlayer.extent())
                canvas_layers.append(QgsMapCanvasLayer(vlayer))

                print writer
                # set extent to the extent of our layer
                # canvas.setExtent(vlayer.extent())

                # set the map canvas layer set
                # canvas.setLayerSet([QgsMapCanvasLayer(vlayer)])

        canvas.setExtent(extent)
        canvas.setLayerSet(canvas_layers)
Пример #27
0
 def createLayer(self, datas):
     layerName = self.save_layer_name  # 图层名称
     layerType = QGis.WKBPoint  # 图层类型
     shapPath = os.path.join(getProjectDir(self.iface), layerName + u".shp")
     # 创建图层字段
     field_names = [u"名称", u"类别", u"地址", u"经度", u"纬度"]
     field_types = [
         QVariant.String, QVariant.String, QVariant.String, QVariant.Double,
         QVariant.Double
     ]
     field_lengs = [50, 50, 100, 20, 20]
     field_precs = [0, 0, 0, 7, 7]
     fields = QgsFields()
     for (i, itm) in enumerate(field_names):
         cuType = field_types[i]
         if cuType == QVariant.Int:
             mtype = 'Integer'
         elif cuType == QVariant.Double:
             mtype = 'Real'
         else:
             mtype = 'String'
         field = QgsField(itm, cuType, mtype, field_lengs[i],
                          field_precs[i])
         fields.append(field)
     # 创建出Shap文件
     # 数据源编码模式为GBK2312(否则中文字段会乱码)
     wr = QgsVectorFileWriter(shapPath, "GBK2312", fields, layerType, None,
                              "ESRI Shapefile")
     # 如果保存的时候没有错误
     if wr.hasError() == QgsVectorFileWriter.NoError:
         pass
     else:
         print wr.hasError()
         raise Exception, wr.errorMessage()  # 发生错误,抛出异常交给外面的方法处理异常
     del wr  # 使添加的字段生效
     layer = QgsVectorLayer(shapPath, layerName, 'ogr')  # 新生成的搜索结果图层
     QgsMapLayerRegistry.instance().addMapLayer(layer)
     # 更新图层
     self.iface.actionDraw().trigger()
     # 写入数据
     features_list = []
     selected_polygons = []
     for polygon in self.selectedLayer.selectedFeatures():
         selected_polygons.append(polygon)
     for data in datas:
         feature = createABasicPointFeature(
             QgsPoint(float(data[3]), float(data[4])), data)
         point_gemo = feature.geometry()
         if self.searchType == 0:
             for polygon in selected_polygons:
                 if point_gemo.intersects(polygon.geometry()):
                     features_list.append(feature)
                     break
         else:
             features_list.append(feature)
     # 把新建的features导入图层
     result = importFeaturesToLayer(layer, features_list)
     if result:
         # 更新图层
         self.iface.actionDraw().trigger()
         return layer
     else:
         return None
Пример #28
0
                point=QgsPointXY(point_vertex),
                neighbors=4,
                maxDistance=self.__user_distance)
            if len(pipelines_nearest) > 0:
                for pipeline_id in pipelines_nearest:
                    pipeline_geometry = self.__idx_pipelines.geometry(
                        pipeline_id)
                    if pipeline_id not in self.__list_visited_pipelines_ids:
                        self.__q_list_pipelines_ids.append(pipeline_id)
                        self.__q_list_pipelines.append(pipeline_geometry)


if __name__ == '__main__':
    path_to_pipeline_layer = "C:\\Users\\jeferson.machado\\Desktop\\QGIS\\shapes\\rede_agua_tracing.shp"
    path_to_valves_layer = "C:\\Users\\jeferson.machado\\Desktop\\QGIS\\shapes\\registro_manobra.shp"

    pipelines = QgsVectorLayer(path_to_pipeline_layer, "pipelines_tracing",
                               "ogr")
    valves = QgsVectorLayer(path_to_valves_layer, "valves_tracing", "ogr")
    if not pipelines.isValid() or not valves.isValid():
        print("Layer failed to load!")
    else:
        QgsProject.instance().addMapLayer(pipelines)
        QgsProject.instance().addMapLayer(valves)

    pipe_features = QgsProject.instance().mapLayersByName('pipelines_tracing')
    valves_features = QgsProject.instance().mapLayersByName('valves_tracing')

    tracing = TracingPipelines(pipe_features, valves_features, debug=True)
    tracing.run()
Пример #29
0
    def ltefpsOKBtn(self):
        currentInputCRS = self.dlg.inputCRS.text().replace(" ", "")
        try:
            sourceLayer = QgsMapLayerRegistry.instance().mapLayersByName(u'4G基础信息图层')[0]
        except:
            self.showErrorDialog(u'未找到图层', u'请检查是否已加载“4G基础信息图层”')
            return
        try:
            inputFreq = int(self.ltefpsdlg.inputFreq.text())
            inputPCI = int(self.ltefpsdlg.inputPCI.text())
        except:
            self.showErrorDialog(u'错误的输入', u'请输入数字')
            return

        # 隐藏之前的同名图层
        try:
            sameLayers = QgsMapLayerRegistry.instance().mapLayersByName(u'4G图层频点PCI查找')
            for oneLayer in sameLayers:
                qgis.utils.iface.legendInterface().setLayerVisible(oneLayer, False)
        except:
            pass

        ltefpsLayer = QgsVectorLayer("Polygon?crs=EPSG:"+currentInputCRS, u"4G图层频点PCI查找", "memory")
        ltefpsPr = ltefpsLayer.dataProvider()
        ltefpsPr.addAttributes(self.createAttributesTable('4GFreqPCISearch'))
        ltefpsLayer.updateFields()
        qgis.utils.iface.legendInterface().setLayerVisible(sourceLayer, False)
        ltefpsFet = QgsFeature()

        PCI_Types = {
            1: ('#FFFF00', u'频点='+str(inputFreq)+',PCI='+str(inputPCI)),
            0: ('#EEEEEE', u'无关频点PCI')
        }
        categories = []
        for pci_type, (color, label) in PCI_Types.items():
            symbol = QgsSymbolV2.defaultSymbol(ltefpsLayer.geometryType())
            symbol.setColor(QColor(color))
            category = QgsRendererCategoryV2(pci_type, symbol, label)
            categories.append(category)
            # 创建属性表
            fetAttrs = []
            relatedAttrs = []
            Longitude, Latitude, Azimuth = 11, 12, 14
            for feature in sourceLayer.getFeatures():
                attrs = feature.attributes()
                if (inputFreq == attrs[9]) & (inputPCI == int(attrs[13])):
                    temp = []
                    for j in range(21):
                        temp.append(attrs[j])
                    temp.append(1)
                    relatedAttrs.append(temp)
                else:
                    temp = []
                    for j in range(21):
                        temp.append(attrs[j])
                    temp.append(0)
                    fetAttrs.append(temp)
            for one in relatedAttrs:
                fetAttrs.append(one)
            for fetAttr in fetAttrs:
                ltefpsFet.setAttributes(fetAttr)
                # 开始画图
                points = [QgsPoint(fetAttr[Longitude], fetAttr[Latitude])]  # start point
                startAngle = -20
                endAngle = 20
                while startAngle <= endAngle:
                    points.append(
                        QgsPoint(fetAttr[Longitude] + 0.001 * math.sin(math.radians(fetAttr[Azimuth] + startAngle)),
                                 fetAttr[Latitude] + 0.001 * math.cos(math.radians(fetAttr[Azimuth] + startAngle))))
                    startAngle += 2
                points.append(QgsPoint(fetAttr[Longitude], fetAttr[Latitude]))  # end point
                ltefpsFet.setGeometry(QgsGeometry.fromPolygon([points]))
                ltefpsPr.addFeatures([ltefpsFet])
                # 根据字段值渲染颜色
                expression = 'FreqPCI'  # field name
                renderer = QgsCategorizedSymbolRendererV2(expression, categories)
                ltefpsLayer.setRendererV2(renderer)

                ltefpsLayer.updateExtents()
                ltefpsLayer.commitChanges()
                ltefpsLayer.updateFields()
                # 更新图层
                QgsMapLayerRegistry.instance().addMapLayer(ltefpsLayer)
        self.ltefpsdlg.close()
        self.saveEPSGChange()
        self.dlg.close()
Пример #30
0
def getTweetsLayer():
    testfile_dir = os.path.join(tm_dir(), testcfg.TEST_DATA_DIR)
    tweets = QgsVectorLayer(os.path.join(testfile_dir, 'tweets.shp'), 'tweets',
                            'ogr')
    return tweets