def unloadProject(self):
        QgsProject.instance().removeAllMapLayers()
        try:
            dirname = os.path.dirname(__file__)
            os.remove(
                os.path.join(dirname, 'qgis_project/temp_file/TempMap.qgs'))
            os.remove(
                os.path.join(dirname,
                             'qgis_project/temp_file/copy_energy_plant.shp'))
            os.remove(
                os.path.join(dirname,
                             'qgis_project/temp_file/copy_energy_plant.dbf'))
            os.remove(
                os.path.join(dirname,
                             'qgis_project/temp_file/copy_energy_plant.prj'))
            os.remove(
                os.path.join(dirname,
                             'qgis_project/temp_file/copy_energy_plant.qpj'))
            os.remove(
                os.path.join(dirname,
                             'qgis_project/temp_file/copy_energy_plant.shx'))
            os.remove(
                os.path.join(dirname, 'qgis_project/temp_file/TempMap.qgs~'))
        except OSError:
            pass

        self.iface.mapCanvas().refreshAllLayers()
示例#2
0
 def createdistancearea(self):
     distancearea = QgsDistanceArea()
     dest = self.canvas.mapSettings().destinationCrs()
     distancearea.setSourceCrs(dest, QgsProject.instance().transformContext())
     ellispoid = QgsProject.instance().readEntry("Measure", "/Ellipsoid", GEO_NONE)
     distancearea.setEllipsoid(ellispoid[0])
     return distancearea
示例#3
0
    def __init__(self, watchregistry=True, parent=None):
        super(QgsLayerModel, self).__init__(parent)
        self.layerfilter = [QgsMapLayer.VectorLayer, QgsMapLayer.RasterLayer]
        self.layers = []

        if watchregistry:
            QgsProject.instance().layerWasAdded.connect(self.addlayer)
            QgsProject.instance().removeAll.connect(self.removeall)
    def loadProject(self):
        # Get the project instance
        project = QgsProject.instance()
        # Load another project
        dirname = os.path.dirname(__file__)

        #copy all qgis_project folder file in temp_file for not modify it
        copyfile(os.path.join(dirname, 'qgis_project/Map.qgs'),
                 os.path.join(dirname, 'qgis_project/temp_file/TempMap.qgs'))
        copyfile(
            os.path.join(dirname, 'qgis_project/Energy_Plant.shp'),
            os.path.join(dirname,
                         'qgis_project/temp_file/copy_energy_plant.shp'))
        copyfile(
            os.path.join(dirname, 'qgis_project/Energy_Plant.dbf'),
            os.path.join(dirname,
                         'qgis_project/temp_file/copy_energy_plant.dbf'))
        copyfile(
            os.path.join(dirname, 'qgis_project/Energy_Plant.prj'),
            os.path.join(dirname,
                         'qgis_project/temp_file/copy_energy_plant.prj'))
        copyfile(
            os.path.join(dirname, 'qgis_project/Energy_Plant.qpj'),
            os.path.join(dirname,
                         'qgis_project/temp_file/copy_energy_plant.qpj'))
        copyfile(
            os.path.join(dirname, 'qgis_project/Energy_Plant.shx'),
            os.path.join(dirname,
                         'qgis_project/temp_file/copy_energy_plant.shx'))

        copy_map = os.path.join(dirname, 'qgis_project/temp_file/TempMap.qgs')
        copy_energy_plant = os.path.join(
            dirname, 'qgis_project/temp_file/copy_energy_plant.shp')
        project.read(copy_map)

        heatmap_layer_path = os.path.join(
            dirname, 'qgis_project/temp_file/copy_energy_plant.shp')

        self.iface.addVectorLayer(heatmap_layer_path, "radiation_heatmap",
                                  "ogr")
        self.iface.addVectorLayer(copy_energy_plant, "", "ogr")

        layer = QgsProject.instance().mapLayersByName(
            'radiation_heatmap copy_energy_plant')[0]
        layer.setOpacity(0.5)

        renderer = QgsHeatmapRenderer()
        renderer.setRenderQuality(1)
        renderer.setRadius(20)
        renderer.setWeightExpression("Radiation")

        style = QgsStyle.defaultStyle()
        defaultColorRampNames = style.colorRampNames()

        ramp = style.colorRamp(defaultColorRampNames[8])
        ramp.setColor1(QColor(0, 0, 4, 0))
        renderer.setColorRamp(ramp)
        layer.setRenderer(renderer)
示例#5
0
 def on_begin_clicked(self, bol=2):
     if bol == 2:
         return
     theta, dx, dy = icp(self.Timage, self.Simage, float(self.Theta.text()),
                         float(self.Dx.text()), float(self.Dy.text()))
     res = afterImg(theta, dx, dy)
     cv2.imwrite(self.OutputName.text(), res)
     layer = QgsRasterLayer(self.OutputName.text(), 'ICP_result')
     QgsProject.instance().addMapLayer(layer)
示例#6
0
 def store(self, key, value):
     assert len(key) > 0 and type(
         key) == str and key in self.data, "Invalid key!"
     if key == "interpol":
         proj = QgsProject.instance()
         proj.writeEntry(Config.PLUGIN_NAME, key, str(int(value)))
     else:
         proj = QgsProject.instance()
         proj.writeEntry(Config.PLUGIN_NAME, key, str(value))
示例#7
0
def pointFromWGS84(point):
    p = QgsProject.instance()
    (proj4string, ok) = p.readEntry("SpatialRefSys", "ProjectCRSProj4String")
    if not ok:
        return point
    f = QgsCoordinateReferenceSystem("EPSG:4326")
    t = QgsProject.instance().crs()
    transformer = QgsCoordinateTransform(f, t, p)
    pt = transformer.transform(point)
    return pt
示例#8
0
    def final(self):

        vlayer = self.vectorCombo.currentLayer()
        for feat in vlayer.getFeatures():
            the_geom = feat.geometry()
        #TODO: remove the line for debigging
        #self.message(str(vlayer.name())+'|'+str(the_geom.length())+'|'+str(self.breaks), 'red')

        ll1 = createMemLayer(the_geom, self.breaks)
        QgsProject.instance().addMapLayer(ll1)
示例#9
0
    def loadCloudIntoQGIS(self):
        try:
            # loadCloudButton ascFileNameLineEdit pointCloudPathLineEdit stepSizeSpinBox blast2demGroupBox consoleCommandPlainTextEdit
            self.dlg.selectCloudButton.setEnabled(False)
            self.dlg.loadCloudButton.setEnabled(False)
            self.dlg.ascFileNameLineEdit.setEnabled(False)
            self.dlg.pointCloudPathLineEdit.setEnabled(False)
            self.dlg.stepSizeSpinBox.setEnabled(False)
            self.dlg.blast2demGroupBox.setEnabled(False)
            self.dlg.pageDescPlainTextEdit.setEnabled(False)

            #cloudfile = self.PotreeCraftSupport.lasconvert_isready(r'c:\PotreeConverter_16\3DModel_Pcld_LASCloud.las', '-rgb', '0.1')
            cloudfile = self.PotreeCraftSupport.lasconvert_isready(
                self.dlg.pointCloudPathLineEdit.text(), self.ascParam,
                self.dlg.stepSizeSpinBox.text().replace(',', '.'))
            self.dlg.ascFileNameLineEdit.setText(cloudfile)
            print(self.PotreeCraftSupport.potreeconverterpath + cloudfile)
            # add raster layer
            fileInfo = QFileInfo(self.PotreeCraftSupport.potreeconverterpath +
                                 cloudfile)
            print(fileInfo)
            path = fileInfo.filePath()
            baseName = fileInfo.baseName()

            layer = QgsRasterLayer(path, baseName)
            QgsProject.instance().addMapLayer(layer)

            if layer.isValid() is True:
                print("Layer was loaded successfully!")
            else:
                print(
                    "Unable to read basename and file path - Your string is probably invalid"
                )

            self.dlg.selectCloudButton.setEnabled(True)
            self.dlg.loadCloudButton.setEnabled(True)
            self.dlg.ascFileNameLineEdit.setEnabled(True)
            self.dlg.pointCloudPathLineEdit.setEnabled(True)
            self.dlg.stepSizeSpinBox.setEnabled(True)
            self.dlg.blast2demGroupBox.setEnabled(True)
            self.dlg.pageDescPlainTextEdit.setEnabled(True)

        except Exception as genex:
            print('PYTHON EXCEPTOIN CAUGHT:')
            print(str(genex))
            self.dlg.selectCloudButton.setEnabled(True)
            self.dlg.loadCloudButton.setEnabled(True)
            self.dlg.ascFileNameLineEdit.setEnabled(True)
            self.dlg.pointCloudPathLineEdit.setEnabled(True)
            self.dlg.stepSizeSpinBox.setEnabled(True)
            self.dlg.blast2demGroupBox.setEnabled(True)
            self.dlg.pageDescPlainTextEdit.setEnabled(True)
示例#10
0
    def cotaFromTiff(self, layer, p, interpolate=True):
        p = QgsCoordinateTransform(QgsProject.instance().crs(), layer.crs(),
                                   QgsProject.instance()).transform(p)
        if interpolate:
            b, rec, row, col = self.getBlockRecAndItemFromPointInRaster(
                layer, p)
            if not b:
                return 0

            #matrix dos 9 pixels
            matx = [[[None, None, None], [None, None, None],
                     [None, None, None]],
                    [[None, None, None], [None, None, None],
                     [None, None, None]]]

            from itertools import product
            for i, j in product([-1, 0, 1], [-1, 0, 1]):
                matx[0][i + 1][j + 1] = b.value(row + i, col + j)  # elevações
                matx[1][i + 1][j + 1] = self.rectCell(
                    layer, row + i, col + j).center().distance(p)  # distancias
                if row < 0 or col < 0 or row >= layer.height(
                ) or col >= layer.width():
                    return 0

            V = [matx[0][i][j]
                 for i, j in product([0, 1, 2], [0, 1, 2])]  #elevações
            L = [matx[1][i][j]
                 for i, j in product([0, 1, 2], [0, 1, 2])]  #Distancias

            #tolerância de 1 diagonal inteira
            max_dist = (layer.rasterUnitsPerPixelX()**2 +
                        layer.rasterUnitsPerPixelY()**2)**(1 / 2)
            # pesos
            I = [(max_dist - l) / max_dist if l < max_dist else 0 for l in L]
            # média
            del matx
            del b
            del rec

            return sum(v * i for v, i in zip(V, I)) / sum(I)

        else:
            v = layer.dataProvider().sample(p, 1)
            try:
                if v[1]:
                    return v[0]
                else:
                    return 0
            except:
                return 0
示例#11
0
 def loadWebService(self):
     # get selected items and add to the map
     self.bar.show()
     EPSG_CODE_4326 = 'EPSG:4326'
     selectedServices = self.getSelectedItemsFromTable()
     web_map_service = self.generatedService.web_map_service
     for selectedService in selectedServices:
         if self.generatedService.service_url is not None:
             layer_name = selectedServices[selectedService].name
             url = 'contextualWMSLegend=0'
             if hasattr(web_map_service[layer_name], 'crsOptions'):
                 if len(web_map_service[layer_name].crsOptions) > 0:
                     if EPSG_CODE_4326 in web_map_service[
                             layer_name].crsOptions:
                         url += '&crs=' + EPSG_CODE_4326
                         if self.generatedService.service_type == ServiceType.WebMapTileService.value:
                             url += '&tileMatrixSet=' + EPSG_CODE_4326
                     else:
                         url += '&crs=' + web_map_service[
                             layer_name].crsOptions[0]
                         if self.generatedService.service_type == ServiceType.WebMapTileService.value:
                             url += '&tileMatrixSet=' + web_map_service[
                                 layer_name].crsOptions[0]
             else:
                 url += '&crs=' + EPSG_CODE_4326
                 if self.generatedService.service_type == ServiceType.WebMapTileService.value:
                     url += '&tileMatrixSet=' + EPSG_CODE_4326
             url += '&dpiMode=7&featureCount=10&format=image/png&styles' + \
                    '&layers=' + layer_name + \
                    '&url=' + str(self.generatedService.service_url)
             rlayer = QgsRasterLayer(
                 url, selectedServices[selectedService].title, 'wms')
             if not rlayer.isValid():
                 QMessageBox.information(
                     None, "ERROR:", 'Imposible cargar las capas ' +
                     selectedServices[selectedService].title +
                     ' en este momento.')
             else:
                 QgsProject.instance().addMapLayer(rlayer)
                 self.iFace.messageBar().pushMessage(
                     "Mensaje:",
                     "Fueron cargadas las capas WMS con exito",
                     level=Qgis.Success,
                     duration=3)
         else:
             QMessageBox.information(
                 None, "ERROR:",
                 'No selecciono ninguna capa WMS para cargar')
     self.bar.close()
 def init_state(self):
     dirname = os.path.dirname(__file__)
     layer = QgsProject.instance().mapLayersByName('copy_energy_plant')[0]
     if layer.featureCount() < NUMB_ENERGY_PLANT:
         filename = os.path.join(dirname,
                                 'dataset/global_power_plant_database.csv')
         layer.startEditing()
         with open(filename, 'r') as file:
             reader = csv.reader(file)
             for i, row in enumerate(reader):
                 if i > 0 and row[7] == "Nuclear":
                     pr = layer.dataProvider()
                     # insert in attribute table
                     poly = QgsFeature(layer.fields())
                     poly.setAttribute("Country", row[0])
                     poly.setAttribute("count_long", row[1])
                     poly.setAttribute("name", row[2])
                     poly.setAttribute("qppd_idnr", row[3])
                     poly.setAttribute("cap_mw", row[4])
                     poly.setAttribute("latitude", row[5])
                     poly.setAttribute("longitude", row[6])
                     poly.setAttribute("Radiation", random.randint(1, 200))
                     poly.setGeometry(
                         QgsGeometry.fromPointXY(
                             QgsPointXY(float(row[6]), float(row[5]))))
                     pr.addFeatures([poly])
             layer.updateExtents()
             layer.commitChanges()
             layer.reload()
示例#13
0
 def initProject(self):
     """ initialize project related connections """
     self.iface.projectRead.connect(self.readSettings)
     self.iface.newProjectCreated.connect(self.reset)
     QObject.connect(QgsProject.instance(),
                     SIGNAL("writeProject(QDomDocument &)"),
                     self.writeSettings)
示例#14
0
    def runClassifier(self):
        """
        Run method that performs image rendering
        and classification of runways if exist
        """

        # show the dialog
        self.classifier_dlg.show()

        self.classifier_dlg.sb_rn_to_process.setValue(0)

        # Run the dialog event loop
        result = self.classifier_dlg.exec_()

        # See if OK was pressed
        if result:
            self.getAirportNum()
            if self.airport_num == 0:
                return
            self.dataBuffer = []
            self.pointsCount = 0
            self.initialSize = self.iface.mapCanvas().size()
            self.imgSize = self.iface.mapCanvas().resize(QSize(602, 602))
            self.myLayer = QgsProject.instance().mapLayersByName(self.layer_name)[0]
            self.iface.setActiveLayer(self.myLayer)
            self.prepareMap()
    def make_relation(self, child_layer, parent_layer, foreign_key,
                      primary_key, relation_id):
        relation_name = 'from_' + parent_layer.name(
        ) + '_to_' + child_layer.name()
        # Setting up the relation
        rel = QgsRelation()
        rel.setReferencingLayer(parent_layer.id())
        rel.setReferencedLayer(child_layer.id())
        rel.addFieldPair(primary_key, foreign_key)
        rel.setId(relation_id)
        rel.setName(relation_name)

        # Adding the relation only if it's valid
        if rel.isValid():
            QgsProject.instance().relationManager().addRelation(rel)
            self.dev_print('Relation added: ' + relation_name)
        else:
            self.dev_print('Relation failed </3')
示例#16
0
    def processAlgorithm(self, parameters, context, model_feedback: QgsProcessingFeedback):

        project_name = parameters["ProjectName"]

        create_linear_features_layer = parameters["LinearFeaturesLayer"]

        if parameters["OutFolder"] == "TEMPORARY_OUTPUT":
            import tempfile
            parameters["OutFolder"] = tempfile.gettempdir()

        ofolder = Path(parameters["OutFolder"]).joinpath(project_name)
        crs = parameters["CRS"]

        vector_folder = ofolder.joinpath("vector")
        vector_file = vector_folder.joinpath(project_name.lower()).with_suffix(".gpkg")

        model_feedback.pushCommandInfo(f"Setting up project {project_name} in folder {ofolder}")

        model_feedback.pushCommandInfo(
            f"Vector files will be located in folder {vector_folder} (file will be {vector_file})")

        self.ensureDir(ofolder, model_feedback)
        self.ensureDir(vector_folder, model_feedback)

        # vl = QgsVectorLayer("Point", "source_indicators", "memory")

        pts_fields = [["unit_name", QVariant.String]]
        line_fields = [["certainty", QVariant.String]]

        self.generate_and_load_geopackage_layer(vector_file.as_posix(), crs, type="Point", name="source_indicators",
                                                fields=pts_fields)
        self.generate_and_load_geopackage_layer(vector_file.as_posix(), crs, type="Linestring", name="source_contacts",
                                                fields=line_fields)

        if create_linear_features_layer:
            structure_fields = [["certainty", QVariant.String], ["type", QVariant.String] ]
            self.generate_and_load_geopackage_layer(vector_file.as_posix(), crs, type="Linestring", name="linear_features",
                                                    fields=structure_fields)


        proj = QgsProject.instance()
        proj.write(ofolder.joinpath(project_name).with_suffix(".qgz").as_posix())

        from mappy.qgismappy import Mappy
        instance : Mappy = Mappy.instance
        instance.config_dock.show()

        dock = instance.config_dock

        w = dock.get_widget_by_name("output")
        restoreWidgetContent(w, vector_file)

        w = dock.get_widget_by_name("units_field")
        restoreWidgetContent(w, "unit_name")


        return {}
 def getLayerNames(self):
     project = QgsProject.instance()
     nameList = []
     for id, layer in project.mapLayers().items():
         nameList.append(layer.name())
     for i in range(len(nameList)):
         if nameList[i][-3:] == "_2d" or nameList[i][-3:] == "_3d":
             nameList[i] = nameList[i][:-3]
     nameList = list(dict.fromkeys(nameList))
     return nameList
示例#18
0
    def carregamapa(self, tmap=3):
        from ..model.utils import msgLog

        root = QgsProject.instance().layerTreeRoot()
        urlWithParams = 'type=xyz&url=http://mt1.google.com/vt/lyrs%3Ds%26x%3D%7Bx%7D%26y%3D%7By%7D%26z%3D%7Bz%7D&zmax=19&zmin=0'
        rlayer = QgsRasterLayer(urlWithParams, 'Google Satellite', 'wms')
        if rlayer.isValid():
            QgsProject.instance().addMapLayer(rlayer, False)
            root.addLayer(rlayer)
        else:
            msgLog('Failed to load Satellite layer')

        urlWithParams = 'type=xyz&url=http://mt1.google.com/vt/lyrs%3Dt%26x%3D%7Bx%7D%26y%3D%7By%7D%26z%3D%7Bz%7D&zmax=19&zmin=0'
        rlayer = QgsRasterLayer(urlWithParams, 'Google Terrain', 'wms')
        if rlayer.isValid():
            QgsProject.instance().addMapLayer(rlayer, False)
            root.addLayer(rlayer)
        else:
            msgLog('Failed to load Terrain layer')
示例#19
0
 def loadVectors(self):
     """ load vector layer of airport points"""
     self.classifier_dlg.cb_inVect.clear()
     layers = [layer for layer in QgsProject.instance().mapLayers().values()]
     vector_layers = []
     for layer in layers:
         if layer.type() == QgsMapLayer.VectorLayer:
             vector_layers.append(layer.name())
             self.layer_name = layer.name()
     self.classifier_dlg.cb_inVect.addItems(vector_layers)
示例#20
0
    def setLayerToInvisible(self):
        """Set layer to be invisible on map canvas"""

        # defining current project instance
        currentProject = QgsProject.instance()

        if(currentProject.layerTreeRoot().findLayer(self.myLayer.id()).isVisible()):
            # swap to invisible
            currentProject.layerTreeRoot().findLayer(self.myLayer.id()).setItemVisibilityChecked(False)
            return True
        return False
    def run(self):
        self.loadProject()
        self.init_state()
        """Run method that performs all the real work"""
        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            self.dlg = energy_plant_radiation_classDialog()
            self.dlg.start_radiation.clicked.connect(self.run_pub_sub)
            self.dlg.sb.valueChanged.connect(self.setTimeRate)

        def updteRadiation():
            energy_plant_radiation_class.upddateRadiation = threading.Timer(
                energy_plant_radiation_class.radiationRate, schedule_update)
            if not energy_plant_radiation_class.subscriber.isEmpty():

                #Retrieve heatmap
                layer = QgsProject.instance().mapLayersByName(
                    'radiation_heatmap copy_energy_plant')[0]
                radiations = energy_plant_radiation_class.subscriber.getRadiationList(
                )
                layer.startEditing()
                index = 0
                it = layer.getFeatures()
                for feat in it:
                    layer.changeAttributeValue(feat.id(), 5, radiations[index])
                    index = index + 1
                layer.commitChanges()
            energy_plant_radiation_class.upddateRadiation.start()

        def schedule_update():
            GObject.idle_add(updteRadiation)

        updteRadiation()

        layer = QgsProject.instance().mapLayersByName(
            'radiation_heatmap copy_energy_plant')[0]
        layer.reload()
        self.progressBar()
        #set windows dialog to bottom center
        self.dlg.setGeometry(850, 850, 376, 163)
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if Close was pressed
        if result == 0:
            energy_plant_radiation_class.upddateRadiation.cancel()
            self.stopTask()
            self.unloadProject()
            self.iface.messageBar().clearWidgets()
            print("End Nuclear Energy Plant Plugin")
            pass
    def mergeLayers(self):
        project = QgsProject.instance()
        completeLayerList = []
        for id, layer in project.mapLayers().items():
            currentLayerName = layer.name()
            currentLayerType = int(layer.wkbType())
            for id_2, layer_2 in project.mapLayers().items():
                secondLayerName = layer_2.name()
                secondLayerType = int(layer_2.wkbType())
                parameter1 = secondLayerName + "_2d"
                parameter2 = secondLayerName[:-3]
                parameter3 = secondLayerName + "_3d"
                parameter5 = int(repr(currentLayerType)[-1])
                parameter6 = int(repr(secondLayerType)[-1])

                if secondLayerName in currentLayerName and currentLayerType != secondLayerType and (
                        currentLayerName == parameter1
                        or currentLayerName == parameter2 or currentLayerName
                        == parameter3) and parameter5 == parameter6:
                    self.dlg.textEdit.append("Slår sammen: " +
                                             currentLayerName + " " +
                                             str(currentLayerType) + " " +
                                             str(secondLayerType) + " " +
                                             secondLayerName)
                    layerList = [layer, layer_2]
                    completeLayerList.append(layer)
                    completeLayerList.append(layer_2)
                    if len(currentLayerName) > len(secondLayerName):
                        completeLayerName = currentLayerName[:-3]
                    else:
                        completeLayerName = secondLayerName[:-3]
                    try:
                        processing.runAndLoadResults(
                            "qgis:mergevectorlayers", {
                                'LAYERS':
                                layerList,
                                'OUTPUT':
                                completeLayerName + " " +
                                QgsWkbTypes.displayString(currentLayerType)
                            })
                    except QgsProcessingException:
                        completeLayerList = completeLayerList[:-2]
                        self.errorMessage("Fikk problemer med å slå sammen " +
                                          str(currentLayerName) + " og " +
                                          str(secondLayerName))
                        self.dlg.textEdit.append(str(QgsProcessingException))

                    break
                else:
                    pass

        for i in completeLayerList:
            project.removeMapLayers([i.id()])
示例#23
0
 def loadWebService(self):
     # get selected items and add to the map
     self.bar.show()
     EPSG_CODE_4326 = 'EPSG:4326'
     selectedServices = self.getSelectedItemsFromTable()
     web_map_service = self.generatedService.web_map_service
     for selectedService in selectedServices:
         if self.generatedService.service_url is not None:
             layer_name = selectedServices[selectedService].name
             url = 'contextualWMSLegend=0'
             if hasattr(web_map_service[layer_name], 'crsOptions'):
                 if len(web_map_service[layer_name].crsOptions) > 0:
                     if EPSG_CODE_4326 in web_map_service[layer_name].crsOptions:
                         url += '&crs=' + EPSG_CODE_4326
                         if self.generatedService.service_type == ServiceType.WebMapTileService.value:
                                 url += '&tileMatrixSet=' + EPSG_CODE_4326
                     else:
                         url += '&crs=' + web_map_service[layer_name].crsOptions[0]
                         if self.generatedService.service_type == ServiceType.WebMapTileService.value:
                                 url += '&tileMatrixSet=' + web_map_service[layer_name].crsOptions[0]
             else:
                 url += '&crs=' + EPSG_CODE_4326
                 if self.generatedService.service_type == ServiceType.WebMapTileService.value:
                     url += '&tileMatrixSet=' + EPSG_CODE_4326
             url += '&dpiMode=7&featureCount=10&format=image/png&styles' + \
                    '&layers=' + layer_name + \
                    '&url=' + str(self.generatedService.service_url)
             rlayer = QgsRasterLayer(url, selectedServices[selectedService].title, 'wms')
             if not rlayer.isValid():
                 QMessageBox.information(None, "ERROR:", 'Unable to load ' +
                                         selectedServices[selectedService].title +
                                         ' this layer now.')
             else:
                 QgsProject.instance().addMapLayer(rlayer)
         else:
             QMessageBox.information(None, "ERROR:", 'Service url is None')
     self.bar.close()
示例#24
0
 def loadLayerCRSsForComboBox(self):
     self.dlg.crsFromProjectComboBox.clear()
     layers = [
         layer for layer in QgsProject.instance().mapLayers().values()
     ]
     for l in layers:
         AllItems = [
             self.dlg.crsFromProjectComboBox.itemText(i)
             for i in range(self.dlg.crsFromProjectComboBox.count())
         ]
         if (str(l.crs().authid()) + " [" + str(l.crs().description()) +
                 "]") not in AllItems:
             self.dlg.crsFromProjectComboBox.addItem(
                 str(l.crs().authid()) + " [" + str(l.crs().description()) +
                 "]")
示例#25
0
 def read(self, key):
     assert len(key) > 0 and type(
         key) == str and key in self.data, "Invalid key!"
     proj = QgsProject.instance()
     value: str
     value = proj.readEntry(Config.PLUGIN_NAME, key,
                            str(getattr(Config, key)))[0]
     if value.isdigit():
         value = int(value)
     else:
         try:
             value = float(value)
         except:
             pass
     setattr(self, key, value)
     return value
示例#26
0
 def saveGeoPackage(self,name:str, poly, fields, type, driver):
     import shutil
     from pathlib import Path
     extractZIP(Config.fileName)
     tmp=str(Path(self.tmpFolder()+"/"+name+".gpkg"))
     path=str(Path(Config.instance().TMP_DIR_PATH+"tmp/data/"+name+".gpkg"))
     shutil.rmtree(str(path),  ignore_errors=True)
     shutil.rmtree(str(tmp),  ignore_errors=True)
     writer = QgsVectorFileWriter(path, 'UTF-8', fields, type, QgsProject.instance().crs(), driver)
     for p in poly:
         writer.addFeature(p)
     del writer
     shutil.copy(path, tmp)
     shutil.copy(tmp, Config.instance().TMP_DIR_PATH+'tmp/data/'+name+".gpkg")
     compactZIP(Config.fileName)
     return tmp
 def add_value_map(self, layer_name, field_name, dict_choices):
     try:
         layers = QgsProject.instance().mapLayersByName(layer_name)
         if layers and dict_choices:
             for layer in layers:
                 field_index = layer.fields().indexFromName(field_name)
                 editor_widget_setup = QgsEditorWidgetSetup(
                     'ValueMap', {'map': dict_choices})
                 layer.setEditorWidgetSetup(field_index,
                                            editor_widget_setup)
                 self.dev_print('ValueMap added')
         else:
             self.dev_print("Layer or choices don't exist")
             return
     except Exception:
         print('Exception raised')
         return
def get_distance(pnt1, pnt2, epsg_code):
    """
    :param pnt1: QgsPoint object
    :param pnt2: QgsPoint object

    :returns the distance between pnt1 and pnt2
    """
    # Create a measure object
    distance = QgsDistanceArea()
    crs = QgsCoordinateReferenceSystem()
    # Sets this CRS by lookup of the given PostGIS SRID in the CRS database.
    crs.createFromSrid(epsg_code)
    context = QgsProject.instance().transformContext()
    distance.setSourceCrs(crs, context)
    if epsg_code == constants.EPSG_WGS84:
        distance.setEllipsoid("WGS84")
    return distance.measureLine(pnt1, pnt2)
 def run(self):
     if self.first_start:
         self.dlg.kommuneBox.setEnabled(False)
         self.dlg.kontraktBox.setEnabled(False)
         self.displayFilters()
         self.loadPresets()
         self.first_start = False
     self.dlg.comboBox.clear()
     self.dlg.comboBox.addItems(sortCategories())
     self.dlg.fylkeBox.addItems(getFylkeNavn())
     self.dlg.openLayers = openLayers = QgsProject.instance().layerTreeRoot(
     ).children()
     self.dlg.listWidget_layers.clear()
     #self.dlg.listWidget_layers.addItems([layer.name() for layer in openLayers])
     self.dlg.show()
     result = self.dlg.exec_()
     if result:
         """ Close """
        def updteRadiation():
            energy_plant_radiation_class.upddateRadiation = threading.Timer(
                energy_plant_radiation_class.radiationRate, schedule_update)
            if not energy_plant_radiation_class.subscriber.isEmpty():

                #Retrieve heatmap
                layer = QgsProject.instance().mapLayersByName(
                    'radiation_heatmap copy_energy_plant')[0]
                radiations = energy_plant_radiation_class.subscriber.getRadiationList(
                )
                layer.startEditing()
                index = 0
                it = layer.getFeatures()
                for feat in it:
                    layer.changeAttributeValue(feat.id(), 5, radiations[index])
                    index = index + 1
                layer.commitChanges()
            energy_plant_radiation_class.upddateRadiation.start()
示例#31
0
    def __init__(self, db_settings=None):
        """
        Manuals for db connectors:
        https://github.com/qgis/QGIS/blob/master/python/plugins/db_manager/db_plugins/connector.py
        https://github.com/qgis/QGIS/blob/master/python/plugins/db_manager/db_plugins/postgis/connector.py
        https://github.com/qgis/QGIS/blob/master/python/plugins/db_manager/db_plugins/spatialite/connector.py
        """
        self.conn = None
        self.cursor = None
        self.connector = None

        if db_settings is None:
            db_settings = QgsProject.instance().readEntry("Midvatten", "database")[0]

        if isinstance(db_settings, str):
            #Test if the db_setting is an old database
            if os.path.isfile(db_settings):
                db_settings = {'spatialite': {'dbpath': db_settings}}
            else:
                if not db_settings:
                    raise utils.UsageError(ru(QCoreApplication.translate('DbConnectionManager', 'Database setting was empty. Check DB tab in Midvatten settings.' )))
                else:
                    try:
                        db_settings = ast.literal_eval(db_settings)
                    except:
                        raise utils.UsageError(ru(QCoreApplication.translate('DbConnectionManager', 'Database could not be set. Check DB tab in Midvatten settings.')))

        elif isinstance(db_settings, dict):
            # Assume it the dict is a valid db_settings dict.
            pass
        else:
            raise Exception(ru(QCoreApplication.translate('DbConnectionManager', "DbConnectionManager programming error: db_settings must be either a dict like {'spatialite': {'dbpath': 'x'} or a string representation of it. Was: %s"))%ru(db_settings))

        db_settings = ru(db_settings, keep_containers=True)

        self.db_settings = db_settings

        self.dbtype = list(self.db_settings.keys())[0]
        self.connection_settings = list(self.db_settings.values())[0]

        self.uri = QgsDataSourceUri()

        if self.dbtype == 'spatialite':
            self.dbpath = ru(self.connection_settings['dbpath'])

            if not os.path.isfile(self.dbpath):
                raise utils.UsageError(ru(QCoreApplication.translate('DbConnectionManager', 'Database error! File "%s" not found! Check db tab in Midvatten settings!'))%self.dbpath)

            self.check_db_is_locked()

            #Create the database if it's not existing
            self.uri.setDatabase(self.dbpath)

            try:
                self.connector = spatialite_connector.SpatiaLiteDBConnector(self.uri)
            except Exception as e:

                utils.MessagebarAndLog.critical(bar_msg=ru(QCoreApplication.translate('DbConnectionManager', 'Connecting to spatialite db %s failed! Check that the file or path exists.')) % self.dbpath,
                                                log_msg=ru(QCoreApplication.translate('DbConnectionManager', 'msg %s'))%str(e))
                raise

        elif self.dbtype == 'postgis':
            connection_name = self.connection_settings['connection'].split('/')[0]
            self.postgis_settings = get_postgis_connections()[connection_name]
            self.uri.setConnection(self.postgis_settings['host'], self.postgis_settings['port'], self.postgis_settings['database'], self.postgis_settings['username'], self.postgis_settings['password'])
            try:
                self.connector = postgis_connector.PostGisDBConnector(self.uri)
            except Exception as e:
                print(str(e))
                if 'no password supplied' in str(e):
                    utils.MessagebarAndLog.warning(bar_msg=ru(QCoreApplication.translate('DbConnectionManager', 'No password supplied for postgis connection')))
                    raise utils.UserInterruptError()
                else:
                    raise

        if self.connector is not None:
            self.conn = self.connector.connection
            self.cursor = self.conn.cursor()
示例#32
0
 def initProject(self):
     """ initialize project related connections """
     self.iface.projectRead.connect(self.readSettings)
     self.iface.newProjectCreated.connect(self.reset)
     QObject.connect(QgsProject.instance(), SIGNAL("writeProject(QDomDocument &)"),
                     self.writeSettings)
示例#33
0
def save_project_to_file(fn):
    QgsProject.instance().write(QtCore.QFileInfo(fn))
    sleep(0.1)
示例#34
0
def load_project(fn):
    QgsProject.instance().setFileName(fn)
    QgsProject.instance().read()
    iface.projectRead.emit()