Пример #1
0
    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """

        source = self.parameterAsLayer(parameters, self.INPUT, context)

        feedback.pushInfo(f"source {source}")

        if source is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.INPUT))

        curcrs = source.crs().toProj()
        import re
        mm = re.compile("\+k.*")

        newcrs = [c for c in curcrs.split(" ") if not mm.match(c)]

        out = " ".join(newcrs)

        feedback.pushInfo(f" Starting crs: {curcrs}")
        feedback.pushInfo(f" cleaned crs: {out}")

        newcrs = QgsCoordinateReferenceSystem()
        status = newcrs.createFromProj(out)

        feedback.pushInfo(f" cleaned crs 2: stat {status} : {newcrs}")
        source.setCrs(newcrs)

        return {}
Пример #2
0
    def testTransformIdentity(self):

        crsIn = QgsCoordinateReferenceSystem("EPSG:4326")
        crsOut = QgsCoordinateReferenceSystem("EPSG:4326")

        self.coordinator.setInputCrs(crsIn)
        self.dw.outputCrsConn.setEnabled(False)
        self.coordinator.setOutputCrs(crsOut)

        QTest.keyPress(self.dw.inLeft, "2")
        self.assertEqual(helperFormatCoordinates("2°0′0.000″E"),
                         self.dw.resultLeft.text())
        self.assertEqual(helperFormatCoordinates("0°0′0.000″"),
                         self.dw.resultRight.text())

        QTest.keyPress(self.dw.inLeft, "3")
        self.assertEqual(helperFormatCoordinates("23°0′0.000″E"),
                         self.dw.resultLeft.text())
        self.assertEqual(helperFormatCoordinates("0°0′0.000″"),
                         self.dw.resultRight.text())

        QTest.keyPress(self.dw.inRightMin, "2")
        self.assertEqual(helperFormatCoordinates("23°0′0.000″E"),
                         self.dw.resultLeft.text())
        self.assertEqual(helperFormatCoordinates("0°2′0.000″N"),
                         self.dw.resultRight.text())
Пример #3
0
 def onCRSComboboxChanged(self):
     crsidtext = self.dlg.crsFromProjectComboBox.currentText().split(
         "[")[0].strip()
     crs = QgsCoordinateReferenceSystem(crsidtext)
     if crs.isValid():
         self.crsParam = str(crs.toProj4())
         print(self.crsParam)
         print(crs.toProj4())
Пример #4
0
    def testCanvasTransformation(self):

        currentCanvasCrs = CANVAS.mapSettings().destinationCrs()
        self.assertEqual(currentCanvasCrs,
                         self.coordinator._canvasTransform.destinationCrs())

        CANVAS.setDestinationCrs(QgsCoordinateReferenceSystem("EPSG:32615"))
        self.assertEqual(
            "EPSG:32615",
            self.coordinator._canvasTransform.destinationCrs().authid())

        CANVAS.setDestinationCrs(
            QgsCoordinateReferenceSystem(currentCanvasCrs))
        self.assertEqual(currentCanvasCrs,
                         self.coordinator._canvasTransform.destinationCrs())
Пример #5
0
    def onLayerCRSRadioButtonClicked(self):
        thisRadioButton = self.dlg.sender()
        self.loadLayerCRSsForComboBox()
        crsidtext = self.dlg.crsFromProjectComboBox.currentText().split(
            "[")[0].strip()
        crs = QgsCoordinateReferenceSystem(crsidtext)

        #crs = QgsCoordinateReferenceSystem("EPSG:27700")
        if crs.isValid():
            self.crsParam = str(crs.toProj4())
            print(self.crsParam)
        if thisRadioButton.isChecked():
            print("selected: %s" % (thisRadioButton.text()))
            self.dlg.customCrsPlainTextEdit.setEnabled(False)
            print(crs.toProj4())
            self.dlg.crsFromProjectComboBox.setEnabled(True)
def set_layer_crs(layer_instance, epsg_code):
    """
    set the coordinate reference system of the layer to the given epsg code
    """
    qcrs = QgsCoordinateReferenceSystem("EPSG:{}".format(epsg_code))
    layer_instance.setCrs(qcrs)
    return layer_instance
Пример #7
0
    def testSwitchHemispheres(self):
        crsIn = QgsCoordinateReferenceSystem("EPSG:4326")
        crsOut = QgsCoordinateReferenceSystem("EPSG:4326")

        self.coordinator.setInputCrs(crsIn)
        self.dw.outputCrsConn.setEnabled(False)
        self.coordinator.setOutputCrs(crsOut)

        self.assertEqual("E", self.dw.leftDirButton.text())
        self.assertEqual("N", self.dw.rightDirButton.text())

        self.dw.inLeft.insert("10")
        self.dw.inLeftMin.insert("5")
        self.dw.inLeftSec.insert("1")

        self.dw.inRight.insert("5")
        self.dw.inRightMin.insert("10")
        self.dw.inRightSec.insert("45")

        self.assertEqual(helperFormatCoordinates("10°5′1.000″E"),
                         self.dw.resultLeft.text())
        self.assertEqual(helperFormatCoordinates("5°10′45.000″N"),
                         self.dw.resultRight.text())

        QTest.mouseClick(self.dw.leftDirButton, QtCore.Qt.LeftButton)
        self.assertEqual("W", self.dw.leftDirButton.text())
        self.assertEqual("N", self.dw.rightDirButton.text())
        self.assertEqual(helperFormatCoordinates("10°5′1.000″W"),
                         self.dw.resultLeft.text())
        self.assertEqual(helperFormatCoordinates("5°10′45.000″N"),
                         self.dw.resultRight.text())

        QTest.mouseClick(self.dw.rightDirButton, QtCore.Qt.LeftButton)
        self.assertEqual("W", self.dw.leftDirButton.text())
        self.assertEqual("S", self.dw.rightDirButton.text())
        self.assertEqual(helperFormatCoordinates("10°5′1.000″W"),
                         self.dw.resultLeft.text())
        self.assertEqual(helperFormatCoordinates("5°10′45.000″S"),
                         self.dw.resultRight.text())

        QTest.mouseClick(self.dw.rightDirButton, QtCore.Qt.LeftButton)
        self.assertEqual("W", self.dw.leftDirButton.text())
        self.assertEqual("N", self.dw.rightDirButton.text())
        self.assertEqual(helperFormatCoordinates("10°5′1.000″W"),
                         self.dw.resultLeft.text())
        self.assertEqual(helperFormatCoordinates("5°10′45.000″N"),
                         self.dw.resultRight.text())
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)
Пример #9
0
 def changeCRS(self, crs):
     if crs == None:
         crs = 31983
     mycrs = QgsCoordinateReferenceSystem(int(crs), 0)
     # self.iface.mapCanvas().mapRenderer().setCrs( QgsCoordinateReferenceSystem(mycrs, QgsCoordinateReferenceSystem.EpsgCrsId) )
     self.iface.mapCanvas().mapSettings().setDestinationCrs(
         mycrs)  # set CRS to canvas
     # self.iface.mapCanvas().setMapUnits(QGis.Meters)
     self.iface.mapCanvas().refresh()
Пример #10
0
    def testTransformGeodesicToGeographic(self):
        self.coordinator.setInputCrs(
            QgsCoordinateReferenceSystem("EPSG:32633"))
        self.dw.outputCrsConn.setEnabled(False)
        self.coordinator.setOutputCrs(
            QgsCoordinateReferenceSystem("EPSG:4326"))

        QTest.keyClicks(self.dw.inLeftDec, "560000")
        QTest.keyClicks(self.dw.inRightDec, "5400000")
        self.assertEqual(helperFormatCoordinates("15°48′58.480″E"),
                         self.dw.resultLeft.text())
        self.assertEqual(helperFormatCoordinates("48°45′0.440″N"),
                         self.dw.resultRight.text())

        QTest.mouseClick(self.dw.resultAsDec, QtCore.Qt.LeftButton)
        self.assertEqual(helperFormatCoordinates("15.816244426°E"),
                         self.dw.resultLeft.text())
        self.assertEqual(helperFormatCoordinates("48.750122268°N"),
                         self.dw.resultRight.text())
Пример #11
0
    def testCrsChangeOnLayer(self):
        """[GITHUB #1] CRS change of selected layer"""

        eLayer = self.addEuropeLayer()
        self.assertEqual("EPSG:4326", eLayer.crs().authid())
        global IFACE
        IFACE.setActiveLayer(eLayer)

        self.assertEqual("EPSG:4326", self.coordinator.outputCrs().authid())

        eLayer.setCrs(QgsCoordinateReferenceSystem("EPSG:32633"))
        self.assertEqual("EPSG:32633", eLayer.crs().authid())
        self.assertEqual("EPSG:32633", self.coordinator.outputCrs().authid())
        self.project.removeMapLayer(eLayer)
Пример #12
0
    def testTransformGeographicToGeodesic(self):
        self.coordinator.setInputCrs(QgsCoordinateReferenceSystem("EPSG:4326"))
        self.dw.outputCrsConn.setEnabled(False)
        self.coordinator.setOutputCrs(
            QgsCoordinateReferenceSystem("EPSG:32633"))

        QTest.keyClicks(self.dw.inLeft, "14")
        QTest.keyClicks(self.dw.inLeftMin, "30")
        QTest.keyClicks(self.dw.inLeftSec, "45")
        QTest.keyClicks(self.dw.inRight, "45")
        QTest.keyClicks(self.dw.inRightMin, "10")
        QTest.keyClicks(self.dw.inRightSec, "5")

        self.assertEqual(helperFormatCoordinates("461,690.03"),
                         self.dw.resultLeft.text())
        self.assertEqual(helperFormatCoordinates("5,001,735.10"),
                         self.dw.resultRight.text())

        self.coordinator.setOutputCrs(
            QgsCoordinateReferenceSystem("EPSG:32632"))
        self.assertEqual(helperFormatCoordinates("933,193.62"),
                         self.dw.resultLeft.text())
        self.assertEqual(helperFormatCoordinates("5,016,421.01"),
                         self.dw.resultRight.text())
Пример #13
0
    def init_layers(self):
        """
        Sets up the layers for rendering the items
        :return: None
        """
        if self.footprint_layer:
            QgsMapLayerRegistry.instance().removeMapLayer(
                self.footprint_layer.id())

        self.footprint_layer = QgsVectorLayer("Polygon?crs=EPSG:4326",
                                              "Catalog Footprints", "memory")
        self.footprint_layer.setCrs(QgsCoordinateReferenceSystem(4326), True)
        self.footprint_layer.dataProvider().addAttributes(
            CatalogAcquisitionFeature.get_fields())
        QgsMapLayerRegistry.instance().addMapLayer(self.footprint_layer)
Пример #14
0
    def testLayerLock(self):
        outputCrs = self.coordinator._outputCrs

        newCrs = QgsCoordinateReferenceSystem("EPSG:32615")
        CANVAS.setDestinationCrs(newCrs)

        self.dw.outputCrsConn.setEnabled(True)
        QTest.mouseClick(self.dw.outputCrsConn, QtCore.Qt.LeftButton)
        QTest.qWait(100)
        QTest.mouseClick(self.dw.outputCrsConn, QtCore.Qt.LeftButton)

        self.assertEqual(self.coordinator._outputCrs, newCrs)

        QTest.qWait(100)
        # Simulate a click, but nothing should happen
        QTest.mouseClick(self.dw.outputCrs, QtCore.Qt.LeftButton)
Пример #15
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
Пример #16
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)
Пример #17
0
    def testGeographicInputDisplay(self):
        crsIn = QgsCoordinateReferenceSystem("EPSG:4326")

        QTest.mouseClick(self.dw.inputAsDec, QtCore.Qt.LeftButton)
        self.assertFalse(self.dw.inputAsDMS.isChecked())
        self.assertTrue(self.dw.inputAsDec.isChecked())

        QTest.qSleep(3000)

        self.assertFalse(self.dw.inLeft.isVisible())
        self.assertFalse(self.dw.inLeftMin.isVisible())
        self.assertFalse(self.dw.inLeftSec.isVisible())

        self.assertFalse(self.dw.inRight.isVisible())
        self.assertFalse(self.dw.inRightMin.isVisible())
        self.assertFalse(self.dw.inRightSec.isVisible())

        self.assertTrue(self.dw.inLeftDec.isVisible())
        self.assertTrue(self.dw.inRightDec.isVisible())

        QTest.mouseClick(self.dw.inputAsDMS, QtCore.Qt.LeftButton)
        self.assertTrue(self.dw.inputAsDMS.isChecked())
        self.assertFalse(self.dw.inputAsDec.isChecked())

        self.dw.inLeft.insert("10")
        self.dw.inLeftMin.insert("5")
        self.dw.inLeftSec.insert("1")

        self.dw.inRight.insert("5")
        self.dw.inRightMin.insert("10")
        self.dw.inRightSec.insert("45")

        QTest.mouseClick(self.dw.inputAsDec, QtCore.Qt.LeftButton)
        self.assertEqual(helperFormatCoordinates("10.083611111"),
                         self.dw.inLeftDec.text())
        self.assertEqual(helperFormatCoordinates("5.179166667"),
                         self.dw.inRightDec.text())
Пример #18
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)
Пример #19
0
    def executeCropRowsClipProcessing(self):
        """Execute Crop Rows STEP 1"""
        QgsMessageLog.logMessage(
            'Excecute Task1: Clip Raster Mosaic by Vector Mask')
        strMosaicRasterFileSelected = self.dlg.comboBoxInputRaster.currentText(
        )
        strMaskVectorFileSelected = self.dlg.comboBoxInputVector.currentText()

        seedValue = 0
        QgsMessageLog.logMessage('Get Seed from user selection')
        if self.dlg.radioButtonSeed1.isChecked() == True:
            seedValue = 1
        elif self.dlg.radioButtonSeed2.isChecked() == True:
            seedValue = 2
        elif self.dlg.radioButtonSeed3.isChecked() == True:
            seedValue = 3
        elif self.dlg.radioButtonSeed4.isChecked() == True:
            seedValue = 4

        if (seedValue == 0):
            QgsMessageLog.logMessage('You must be set a seed value !')
            QMessageBox.critical(None, 'Error!',
                                 "You must be set a <b>seed</b> value !",
                                 QMessageBox.Ok)
            pass
        else:
            QgsMessageLog.logMessage('Seed value: ' + str(seedValue))

        #Start Crop Rows processing
        if strMosaicRasterFileSelected != '' and strMaskVectorFileSelected != '' and seedValue > 0 and self.flagClipTaskDone == 0:
            if self.flagNoCropRaster == False:
                msgboxCrop = "Are you sure that you want to start a <b>Mosaic Clip by Mask</b> process?<br>Keep in mind this task can take a few minutes, even several hours."
            else:
                msgboxCrop = "Are you sure that you want to copy a raster <b>Mosaic</b> into a selected shared folder?<br>Keep in mind this process can take a few minutes, even several hours."
            ret = QMessageBox.question(None, "Mosaic Data Preprocessing",
                                       (msgboxCrop),
                                       QMessageBox.Yes | QMessageBox.No,
                                       QMessageBox.Yes)
            if ret == QMessageBox.Yes:
                #hide step1 button
                self.dlg.btnExecuteClippingTask.setVisible(False)
                QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)

                self.dlg.statusBarProcessing.setGeometry(10, 281, 631, 31)

                self.dlg.statusBarProcessing.setValue(1)
                QgsMessageLog.logMessage('Processing Raster ')
                #urlSourceRasterMosaic = QgsMapLayerRegistry.instance().mapLayersByName(strMosaicRasterFileSelected)[0].dataProvider().dataSourceUri()
                urlSourceRasterMosaic = QgsProject.instance().mapLayersByName(
                    strMosaicRasterFileSelected)[0].dataProvider(
                    ).dataSourceUri()
                self.dlg.statusBarProcessing.setValue(5)
                #urlSourceVectorMask = QgsMapLayerRegistry.instance().mapLayersByName(strMaskVectorFileSelected)[0].dataProvider().dataSourceUri()
                urlSourceVectorMask = QgsProject.instance().mapLayersByName(
                    strMaskVectorFileSelected)[0].dataProvider().dataSourceUri(
                    )
                self.dlg.statusBarProcessing.setValue(10)
                urlSourceVectorMaskSplit = urlSourceVectorMask.split("|")[0]
                self.dlg.statusBarProcessing.setValue(20)
                temporalPath = self.dlg.inputSharedFolderPath.text().replace(
                    "/", "\\")
                rasterLyr = QgsRasterLayer(urlSourceRasterMosaic, "masklayer")
                pixelSizeX = rasterLyr.rasterUnitsPerPixelX()
                pixelSizeY = rasterLyr.rasterUnitsPerPixelY()
                self.dlg.statusBarProcessing.setValue(25)

                QgsMessageLog.logMessage(str(urlSourceRasterMosaic))
                QgsMessageLog.logMessage(str(urlSourceVectorMaskSplit))
                QgsMessageLog.logMessage('GDAL Clipper')
                QgsMessageLog.logMessage(str(pixelSizeX))
                QgsMessageLog.logMessage(str(pixelSizeY))

                gdalOSGeoPath = self.dlg.inputGdalOsgeoPath.text().replace(
                    "/", "\\")
                #temporalPath = self.dlg.inputSharedFolderPath.text().replace("/", "\\")
                self.dlg.statusBarProcessing.setValue(30)
                timestr = time.strftime("%Y%m%d-%H%M%S")
                ouputFilenameRasterClip = 'clipfile_' + timestr + '.tif'
                ouputFilenameVectorMask = 'maskfile_' + timestr + '.shp'
                ouputFilenamePrj = 'croprows_' + timestr
                ouputFilenameCropRowsProjectXML = 'croprows_' + timestr + '.xml'
                ouputclipfile_path = os.path.join(temporalPath,
                                                  ouputFilenameRasterClip)
                #temporalPath.replace("/", "\\") + ouputFilenameRasterClip
                self.dlg.statusBarProcessing.setValue(35)

                if self.flagNoCropRaster == True:
                    QgsMessageLog.logMessage(
                        'No Crop option selected - Copy file directly')
                    shutil.copyfile(
                        urlSourceRasterMosaic,
                        os.path.join(ouputclipfile_path[:-4] + '.tif'))
                    self.dlg.statusBarProcessing.setValue(40)
                else:
                    QgsMessageLog.logMessage(
                        'Crop raster by mask option selected - Cliping using GDAL'
                    )
                    #print('C:/Program Files/QGIS 2.14/bin/gdalwarp')
                    gdalWarpSubProcessCommand = '"' + gdalOSGeoPath + "\\" + 'gdalwarp.exe" -dstnodata -9999 -q -cutline ' + urlSourceVectorMaskSplit.replace(
                        "/", "\\") + ' -crop_to_cutline -tr ' + str(
                            pixelSizeX) + ' ' + str(
                                pixelSizeX
                            ) + ' -of GTiff ' + urlSourceRasterMosaic.replace(
                                "/", "\\") + ' ' + ouputclipfile_path
                    QgsMessageLog.logMessage(str(gdalWarpSubProcessCommand))
                    self.dlg.statusBarProcessing.setValue(40)
                    p = subprocess.Popen(gdalWarpSubProcessCommand,
                                         shell=True,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.STDOUT)
                    for line in p.stdout.readlines():
                        print(line),
                        retval = p.wait()

                self.dlg.statusBarProcessing.setValue(50)
                QgsMessageLog.logMessage(
                    'Clipper process done check result file ' +
                    ouputclipfile_path)
                #Load result file into map environment
                rasterLayerClipped = QgsRasterLayer(
                    ouputclipfile_path, ouputFilenameRasterClip[:-4])

                pixelSizeXClip = rasterLayerClipped.rasterUnitsPerPixelX()
                pixelSizeYClip = rasterLayerClipped.rasterUnitsPerPixelY()

                imageWClip = rasterLayerClipped.width()
                imageHClip = rasterLayerClipped.height()

                providerRasterLayerClipped = rasterLayerClipped.dataProvider()
                extentRasterLayerClipped = rasterLayerClipped.extent()

                #print(providerRasterLayerClipped)
                #xmin,ymax,xmax,ymin
                imageXminClip = (extentRasterLayerClipped.xMinimum())
                imageYminClip = (extentRasterLayerClipped.yMinimum())
                imageXmaxClip = (extentRasterLayerClipped.xMaximum())
                imageYmaxClip = (extentRasterLayerClipped.yMaximum())
                #origin
                imageXOriginClip = int(
                    round(extentRasterLayerClipped.xMinimum()))
                imageYOriginClip = int(
                    round(extentRasterLayerClipped.yMinimum()))
                #epsg

                proj4crs = rasterLayerClipped.crs()

                QgsMessageLog.logMessage(str(proj4crs.srsid()))
                QgsMessageLog.logMessage(str(proj4crs.toProj4()))
                QgsMessageLog.logMessage(str(proj4crs.authid()))
                QgsMessageLog.logMessage(str(proj4crs.description()))
                QgsMessageLog.logMessage(str(proj4crs.ellipsoidAcronym()))
                QgsMessageLog.logMessage(str(proj4crs.findMatchingProj()))
                QgsMessageLog.logMessage(str(proj4crs.postgisSrid()))
                QgsMessageLog.logMessage(str(proj4crs.toWkt()))

                epsgClip = proj4crs.postgisSrid()
                epsgWKTClip = proj4crs.toWkt()

                #QgsMapLayerRegistry.instance().addMapLayer(rasterLayerClipped)
                QgsProject.instance().addMapLayer(rasterLayerClipped)
                #pass

                self.dlg.statusBarProcessing.setValue(75)
                #copy vector mask
                outputFileMaskPath = os.path.join(temporalPath,
                                                  ouputFilenameVectorMask)
                #temporalPath.replace("/", "\\") + ouputFilenameVectorMask
                temporalVectorLayer = QgsVectorLayer(urlSourceVectorMaskSplit,
                                                     "tmp_polygon", "ogr")
                shutil.copyfile(urlSourceVectorMaskSplit[:-4] + '.shp',
                                os.path.join(outputFileMaskPath[:-4] + '.shp'))
                shutil.copyfile(urlSourceVectorMaskSplit[:-4] + '.dbf',
                                os.path.join(outputFileMaskPath[:-4] + '.dbf'))
                shutil.copyfile(urlSourceVectorMaskSplit[:-4] + '.shx',
                                os.path.join(outputFileMaskPath[:-4] + '.shx'))
                temporalVectorLayerDataProvider = temporalVectorLayer.dataProvider(
                )
                temporalVectorLayerCrs = temporalVectorLayerDataProvider.crs()
                temporalVectorLayerCrsString = temporalVectorLayerCrs.authid()
                temporalVectorLayerEPSGInt = int(
                    temporalVectorLayerCrsString[5:])

                QgsMessageLog.logMessage(str(temporalVectorLayerEPSGInt))
                maskVectorLayerExported = QgsVectorLayer(
                    outputFileMaskPath, ouputFilenameVectorMask[:-4], "ogr")
                crs = maskVectorLayerExported.crs()
                crs.createFromId(temporalVectorLayerEPSGInt)
                maskVectorLayerExported.setCrs(crs)
                maskVectorLayerExported.setCrs(
                    QgsCoordinateReferenceSystem(
                        temporalVectorLayerEPSGInt,
                        QgsCoordinateReferenceSystem.EpsgCrsId))

                styleBoundary = os.path.join(
                    (os.path.dirname(os.path.abspath(__file__))), 'styles',
                    'croprows_style_boundary.qml')
                maskVectorLayerExported.loadNamedStyle(styleBoundary)
                #QgsMapLayerRegistry.instance().addMapLayer(maskVectorLayerExported)
                QgsProject.instance().addMapLayer(maskVectorLayerExported)

                #end copy vector mask

                #TODO: try not to simulate process status, make it real
                for i in range(76, 90):
                    self.dlg.statusBarProcessing.setValue(i)

                #show step2 button
                self.dlg.btnExecuteProcessingFromApi.setVisible(True)

                self.dlg.statusBarProcessing.setValue(95)

                arrXMLOptions = [
                    str(seedValue),
                    str(ouputFilenameRasterClip),
                    str(ouputFilenameVectorMask),
                    str(pixelSizeXClip) + ',-' + str(pixelSizeYClip),
                    str(imageWClip) + ',' + str(imageHClip),
                    str(imageXminClip) + ',' + str(imageYminClip) + ',' +
                    str(imageXmaxClip) + ',' + str(imageYmaxClip),
                    str(imageXOriginClip) + ',' + str(imageYOriginClip),
                    str(epsgClip),
                    str(epsgWKTClip),
                    str(ouputFilenamePrj)
                ]

                #Write XML file
                self.writeXMLFile(ouputFilenameCropRowsProjectXML,
                                  arrXMLOptions)

                self.dlg.xmlCoreFile.setText(
                    str(ouputFilenameCropRowsProjectXML))

                self.dlg.statusBarProcessing.setValue(100)

                QApplication.setOverrideCursor(QtCore.Qt.ArrowCursor)

                self.flagClipTaskDone = 1

                toStep2Msg = QMessageBox.question(
                    None, "Crop Rows processing task start",
                    ("Are you sure that you want to start a <b>Crop Rows</b> processing task ?<br>Keep in mind this process can take a few minutes, even several hours.<br><br>Make sure that <b>Crop Rows - API Server is Running before continue.</b>"
                     ), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
                if toStep2Msg == QMessageBox.Yes:
                    QgsMessageLog.logMessage('Run Step 2')
                    self.executeCropRowsProcessingFromAPI()
                    pass
                else:
                    QMessageBox.information(
                        None, 'Message !',
                        "You must be run the processing task by manually way !<br>Just click on the button <b>Processing Task (manual)</b>",
                        QMessageBox.Ok)
                    pass
            else:
                QgsMessageLog.logMessage('No Mosaic Clip Process Selected')
                pass
        else:
            QgsMessageLog.logMessage('Missing Required Parameters')
            QgsMessageLog.logMessage('strMosaicRasterFileSelected: ' +
                                     strMosaicRasterFileSelected)
            QgsMessageLog.logMessage('strMaskVectorFileSelected: ' +
                                     strMaskVectorFileSelected)
            QgsMessageLog.logMessage('seedValue: ' + str(seedValue))
            QgsMessageLog.logMessage('flagClipTaskDone: ' +
                                     str(self.flagClipTaskDone))
            QMessageBox.critical(None, 'Error!',
                                 "Missing Required Parameter !",
                                 QMessageBox.Ok)
Пример #20
0
from qgis._core import QgsCoordinateTransform, QgsCoordinateReferenceSystem,\
    QgsProject
from qgis.core import QgsPointXY

x, y = -112.0, 13.0
crs = QgsCoordinateReferenceSystem(4326)  # wgs84
crsnuevo = QgsCoordinateReferenceSystem(26912)  # NAD 83 / UTM Zpne 12
trform = QgsCoordinateTransform(crs, crsnuevo, QgsProject.instance())
ptutm = trform.transform(QgsPointXY(x, y))
print("punto utm:", ptutm)
ptwgs = trform.transform(ptutm, QgsCoordinateTransform.ReverseTransform)
print("punto wgs:", ptwgs)
Пример #21
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)