Python qgis.utils.iface.mapCanvas() Examples

The following are 18 code examples of qgis.utils.iface.mapCanvas(). 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.utils.iface , or try the search function .
Example #1
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 #2
Source File: script_editor_dialog.py    From qgis-processing-r with GNU General Public License v3.0 6 votes vote down vote up
def runAlgorithm(self):
        alg = RAlgorithm(description_file=None, script=self.editor.text())
        if alg.error is not None:
            error = QgsError(alg.error, "R")
            QgsErrorDialog.show(error,
                                self.tr("Execution error")
                                )
            return

        alg.setProvider(QgsApplication.processingRegistry().providerById("r"))
        alg.initAlgorithm()

        dlg = alg.createCustomParametersWidget(iface.mainWindow())
        if not dlg:
            dlg = AlgorithmDialog(alg, parent=iface.mainWindow())

        canvas = iface.mapCanvas()
        prevMapTool = canvas.mapTool()

        dlg.show()

        if canvas.mapTool() != prevMapTool:
            if canvas.mapTool():
                canvas.mapTool().reset()
            canvas.setMapTool(prevMapTool) 
Example #3
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 #4
Source File: Map.py    From qgis-earthengine-plugin with MIT License 6 votes vote down vote up
def getCenter():
    """
        Returns the coordinates at the center of the map.

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

        Uses:
            >>> from ee_plugin import Map
            >>> center = Map.getCenter()
            >>> Map.addLayer(center, { 'color': 'red' }, 'center')
    """
    center = iface.mapCanvas().center()

    crs = iface.mapCanvas().mapSettings().destinationCrs().authid()

    return ee.Geometry.Point([center.x(), center.y()], crs) 
Example #5
Source File: Map.py    From qgis-earthengine-plugin with MIT License 5 votes vote down vote up
def getScale():
    """
        Returns the approximate pixel scale of the current map view, in meters.

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

        Uses:
            >>> from ee_plugin import Map
            >>> print(Map.getScale())
    """

    return iface.mapCanvas().scale() / 1000 
Example #6
Source File: qgis-sample-QgsScaleWidget.py    From pyqgis-samples with GNU General Public License v2.0 5 votes vote down vote up
def on_scale_changed():
    print(scale_widget.scale(),
          QgsScaleWidget.toString(scale_widget.scale()))
    print(scale_widget.scaleString(),
          QgsScaleWidget.toDouble(scale_widget.scaleString()))
    print(scale_widget.showCurrentScaleButton())
    print("Scale changed")
    iface.mapCanvas().zoomScale(1 / scale_widget.scale()) 
Example #7
Source File: qgis-sample-QgsScaleComboBox.py    From pyqgis-samples with GNU General Public License v2.0 5 votes vote down vote up
def on_scale_changed():
    print(scale_box.scale(),
          QgsScaleComboBox.toString(scale_box.scale()))
    print(scale_box.scaleString(),
          QgsScaleComboBox.toDouble(scale_box.scaleString()))
    print("Scale changed")
    iface.mapCanvas().zoomScale(1 / scale_box.scale())

# The default values come from Options > Cartographic Tools, part Predefined scales 
Example #8
Source File: filterDialog.py    From DsgTools with GNU General Public License v2.0 5 votes vote down vote up
def layerNamesFromCanvas(self):
        """
        Gets all available layers from map canvas.
        :return: (list-of-str) map cointaing layer name to vector layer object.
        """
        return sorted([l.name() for l in iface.mapCanvas().layers()]) 
Example #9
Source File: Map.py    From qgis-earthengine-plugin with MIT License 5 votes vote down vote up
def getBounds(asGeoJSON=False):
    """
        Returns the bounds of the current map view, as a list in the format [west, south, east, north] in degrees.

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

        Uses:
            >>> from ee_plugin import Map
            >>> bounds = Map.getBounds(True)
            >>> Map.addLayer(bounds, {}, 'bounds')
    """
    ex = iface.mapCanvas().extent()
    # return ex
    xmax = ex.xMaximum()
    ymax = ex.yMaximum()
    xmin = ex.xMinimum()
    ymin = ex.yMinimum()

    # return as [west, south, east, north]
    if not asGeoJSON:
        return [xmin, ymin, xmax, ymax]

    # return as geometry
    crs = iface.mapCanvas().mapSettings().destinationCrs().authid()

    return ee.Geometry.Rectangle([xmin, ymin, xmax, ymax], crs, False) 
Example #10
Source File: Map.py    From qgis-earthengine-plugin with MIT License 5 votes vote down vote up
def centerObject(feature, zoom=None):
    """
        Centers the map view on a given object.

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

        Uses:
            >>> from ee_plugin import Map
            >>> Map.centerObject(feature)
    """


    feature = ee.Feature(feature)

    if not zoom:
        # make sure our geometry is in geo
        rect = feature.geometry().transform(ee.Projection('EPSG:4326'), 1)

        # get coordinates
        coords = rect.bounds().getInfo()['coordinates'][0]
        xmin = coords[0][0]
        ymin = coords[0][1]
        xmax = coords[2][0]
        ymax = coords[2][1]

        # construct QGIS geometry
        rect = QgsRectangle(xmin, ymin, xmax, ymax)

        # transform rect to a crs used by current project
        crs_src = QgsCoordinateReferenceSystem(4326)
        crs_dst = QgsCoordinateReferenceSystem(QgsProject.instance().crs())
        geo2proj = QgsCoordinateTransform(crs_src, crs_dst, QgsProject.instance())
        rect_proj = geo2proj.transform(rect)

        # center geometry
        iface.mapCanvas().zoomToFeatureExtent(rect_proj)
    else:
        # set map center to feature centroid at a specified zoom
        center = feature.geometry().centroid().coordinates().getInfo()
        setCenter(center[0], center[1], zoom) 
Example #11
Source File: gsexploreritems.py    From qgis-geoserver-plugin with GNU General Public License v2.0 5 votes vote down vote up
def editStyle(self, tree, explorer, gslayer = None):
        settings = QSettings()
        prjSetting = settings.value('/Projections/defaultBehaviour')
        settings.setValue('/Projections/defaultBehaviour', '')
        if gslayer is None:
            gslayer = getLayerFromStyle(self.element)
        if gslayer is not None:
            if not hasattr(gslayer.resource, "attributes"):
                QMessageBox.warning(explorer, "Edit style", "Editing raster layer styles is currently not supported")
                return
        sld = self.element.sld_body.decode()
        try:
            _sld = "\n".join([line for line in
                              xml.dom.minidom.parseString(sld).toprettyxml().splitlines() if line.strip()])
        except:
            self._showSldParsingError()
            return
        sld = adaptGsToQgs(sld)
        sldfile = tempFilename("sld")
        with open(sldfile, 'w') as f:
            f.write(sld)
        geomtype = getGeomTypeFromSld(sld)
        uri = geomtype + "?crs=epsg:4326&"
        if gslayer is not None:
            fields = gslayer.resource.attributes
            fieldsdesc = ['field=%s:double' % f for f in fields if "geom" not in f]
            fieldsstring = '&'.join(fieldsdesc)
            uri += fieldsstring
        layer = QgsVectorLayer(uri, "tmp", "memory")
        layer.loadSldStyle(sldfile)
        oldSld = getGsCompatibleSld(layer)[0]

        dlg = QgsRendererPropertiesDialog(layer, QgsStyle.defaultStyle())
        dlg.setMapCanvas(iface.mapCanvas())
        dlg.exec_()
        settings.setValue('/Projections/defaultBehaviour', prjSetting)
        newSld = getGsCompatibleSld(layer)[0]
        #TODO: we are not considering the possibility of the user selecting new svg markers,
        #      which would need to be uploaded
        if newSld != oldSld:
            explorer.run(self.element.update_body, "Update style", [], newSld) 
Example #12
Source File: extentpanel.py    From qgis-geoserver-plugin with GNU General Public License v2.0 5 votes vote down vote up
def setValueFromRect(self,r):
        s = str(r.xMinimum()) + "," + str(r.xMaximum()) + "," + str(r.yMinimum()) + "," + str(r.yMaximum())
        self.text.setText(s)
        self.tool.reset()
        canvas = iface.mapCanvas()
        canvas.setMapTool(self.prevMapTool)
        self.dialog.showNormal()
        self.dialog.raise_()
        self.dialog.activateWindow() 
Example #13
Source File: extentpanel.py    From qgis-geoserver-plugin with GNU General Public License v2.0 5 votes vote down vote up
def selectOnCanvas(self):
        canvas = iface.mapCanvas()
        canvas.setMapTool(self.tool)
        self.dialog.showMinimized() 
Example #14
Source File: extentpanel.py    From qgis-geoserver-plugin with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, dialog):
        super(ExtentSelectionPanel, self).__init__(None)
        self.dialog = dialog
        self.horizontalLayout = QHBoxLayout(self)
        self.horizontalLayout.setSpacing(2)
        self.horizontalLayout.setMargin(0)
        self.text = QLineEdit()
        if hasattr(self.text, 'setPlaceholderText'):
            self.text.setPlaceholderText("[xmin,xmax,ymin,ymax] Leave blank to use full extent")
        self.horizontalLayout.addWidget(self.text)
        self.pushButton = QPushButton()
        self.pushButton.setText("Define in canvas")
        self.pushButton.clicked.connect(self.selectOnCanvas)
        self.horizontalLayout.addWidget(self.pushButton)
        self.setLayout(self.horizontalLayout)
        canvas = iface.mapCanvas()
        self.prevMapTool = canvas.mapTool()
        self.tool = RectangleMapTool(canvas)
        self.tool.rectangleCreated.connect(self.fillCoords) 
Example #15
Source File: QgsVideo.py    From QGISFMV with GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, parent=None):
        ''' Constructor '''
        super().__init__(parent)
        self.surface = VideoWidgetSurface(self)
        self.setAttribute(Qt.WA_OpaquePaintEvent)

        self.Tracking_Video_RubberBand = QRubberBand(QRubberBand.Rectangle, self)
        self.Censure_RubberBand = QRubberBand(QRubberBand.Rectangle, self)

        color_blue = QColor(Qt.blue)
        color_black = QColor(Qt.black)
        color_amber = QColor(252, 215, 108)

        pal_blue = QPalette()
        pal_blue.setBrush(QPalette.Highlight, QBrush(color_blue))
        self.Tracking_Video_RubberBand.setPalette(pal_blue)

        pal_black = QPalette()
        pal_black.setBrush(QPalette.Highlight, QBrush(color_black))
        self.Censure_RubberBand.setPalette(pal_black)

        self._interaction = InteractionState()
        self._filterSatate = FilterState()

        self._isinit = False
        self._MGRS = False
        self.gt = None

        self.drawCesure = []
        self.poly_coordinates, self.drawPtPos, self.drawLines, self.drawMeasureDistance, self.drawMeasureArea, self.drawPolygon = [], [], [], [], [], []
        # Draw Polygon Canvas Rubberband
        self.poly_Canvas_RubberBand = QgsRubberBand(
            iface.mapCanvas(), True)  # Polygon type
        # set rubber band style
        self.poly_Canvas_RubberBand.setColor(color_amber)
        self.poly_Canvas_RubberBand.setWidth(3)

        # Tracking Canvas Rubberband
        self.Track_Canvas_RubberBand = QgsRubberBand(
            iface.mapCanvas(), QgsWkbTypes.LineGeometry)
        # set rubber band style
        self.Track_Canvas_RubberBand.setColor(color_blue)
        self.Track_Canvas_RubberBand.setWidth(5)

        # Cursor Canvas Rubberband
        self.Cursor_Canvas_RubberBand = QgsRubberBand(
            iface.mapCanvas(), QgsWkbTypes.PointGeometry)
        self.Cursor_Canvas_RubberBand.setWidth(4)
        self.Cursor_Canvas_RubberBand.setColor(QColor(255, 100, 100, 250))
        self.Cursor_Canvas_RubberBand.setIcon(QgsRubberBand.ICON_FULL_DIAMOND)

        self.parent = parent.parent()

        palette = self.palette()
        palette.setColor(QPalette.Background, Qt.transparent)
        self.setPalette(palette)

        self.origin, self.dragPos = QPoint(), QPoint()
        self.tapTimer = QBasicTimer()
        self.brush = QBrush(color_black)
        self.blue_Pen = QPen(color_blue, 3) 
Example #16
Source File: loadLayersFromPostgisAlgorithm.py    From DsgTools with GNU General Public License v2.0 4 votes vote down vote up
def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """
        host = self.parameterAsString(
            parameters,
            self.HOST,
            context
        )
        port = self.parameterAsString(
            parameters,
            self.PORT,
            context
        )
        database = self.parameterAsString(
            parameters,
            self.DATABASE,
            context
        )
        user = self.parameterAsString(
            parameters,
            self.USER,
            context
        )
        password = self.parameterAsString(
            parameters,
            self.PASSWORD,
            context
        )
        layerStringList = self.parameterAsString(
            parameters,
            self.LAYER_LIST,
            context
        )
        loadToCanvas = self.parameterAsBoolean(
            parameters,
            self.LOAD_TO_CANVAS,
            context
        )
        uniqueLoad = self.parameterAsBoolean(
            parameters,
            self.UNIQUE_LOAD,
            context
        )
        abstractDb = self.getAbstractDb(host, port, database, user, password)
        inputParamList = layerStringList.split(',')
        layerLoader = LayerLoaderFactory().makeLoader(
            iface, abstractDb
        )
        if loadToCanvas:
            iface.mapCanvas().freeze(True)
        outputLayers = layerLoader.loadLayersInsideProcessing(
            inputParamList,
            uniqueLoad=uniqueLoad,
            addToCanvas=loadToCanvas,
            feedback=feedback
        )
        if loadToCanvas:
            iface.mapCanvas().freeze(False)
        return {self.OUTPUT: [i.id() for i in outputLayers]} 
Example #17
Source File: groupLayersAlgorithm.py    From DsgTools with GNU General Public License v2.0 4 votes vote down vote up
def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """
        inputLyrList = self.parameterAsLayerList(
            parameters,
            self.INPUT_LAYERS,
            context
        )
        categoryExpression = self.parameterAsExpression(
            parameters,
            self.CATEGORY_EXPRESSION,
            context
        ) 
        listSize = len(inputLyrList)
        progressStep = 100/listSize if listSize else 0
        rootNode = QgsProject.instance().layerTreeRoot()
        inputLyrList.sort(key=lambda x: (x.geometryType(), x.name()))
        geometryNodeDict = {
            0 : self.tr('Point'),
            1 : self.tr('Line'),
            2 : self.tr('Polygon'),
            4 : self.tr('Non spatial')
        }
        iface.mapCanvas().freeze(True)
        for current, lyr in enumerate(inputLyrList):
            if feedback.isCanceled():
                break
            rootDatabaseNode = self.getLayerRootNode(lyr, rootNode)
            geometryNode = self.createGroup(
                geometryNodeDict[lyr.geometryType()],
                rootDatabaseNode
            )
            categoryNode = self.getLayerCategoryNode(
                lyr,
                geometryNode,
                categoryExpression
            )
            lyrNode = rootNode.findLayer(lyr.id())
            myClone = lyrNode.clone()
            categoryNode.addChildNode(myClone)
            # not thread safe, must set flag to FlagNoThreading
            rootNode.removeChildNode(lyrNode)
            feedback.setProgress(current*progressStep)
        iface.mapCanvas().freeze(False)
        return {self.OUTPUT: [i.id() for i in inputLyrList]} 
Example #18
Source File: sapLoadLayersAlgorithm.py    From DsgTools with GNU General Public License v2.0 4 votes vote down vote up
def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """
        host = self.parameterAsString(
            parameters,
            self.HOST,
            context
        )
        port = self.parameterAsString(
            parameters,
            self.PORT,
            context
        )
        database = self.parameterAsString(
            parameters,
            self.DATABASE,
            context
        )
        user = self.parameterAsString(
            parameters,
            self.USER,
            context
        )
        password = self.parameterAsString(
            parameters,
            self.PASSWORD,
            context
        )
        layerStringList = self.parameterAsString(
            parameters,
            self.LAYER_LIST,
            context
        )
        inputParamList = layerStringList.split(',')
        layerLoader = LayerLoaderFactory().makeLoader(
            iface, abstractDb
        )
        iface.mapCanvas().freeze(True)
        outputLayers = layerLoader.loadLayersInsideProcessing(
            inputParamList,
            uniqueLoad=True,
            addToCanvas=True,
            feedback=feedback
        )
        iface.mapCanvas().freeze(False)
        #TODO: Resto
        return {self.OUTPUT: [i.id() for i in outputLayers]}