Python qgis.core.QgsProject.instance() Examples

The following are 30 code examples of qgis.core.QgsProject.instance(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module qgis.core.QgsProject , or try the search function .
Example #1
Source File: azDigitizer.py    From qgis-shapetools-plugin with GNU General Public License v2.0 14 votes vote down vote up
def canvasPressEvent(self, event):
        """Capture the coordinate when the mouse button has been released."""
        pt = self.snappoint(event.originalPixelPoint())
        self.removeVertexMarker()
        if self.azDigitizerDialog is None:
            from .azDigitizer import AzDigitizerWidget
            self.azDigitizerDialog = AzDigitizerWidget(self.iface, self.iface.mainWindow())

        layer = self.iface.activeLayer()
        if layer is None or layer.wkbType() != QgsWkbTypes.Point:
            self.azDigitizerDialog.includeStartLabel.setEnabled(False)
            self.azDigitizerDialog.checkBox.setEnabled(False)
        else:
            self.azDigitizerDialog.includeStartLabel.setEnabled(True)
            self.azDigitizerDialog.checkBox.setEnabled(True)
        try:
            canvasCRS = self.canvas.mapSettings().destinationCrs()
            transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())
            pt4326 = transform.transform(pt.x(), pt.y())
            self.azDigitizerDialog.setPoint(pt4326)
            self.azDigitizerDialog.show()
        except Exception:
            self.iface.messageBar().pushMessage("", tr("Clicked location is invalid"), level=Qgis.Warning, duration=4) 
Example #2
Source File: Map.py    From qgis-earthengine-plugin with MIT License 8 votes vote down vote up
def setCenter(lon, lat, zoom=None):
    """
        Centers the map view at the given coordinates with the given zoom level. If no zoom level is provided, it uses the most recent zoom level on the map.

        https://developers.google.com/earth-engine/api_docs#map.setcenter

        Uses:
            >>> from ee_plugin import Map
            >>> Map.setCenter(lon, lat, zoom)
    """

    ### center
    center_point_in = QgsPointXY(lon, lat)
    # convert coordinates
    crsSrc = QgsCoordinateReferenceSystem(4326)  # WGS84
    crsDest = QgsCoordinateReferenceSystem(QgsProject.instance().crs())
    xform = QgsCoordinateTransform(crsSrc, crsDest, QgsProject.instance())
    # forward transformation: src -> dest
    center_point = xform.transform(center_point_in)
    iface.mapCanvas().setCenter(center_point)

    ### zoom
    if zoom is not None:
        # transform the zoom level to scale
        scale_value = 591657550.5 / 2 ** (zoom - 1)
        iface.mapCanvas().zoomScale(scale_value) 
Example #3
Source File: latLonTools.py    From qgis-latlontools-plugin with GNU General Public License v2.0 7 votes vote down vote up
def zoomTo(self, srcCrs, lat, lon):
        canvasCrs = self.canvas.mapSettings().destinationCrs()
        transform = QgsCoordinateTransform(srcCrs, canvasCrs, QgsProject.instance())
        x, y = transform.transform(float(lon), float(lat))

        rect = QgsRectangle(x, y, x, y)
        self.canvas.setExtent(rect)

        pt = QgsPointXY(x, y)
        self.highlight(pt)
        self.canvas.refresh()
        return pt 
Example #4
Source File: utm.py    From qgis-latlontools-plugin with GNU General Public License v2.0 7 votes vote down vote up
def utmString2Crs(utm, crs=epsg4326):
    parts = re.split(r'[\s]+', utm.upper())
    utmlen = len(parts)
    if utmlen == 3:
        m = re.findall(r'(\d+)([NS])', parts[0])
        if len(m) != 1 or len(m[0]) != 2:
            raise ValueError('Invalid UTM Coordinate')
        zone = int(m[0][0])
        hemisphere = m[0][1]
        easting = float(parts[1])
        northing = float(parts[2])
    elif utmlen == 4:
        if parts[1] != 'N' and parts[1] != 'S':
            raise ValueError('Invalid UTM Coordinate')
        zone = int(parts[0])
        easting = float(parts[2])
        northing = float(parts[3])
    else:
        raise ValueError('Invalid UTM Coordinate')
    if zone < 1 or zone > 60:
        raise ValueError('Invalid UTM Coordinate')

    utmcrs = QgsCoordinateReferenceSystem(utm_epsg_codes['{}{}'.format(zone, hemisphere)])
    pt = QgsPointXY(easting, northing)
    utmtrans = QgsCoordinateTransform(utmcrs, crs, QgsProject.instance())
    return(utmtrans.transform(pt)) 
Example #5
Source File: HydroSEDPluginUtils.py    From WMF with GNU General Public License v3.0 7 votes vote down vote up
def cargar_mapa_raster (self,pathMapaRaster):
    
        retornoCargaLayerMapaRaster = False
    
        pathMapaRaster = pathMapaRaster.strip ()
    
        if (os.path.exists (pathMapaRaster)):
    
            baseNameMapaRaster   = os.path.basename (pathMapaRaster)
            baseNameMapaRaster = os.path.splitext(baseNameMapaRaster)[0]
            layerMapaRaster = QgsRasterLayer (pathMapaRaster, baseNameMapaRaster)
            QgsProject.instance ().addMapLayer (layerMapaRaster)
    
            retornoCargaLayerMapaRaster = layerMapaRaster.isValid()
    
        return retornoCargaLayerMapaRaster 
Example #6
Source File: do_SourceDetailsRoads.py    From openoise-map with GNU General Public License v3.0 7 votes vote down vote up
def source_fields_update(self):

        source_layer = QgsProject.instance().mapLayersByName(self.layer_name)[0]
        source_layer_fields = list(source_layer.dataProvider().fields())

        source_layer_fields_labels = [""]

        for f in source_layer_fields:
#            if f.type() == QVariant.Int or f.type() == QVariant.Double:
                source_layer_fields_labels.append(str(f.name()))


        for comboBox in self.all_emission_comboBoxes:
            comboBox.clear()
            comboBox.setEnabled(False)

            comboBox.setLayer(source_layer)

        #load only fields type according to the required input
        for comboBox in self.decimal_comboBoxes:
            comboBox.setFilters(QgsFieldProxyModel.Numeric | QgsFieldProxyModel.Double | QgsFieldProxyModel.Int)
        for comboBox in self.int_comboBoxes:
            comboBox.setFilters(QgsFieldProxyModel.Numeric | QgsFieldProxyModel.Double | QgsFieldProxyModel.Int)
        for comboBox in self.string_comboBoxes:
            comboBox.setFilters(QgsFieldProxyModel.String) 
Example #7
Source File: snapWithLayerChooserWidget.py    From DsgTools with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, parameterDict={}, blackList=None, parent=None):
        """Constructor."""
        super(SnapWithLayerChooserWidget, self).__init__(parent=parent)
        self.parent = parent
        self.setupUi(self)
        self.project = QgsProject.instance()
        self.validKeys = ['layer', 'layerName', 'snap']
        self.snapDoubleSpinBox.setDecimals(20)
        self.snapDoubleSpinBox.setMaximum(1000000)
        self.snapDoubleSpinBox.setMinimum(0.00000000000000001)
        self.layerComboBox.setFilters(
            QgsMapLayerProxyModel.HasGeometry |
            QgsMapLayerProxyModel.VectorLayer
            )
        if blackList is not None:
            self.layerComboBox.setExceptedLayerList(blackList)
        if parameterDict != {}:
            self.populateInterface(parameterDict) 
Example #8
Source File: qgis_interface.py    From WMF with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, canvas):
        """Constructor
        :param canvas:
        """
        QObject.__init__(self)
        self.canvas = canvas
        # Set up slots so we can mimic the behaviour of QGIS when layers
        # are added.
        LOGGER.debug('Initialising canvas...')
        # noinspection PyArgumentList
        QgsProject.instance().layersAdded.connect(self.addLayers)
        # noinspection PyArgumentList
        QgsProject.instance().layerWasAdded.connect(self.addLayer)
        # noinspection PyArgumentList
        QgsProject.instance().removeAll.connect(self.removeAllLayers)

        # For processing module
        self.destCrs = None 
Example #9
Source File: captureCoordinate.py    From qgis-latlontools-plugin with GNU General Public License v2.0 6 votes vote down vote up
def canvasReleaseEvent(self, event):
        '''Capture the coordinate when the mouse button has been released,
        format it, and copy it to the clipboard. pt is QgsPointXY'''
        pt = self.snappoint(event.originalPixelPoint())
        self.removeVertexMarker()

        try:
            canvasCRS = self.canvas.mapSettings().destinationCrs()
            transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())
            pt4326 = transform.transform(pt.x(), pt.y())
            self.capturePoint.emit(pt4326)
        except Exception as e:
            pass 
Example #10
Source File: do_SourceDetailsPts.py    From openoise-map with GNU General Public License v3.0 6 votes vote down vote up
def source_fields_update(self):

        source_layer = QgsProject.instance().mapLayersByName(self.layer_name)[0]
        source_layer_fields = list(source_layer.dataProvider().fields())

        source_layer_fields_labels = [""]

        for f in source_layer_fields:
#            if f.type() == QVariant.Int or f.type() == QVariant.Double:
                source_layer_fields_labels.append(str(f.name()))


        for comboBox in self.all_emission_comboBoxes:
            comboBox.clear()
            comboBox.setEnabled(False)
            comboBox.setLayer(source_layer)

            comboBox.setFilters(QgsFieldProxyModel.Double | QgsFieldProxyModel.Int | QgsFieldProxyModel.Numeric)
            # for label in source_layer_fields_labels:
            #     comboBox.addItem(label) 
Example #11
Source File: Master Script Model.py    From GeoPythonConf2018-QGIS-Processing-Workshop with GNU General Public License v3.0 6 votes vote down vote up
def buffer_creation(self):
        answer = self.question("Buffer Creation", "Would you like to create a buffer?")
        if answer == QMessageBox.Yes:
            bufferNumber = self.inputDialog(2, "Buffer Creation", "How many buffers do you want to create?")
        for x in range(0, (bufferNumber[0])):
            
            layerInput = self.inputDialog(1, "Buffer %d" % (x+1), "Enter the name of your layer to be buffered: ")
            while ((layerInput[1] == True) and (len(QgsProject.instance().mapLayersByName(layerInput[0])) == 0)):
                self.information("Error", "There is no layer named " + layerInput[0] + "!")
                layerInput = self.inputDialog(1, "Buffer %d" % (x+1), "Enter the name of your layer to be buffered: ")
            if layerInput[1] == False:
                break
            layerName = layerInput[0]
            bufferDist = self.inputDialog(2, "Buffer %d" % (x+1), "Enter the distance to buffer: ")[0]
            param = { 'INPUT' : QgsProject.instance().mapLayersByName(layerName)[0], 'DISTANCE' : bufferDist, 'SEGMENTS' : 5, 'END_CAP_STYLE' : 0, 'JOIN_STYLE' : 0, 'MITER_LIMIT' : 2, 'DISSOLVE' : False, 'OUTPUT' : 'memory:' }
            bufferLayer = QgsProject.instance().addMapLayer(processing.run("qgis:buffer", param)['OUTPUT'])
            inputAnswer = self.inputDialog(1, "Layer Name", "Name the output buffer layer: ")
            if (inputAnswer[1] == True):
                bufferLayer.setName(inputAnswer[0]) 
Example #12
Source File: Master Script Model.py    From GeoPythonConf2018-QGIS-Processing-Workshop with GNU General Public License v3.0 6 votes vote down vote up
def old_buffer_creation(self):
        answer = self.question("Buffer Creation", "Would you like to create a buffer?")
        if answer == QMessageBox.Yes:
            bufferNumber = self.inputDialog(2, "Buffer Creation", "How many buffers do you want to create?")
            print("Input selected: " + str(bufferNumber[0]))
        for x in range(0, (bufferNumber[0])):
            
            layerName = self.inputDialog(1, "Buffer %d" % x, "Enter the name of your layer to be buffered: ")
            if (layerName[1] == QMessageBox.Cancel):
                break
            while (len(QgsProject.instance().mapLayersByName(layerName[0])) == 0):
                if (layerName[1] == QMessageBox.Cancel):
                    break
                self.information("Error", "There is no layer named " + layerName[0] + "!")
                layerName = self.inputDialog(1, "Buffer %d" % x, "Enter the name of your layer to be buffered: ")
            bufferDist = self.inputDialog(2, "Buffer %d" % x, "Enter the distance to buffer: ")[0]
            while (len(layerName) != 0):
                param = { 'INPUT' : QgsProject.instance().mapLayersByName(layerName[0])[0], 'DISTANCE' : bufferDist, 'SEGMENTS' : 5, 'END_CAP_STYLE' : 0, 'JOIN_STYLE' : 0, 'MITER_LIMIT' : 2, 'DISSOLVE' : False, 'OUTPUT' : 'memory:' }
                bufferLayer = QgsProject.instance().addMapLayer(processing.run("qgis:buffer", param)['OUTPUT'])
                inputAnswer = self.inputDialog(1, "Layer Name", "Name the output buffer layer: ")
                if (inputAnswer[1] == True):
                    bufferLayer.setName(inputAnswer[0])
                if (len(layerName) == 0):
                    self.information("Error!", "The layer name you gave does not exist! Try again!") 
Example #13
Source File: Master Script Model.py    From GeoPythonConf2018-QGIS-Processing-Workshop with GNU General Public License v3.0 6 votes vote down vote up
def perform_union(self):
        answer = self.question("Union Creation", "Would you like to union 2 layers?")
        if answer == QMessageBox.Yes:
            layer1 = self.inputDialog(1, "Layer 1", "Enter the name of your first/base layer: ")
            while ((layer1[1] == True) and (len(QgsProject.instance().mapLayersByName(layer1[0])) == 0)):
                self.information("Error", "There is no layer named " + layer1[0] + "!")
                layer1 = self.inputDialog(1, "Layer 1", "Enter the name of your first/base layer: ")
            if (layer1[1] == True):
                layer2 = self.inputDialog(1, "Layer 2", "Enter the name of your second/overlay layer: ")
                while ((layer2[1] == True) and (len(QgsProject.instance().mapLayersByName(layer2[0])) == 0)):
                    self.information("Error", "There is no layer named " + layer2[0] + "!")
                    layer2 = self.inputDialog(1, "Layer 2", "Enter the name of your second/overlay layer: ")
                if (layer2[1] == True):
                    param = { 'INPUT' : QgsProject.instance().mapLayersByName(layer1[0])[0], 'OVERLAY' : QgsProject.instance().mapLayersByName(layer2[0])[0], 'OUTPUT' : 'memory:' }
                    algoOutput = processing.run("qgis:union", param)
                    unionResult = QgsProject.instance().addMapLayer(algoOutput['OUTPUT'])
                    outputName = self.inputDialog(1, "Layer Name", "Name the output union layer: ")
                    if (outputName[1] == True):
                        unionResult.setName(outputName[0]) 
Example #14
Source File: utils.py    From qgis-earthengine-plugin with MIT License 6 votes vote down vote up
def update_ee_image_layer(image, layer, shown=True, opacity=1.0):
    check_version()

    url = "type=xyz&url=" + get_ee_image_url(image)

    provider = layer.dataProvider()
    msg = 'Updating layer with provider %s' % (type(provider).__name__, )
    QgsMessageLog.logMessage(msg, 'Earth Engine')

    provider.setDataSourceUri(url)
    provider.reloadData()
    layer.triggerRepaint()
    layer.reload()
    iface.mapCanvas().refresh()

    item = QgsProject.instance().layerTreeRoot().findLayer(layer.id())
    if not (shown is None):
        item.setItemVisibilityChecked(shown) 
Example #15
Source File: ee_plugin.py    From qgis-earthengine-plugin with MIT License 6 votes vote down vote up
def updateLayers(self):
        layers = QgsProject.instance().mapLayers().values()

        for l in filter(lambda layer: layer.customProperty('ee-layer'), layers):
            ee_object = l.customProperty('ee-object')
            ee_object_vis = l.customProperty('ee-object-vis')

            ee_object = ee.deserializer.fromJSON(ee_object)
            ee_object_vis = json.loads(ee_object_vis)
            
            # update loaded EE layer

            # get existing values for name, visibility, and opacity 
            # TODO: this should not be needed, refactor add_or_update_ee_layer to update_ee_layer
            name = l.name()
            shown = QgsProject.instance().layerTreeRoot().findLayer(l.id()).itemVisibilityChecked()
            opacity = l.renderer().opacity()

            utils.add_or_update_ee_layer(ee_object, ee_object_vis, name, shown, opacity) 
Example #16
Source File: searchDialog.py    From qgis-searchlayers-plugin with GNU General Public License v2.0 6 votes vote down vote up
def populateLayerListComboBox(self):
        '''Find all the vector layers and add them to the layer list
        that the user can select. In addition the user can search on all
        layers or all selected layers.'''
        layerlist = ['<All Layers>','<Selected Layers>']
        self.searchLayers = [None, None] # This is same size as layerlist
        layers = QgsProject.instance().mapLayers().values()
        
        for layer in layers:
            if layer.type() == QgsMapLayer.VectorLayer:
                layerlist.append(layer.name())
                self.searchLayers.append(layer)

        self.layerListComboBox.clear()
        self.layerListComboBox.addItems(layerlist)
        self.initFieldList() 
Example #17
Source File: qgis_interface.py    From qgis-processing-r with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, canvas: QgsMapCanvas):
        """Constructor
        :param canvas:
        """
        QObject.__init__(self)
        self.canvas = canvas
        # Set up slots so we can mimic the behaviour of QGIS when layers
        # are added.
        LOGGER.debug('Initialising canvas...')
        # noinspection PyArgumentList
        QgsProject.instance().layersAdded.connect(self.addLayers)
        # noinspection PyArgumentList
        QgsProject.instance().layerWasAdded.connect(self.addLayer)
        # noinspection PyArgumentList
        QgsProject.instance().removeAll.connect(self.removeAllLayers)

        # For processing module
        self.destCrs = None

        self.message_bar = QgsMessageBar() 
Example #18
Source File: searchDialog.py    From qgis-searchlayers-plugin with GNU General Public License v2.0 6 votes vote down vote up
def select_feature(self):
        '''A feature has been selected from the list so we need to select
        and zoom to it'''
        if self.noSelection:
            # We do not want this event while data is being changed
            return
        # Deselect all selections
        layers = QgsProject.instance().mapLayers().values()
        for layer in layers:
            if layer.type() == QgsMapLayer.VectorLayer:
                layer.removeSelection()
        # Find the layer that was selected and select the feature in the layer
        selectedRow = self.resultsTable.currentRow()
        selectedLayer = self.results[selectedRow][0]
        selectedFeature = self.results[selectedRow][1]
        selectedLayer.select(selectedFeature.id())
        # Zoom to the selected feature
        self.canvas.zoomToSelected(selectedLayer) 
Example #19
Source File: shapefileLayerLoader.py    From DsgTools with GNU General Public License v2.0 6 votes vote down vote up
def loadLayer(self, inputParam, parentNode, uniqueLoad, stylePath, domLayerDict):
        """
        Loads a layer
        :param lyrName: Layer nmae
        :param idSubgrupo: sub group id
        :param uniqueLoad: boolean to mark if the layer should only be loaded once
        :param stylePath: path to the styles used
        :param domLayerDict: domain dictionary
        :return:
        """
        lyrName, schema, geomColumn, tableName, srid = self.getParams(inputParam)
        lyr = self.checkLoaded(tableName)
        if uniqueLoad and lyr:
            return lyr
        self.setDataSource('', '_'.join([schema,tableName]), geomColumn, '')

        vlayer = QgsVectorLayer(self.uri.uri(), tableName, self.provider)
        QgsProject.instance().addMapLayer(vlayer, addToLegend = False)
        crs = QgsCoordinateReferenceSystem(int(srid), QgsCoordinateReferenceSystem.EpsgCrsId)
        vlayer.setCrs(crs)
        vlayer = self.setDomainsAndRestrictionsWithQml(vlayer)
        vlayer = self.setMulti(vlayer,domLayerDict)
        if stylePath:
            fullPath = self.getStyle(stylePath, tableName)
            if fullPath:
                vlayer.loadNamedStyle(fullPath, True)
        parentNode.addLayer(vlayer) 
        if not vlayer.isValid():
            QgsMessageLog.logMessage(vlayer.error().summary(), "DSGTools Plugin", Qgis.Critical)
        vlayer = self.createMeasureColumn(vlayer)
        return vlayer 
Example #20
Source File: searchDialog.py    From qgis-searchlayers-plugin with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, iface, parent):
        '''Initialize the LayerSearch dialog box'''
        super(LayerSearchDialog, self).__init__(parent)
        self.setupUi(self)
        self.iface = iface
        self.canvas = iface.mapCanvas()
        # Notify us when vector items ared added and removed in QGIS
        QgsProject.instance().layersAdded.connect(self.updateLayers)
        QgsProject.instance().layersRemoved.connect(self.updateLayers)
        
        self.doneButton.clicked.connect(self.closeDialog)
        self.stopButton.clicked.connect(self.killWorker)
        self.searchButton.clicked.connect(self.runSearch)
        self.clearButton.clicked.connect(self.clearResults)
        self.layerListComboBox.activated.connect(self.layerSelected)
        self.searchFieldComboBox.addItems(['<All Fields>'])
        self.maxResults = 1500
        self.resultsTable.setColumnCount(4)
        self.resultsTable.setSortingEnabled(False)
        self.resultsTable.setHorizontalHeaderLabels(['Value','Layer','Field','Feature Id'])
        self.resultsTable.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.comparisonComboBox.addItems(['=','contains','begins with'])
        self.resultsTable.itemSelectionChanged.connect(self.select_feature)
        self.worker = None 
Example #21
Source File: lineDigitizer.py    From qgis-shapetools-plugin with GNU General Public License v2.0 6 votes vote down vote up
def canvasPressEvent(self, event):
        '''Capture the coordinate when the mouse button has been released.'''
        pt = self.snappoint(event.originalPixelPoint())
        self.removeVertexMarker()
        layer = self.iface.activeLayer()
        if layer is None:
            return
        if self.lineDigitizerDialog is None:
            from .lineDigitizer import LineDigitizerWidget
            self.lineDigitizerDialog = LineDigitizerWidget(self.iface, self.iface.mainWindow())

        if layer.geometryType() == QgsWkbTypes.LineGeometry:
            self.lineDigitizerDialog.closeLineCheckBox.setEnabled(True)
        else:
            self.lineDigitizerDialog.closeLineCheckBox.setEnabled(False)
        try:
            canvasCRS = self.canvas.mapSettings().destinationCrs()
            transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance())
            pt4326 = transform.transform(pt.x(), pt.y())
            self.lineDigitizerDialog.setPoint(pt4326)
            self.lineDigitizerDialog.valuesTextEdit.clear()
            self.lineDigitizerDialog.show()
        except Exception:
            self.iface.messageBar().pushMessage("", tr("Clicked location is invalid"), level=Qgis.Warning, duration=4) 
Example #22
Source File: qgis_interface.py    From DataPlotly with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, canvas: QgsMapCanvas):
        """Constructor
        :param canvas:
        """
        QObject.__init__(self)
        self.canvas = canvas
        # Set up slots so we can mimic the behaviour of QGIS when layers
        # are added.
        LOGGER.debug('Initialising canvas...')
        # noinspection PyArgumentList
        QgsProject.instance().layersAdded.connect(self.addLayers)
        # noinspection PyArgumentList
        QgsProject.instance().layerWasAdded.connect(self.addLayer)
        # noinspection PyArgumentList
        QgsProject.instance().removeAll.connect(self.removeAllLayers)

        # For processing module
        self.destCrs = None

        self.message_bar = QgsMessageBar() 
Example #23
Source File: inspectFeatures.py    From DsgTools with GNU General Public License v2.0 6 votes vote down vote up
def zoomToLayer(self, layer, zoom = None):
        box = layer.boundingBoxOfSelected()
        if zoom is not None:
            box.grow(100-zoom)
        # Defining the crs from src and destiny
        epsg = self.iface.mapCanvas().mapSettings().destinationCrs().authid()
        crsDest = QgsCoordinateReferenceSystem(epsg)
        #getting srid from something like 'EPSG:31983'
        if not layer:
            layer = self.iface.mapCanvas().currentLayer()
        srid = layer.crs().authid()
        crsSrc = QgsCoordinateReferenceSystem(srid) #here we have to put authid, not srid
        # Creating a transformer
        coordinateTransformer = QgsCoordinateTransform(crsSrc, crsDest, QgsProject.instance())
        newBox = coordinateTransformer.transform(box)

        self.iface.mapCanvas().setExtent(newBox)
        self.iface.mapCanvas().refresh() 
Example #24
Source File: map_layer_config_widget.py    From qfieldsync with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, layer, canvas, parent):
        super(MapLayerConfigWidget, self).__init__(layer, canvas, parent)
        self.setupUi(self)
        self.layer_source = LayerSource(layer)
        self.project = QgsProject.instance()

        set_available_actions(self.layerActionComboBox, self.layer_source)

        self.isGeometryLockedCheckBox.setEnabled(self.layer_source.can_lock_geometry)
        self.isGeometryLockedCheckBox.setChecked(self.layer_source.is_geometry_locked)
        self.photoNamingTable = PhotoNamingTableWidget()
        self.photoNamingTable.addLayerFields(self.layer_source)
        self.photoNamingTable.setLayerColumnHidden(True)
        
        # insert the table as a second row only for vector layers
        if Qgis.QGIS_VERSION_INT >= 31300 and layer.type() == QgsMapLayer.VectorLayer:
            self.layout().insertRow(1, self.tr('Photo Naming'), self.photoNamingTable)
            self.photoNamingTable.setEnabled(self.photoNamingTable.rowCount() > 0) 
Example #25
Source File: mapillary_image_info.py    From go2mapillary with GNU General Public License v3.0 6 votes vote down vote up
def panToAction(self):
        crsCanvas = self.module.iface.mapCanvas().mapSettings().destinationCrs() # get current crs
        crsWGS84 = QgsCoordinateReferenceSystem(4326)  # WGS 84
        xform = QgsCoordinateTransform(crsWGS84, crsCanvas, QgsProject.instance())
        sourcePoint = QgsPointXY(float(self.field_longitude.text()),float(self.field_latitude.text()))
        self.module.iface.mapCanvas().setCenter(xform.transform(sourcePoint))
        self.module.iface.mapCanvas().refresh() 
Example #26
Source File: filterDialog.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def layerFromLayerName(self, layerName):
        """
        Gets vector layer object from its name.
        :param layerName: (str) 
        :return: (QgsVectorLayer) map cointaing layer name to vector layer object.
        """
        l = QgsProject.instance().mapLayersByName(layerName)
        return l[0] if l else None 
Example #27
Source File: spatialiteLayerLoader.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def loadLayer(self, inputParam, parentNode, uniqueLoad, stylePath, domLayerDict):
        """
        Loads a layer
        :param lyrName: Layer nmae
        :param idSubgrupo: sub group id
        :param uniqueLoad: boolean to mark if the layer should only be loaded once
        :param stylePath: path to the styles used
        :param domLayerDict: domain dictionary
        :return:
        """
        lyrName, schema, geomColumn, tableName, srid = self.getParams(inputParam)
        lyr = self.checkLoaded(tableName)
        if uniqueLoad and lyr:
            return lyr
        self.setDataSource('', '_'.join([schema,tableName]), geomColumn, '')

        vlayer = QgsVectorLayer(self.uri.uri(), tableName, self.provider)
        QgsProject.instance().addMapLayer(vlayer, addToLegend = False)
        crs = QgsCoordinateReferenceSystem(int(srid), QgsCoordinateReferenceSystem.EpsgCrsId)
        vlayer.setCrs(crs)
        vlayer = self.setDomainsAndRestrictionsWithQml(vlayer)
        vlayer = self.setMulti(vlayer,domLayerDict)
        if stylePath:
            fullPath = self.getStyle(stylePath, tableName)
            if fullPath:
                vlayer.loadNamedStyle(fullPath, True)
        parentNode.addLayer(vlayer) 
        if not vlayer.isValid():
            QgsMessageLog.logMessage(vlayer.error().summary(), "DSGTools Plugin", Qgis.Critical)
        vlayer = self.createMeasureColumn(vlayer)
        return vlayer 
Example #28
Source File: ee_plugin.py    From qgis-earthengine-plugin with MIT License 5 votes vote down vote up
def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface

        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)

        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'GoogleEarthEnginePlugin_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        self.menu_name_plugin = self.tr("Google Earth Engine Plugin")

        # Create and register the ee data provider
        provider.register_data_provider()

    # noinspection PyMethodMayBeStatic 
Example #29
Source File: orderedHierarchicalSnapLayerWidget.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def addItem(self, parameterDict=None):
        """
        1. Use super to instantiate parent's add item
        2. Connect new item's layerComboBox.currentIndexChanged signal to self.componentsRefresher
        """
        row = self.tableWidget.rowCount()
        if row < len(QgsProject.instance().mapLayers()):
            super(OrderedHierarchicalSnapLayerWidget, self).addItem(parameterDict=parameterDict)
            newItemWidget = self.tableWidget.cellWidget(row-1, 0)
            # if newItemWidget is not None:
            #     newItemWidget.layerComboBox.currentIndexChanged.connect(self.componentsRefresher)
            #     newItemWidget.layerComboBox.currentIndexChanged.emit(-1) 
Example #30
Source File: bdgexGuiManager.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def loadServiceLayer(self, legendName, service, layerList, serviceType='WMS'):
        urlWithParams = self.BDGExRequestHandler.get_url_string(service, layerList, serviceType)
        if not urlWithParams:
            return
        if serviceType == 'WMS':
            self.iface.addRasterLayer(urlWithParams, legendName, serviceType.lower())
        if serviceType == 'WFS':
            vlayer = QgsVectorLayer(urlWithParams, legendName, serviceType)
            QgsProject.instance().addMapLayer(vlayer)