当前位置: 首页>>代码示例>>Python>>正文


Python QgsMapCanvas.layerCount方法代码示例

本文整理汇总了Python中qgis.gui.QgsMapCanvas.layerCount方法的典型用法代码示例。如果您正苦于以下问题:Python QgsMapCanvas.layerCount方法的具体用法?Python QgsMapCanvas.layerCount怎么用?Python QgsMapCanvas.layerCount使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在qgis.gui.QgsMapCanvas的用法示例。


在下文中一共展示了QgsMapCanvas.layerCount方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: make_pdf

# 需要导入模块: from qgis.gui import QgsMapCanvas [as 别名]
# 或者: from qgis.gui.QgsMapCanvas import layerCount [as 别名]
def make_pdf():
    canvas = QgsMapCanvas()
    # Load our project
    QgsProject.instance().read(QFileInfo(project_path))
    bridge = QgsLayerTreeMapCanvasBridge(
        QgsProject.instance().layerTreeRoot(), canvas)
    bridge.setCanvasLayers()
    if canvas.layerCount() < 1:
        print 'No layers loaded from this project, exiting.'
        return
    print canvas.mapSettings().extent().toString()
    template_file = file(template_path)
    template_content = template_file.read()
    template_file.close()
    document = QDomDocument()
    document.setContent(template_content)
    composition = QgsComposition(canvas.mapSettings())
    # You can use this to replace any string like this [key]
    # in the template with a new value. e.g. to replace
    # [date] pass a map like this {'date': '1 Jan 2012'}
    substitution_map = {
        'DATE_TIME_START': TIME_START,
        'DATE_TIME_END': TIME_STOP}
    composition.loadFromTemplate(document, substitution_map)
    # You must set the id in the template
    map_item = composition.getComposerItemById('map')
    map_item.setMapCanvas(canvas)
    map_item.zoomToExtent(canvas.extent())
    # You must set the id in the template
    legend_item = composition.getComposerItemById('legend')
    legend_item.updateLegend()
    composition.refreshItems()
    composition.exportAsPDF(
        '/home/web/reports/pdf/%s/%s.pdf' % (TIME_SLICE, LABEL))
    QgsProject.instance().clear()
开发者ID:Jannes123,项目名称:watchkeeper,代码行数:37,代码来源:pdf_report_generator.py

示例2: ViewerWnd

# 需要导入模块: from qgis.gui import QgsMapCanvas [as 别名]
# 或者: from qgis.gui.QgsMapCanvas import layerCount [as 别名]

#.........这里部分代码省略.........
        self.LegendDock.setWidget(self.legend)
        self.LegendDock.setContentsMargins(0, 0, 0, 0)
        self.addDockWidget(Qt.BottomDockWidgetArea, self.LegendDock)

    def loadLayer(self, dictOpts):
        print "I: Loading the layer..."
        self.layerSRID = dictOpts["srid"]  # To access the SRID when querying layer properties

        if not self.isActiveWindow():
            self.activateWindow()
            self.raise_()

        if dictOpts["type"] == "vector":
            # QGIS connection
            uri = QgsDataSourceURI()
            uri.setConnection(dictOpts["-h"], dictOpts["-p"], dictOpts["-d"], dictOpts["-U"], dictOpts["-W"])
            uri.setDataSource(dictOpts["-s"], dictOpts["-t"], dictOpts["-g"])
            layer = QgsVectorLayer(uri.uri(), dictOpts["-s"] + "." + dictOpts["-t"], "postgres")
        elif dictOpts["type"] == "raster":
            connString = "PG: dbname=%s host=%s user=%s password=%s port=%s schema=%s table=%s" % (
                dictOpts["-d"],
                dictOpts["-h"],
                dictOpts["-U"],
                dictOpts["-W"],
                dictOpts["-p"],
                dictOpts["-s"],
                dictOpts["-t"],
            )
            layer = QgsRasterLayer(connString, dictOpts["-s"] + "." + dictOpts["-t"])
            layer.setNoDataValue(-32768)
            layer.rasterTransparency().initializeTransparentPixelList(-32768)

        if layer.isValid():
            if self.canvas.layerCount() == 0:
                self.canvas.setExtent(layer.extent())

                if dictOpts["srid"] != "-1":
                    print "I: Map SRS (EPSG): %s" % dictOpts["srid"]
                    self.canvas.setMapUnits(layer.srs().mapUnits())
                else:
                    print "I: Unknown Reference System"
                    self.canvas.setMapUnits(0)  # 0: QGis.Meters

            QgsMapLayerRegistry.instance().addMapLayer(layer)

    def getLayerProperties(self, l):
        """ Create a layer-properties string (l:layer)"""
        print "I: Generating layer properties..."
        if l.type() == 0:  # Vector
            wkbType = [
                "WKBUnknown",
                "WKBPoint",
                "WKBLineString",
                "WKBPolygon",
                "WKBMultiPoint",
                "WKBMultiLineString",
                "WKBMultiPolygon",
                "WKBNoGeometry",
                "WKBPoint25D",
                "WKBLineString25D",
                "WKBPolygon25D",
                "WKBMultiPoint25D",
                "WKBMultiLineString25D",
                "WKBMultiPolygon25D",
            ]
            properties = (
开发者ID:hjanetzek,项目名称:QgsPostGIS-Viewer,代码行数:70,代码来源:postgis_viewer.py

示例3: ViewerWnd

# 需要导入模块: from qgis.gui import QgsMapCanvas [as 别名]
# 或者: from qgis.gui.QgsMapCanvas import layerCount [as 别名]

#.........这里部分代码省略.........
        self.labelAbout.setText("<html><head/><body><a href=\"http://geotux.tuxfamily.org/index.php/en/geo-blogs/item/293-consola-sql-para-plugin-pgadmin-postgis-viewer\">PostGIS Layer Viewer</a> v.1.6.1 (2015.02.24)<br \><br \>" \
            "Copyright (c) 2010 Ivan Mincik,<br \>[email protected]<br \>" \
            u"Copyright (c) 2011-2015 Germán Carrillo,<br \>[email protected]<br \><br \>" \
            "<i>Licensed under the terms of GNU GPL v.2.0</i><br \><br \>" \
            "Based on PyQGIS. Plugin Fast SQL Layer by Pablo T. Carreira.</body></html>" )

    def loadLayer( self, dictOpts ):
        print 'I: Loading the layer...'
        self.layerSRID = dictOpts[ 'srid' ] # To access the SRID when querying layer properties

        if not self.isActiveWindow():
            self.activateWindow()            
            self.raise_() 

        if dictOpts['type'] == 'vector':
            # QGIS connection
            uri = QgsDataSourceURI()
            uri.setConnection( dictOpts['-h'], dictOpts['-p'], dictOpts['-d'], 
                dictOpts['-U'], dictOpts['-W'] )
            uri.setDataSource( dictOpts['-s'], dictOpts['-t'], dictOpts['-g'] )
            layer = QgsVectorLayer( uri.uri(), dictOpts['-s'] + '.' + dictOpts['-t'],
                "postgres" )        
        elif dictOpts['type'] == 'raster':          
            connString = "PG: dbname=%s host=%s user=%s password=%s port=%s mode=2 " \
                "schema=%s column=%s table=%s" % ( dictOpts['-d'], dictOpts['-h'], 
                dictOpts['-U'], dictOpts['-W'], dictOpts['-p'], dictOpts['-s'], 
                dictOpts['col'], dictOpts['-t'] )
            layer = QgsRasterLayer( connString, dictOpts['-s'] + '.' + dictOpts['-t'] )
            
            if layer.isValid():
                layer.setContrastEnhancement( QgsContrastEnhancement.StretchToMinimumMaximum )

        self.addLayer( layer, self.layerSRID )

    def addLayer( self, layer, srid='-1' ):
        if layer.isValid():
            # Only in case that srid != -1, read the layer SRS properties, otherwise don't since it will return 4326
            if srid != '-1': 
               self.layerSRID = layer.crs().description() + ' (' + str( layer.crs().postgisSrid() ) + ')'
            else:
               self.layerSRID = 'Unknown SRS (-1)'

            if self.canvas.layerCount() == 0:
                self.canvas.setExtent( layer.extent() )

                if srid != '-1':
                    print 'I: Map SRS (EPSG): %s' % self.layerSRID                    
                    self.canvas.setMapUnits( layer.crs().mapUnits() )
                else:
                    print 'I: Unknown Reference System'
                    self.canvas.setMapUnits( 0 ) # 0: QGis.Meters

            return QgsMapLayerRegistry.instance().addMapLayer( layer )
        return False

    def activeLayer( self ):
        """ Returns the active layer in the layer list widget """
        return self.legend.activeLayer()

    def getLayerProperties( self, l ):
        """ Create a layer-properties string (l:layer)"""
        print 'I: Generating layer properties...'
        if l.type() == 0: # Vector
            wkbType = ["WKBUnknown","WKBPoint","WKBLineString","WKBPolygon",
                       "WKBMultiPoint","WKBMultiLineString","WKBMultiPolygon",
                       "WKBNoGeometry","WKBPoint25D","WKBLineString25D","WKBPolygon25D",
                       "WKBMultiPoint25D","WKBMultiLineString25D","WKBMultiPolygon25D"]
            properties = "Source: %s\n" \
                         "Geometry type: %s\n" \
                         "Number of features: %s\n" \
                         "Number of fields: %s\n" \
                         "SRS (EPSG): %s\n" \
                         "Extent: %s " \
                          % ( l.source(), wkbType[l.wkbType()], l.featureCount(), 
                              l.dataProvider().fields().count(), self.layerSRID, 
                              l.extent().toString() )
        elif l.type() == 1: # Raster
            rType = [ "GrayOrUndefined (single band)", "Palette (single band)", "Multiband", "ColorLayer" ]
            properties = "Source: %s\n" \
                         "Raster type: %s\n" \
                         "Width-Height (pixels): %sx%s\n" \
                         "Bands: %s\n" \
                         "SRS (EPSG): %s\n" \
                         "Extent: %s" \
                         % ( l.source(), rType[l.rasterType()], l.width(), l.height(),
                             l.bandCount(), self.layerSRID, l.extent().toString() )

        self.layerSRID = '-1' # Initialize the srid 
        return properties

    def changeScale( self, scale ):
        self.lblScale.setText( "Scale 1:" + formatNumber( scale ) )

    def updateXY( self, p ):
        if self.canvas.mapUnits() == 2: # Degrees
            self.lblXY.setText( formatToDegrees( p.x() ) + " | " \
                + formatToDegrees( p.y() ) )
        else: # Unidad lineal
            self.lblXY.setText( formatNumber( p.x() ) + " | " \
                + formatNumber( p.y() ) + "" )
开发者ID:jivechang,项目名称:postgis-layer-viewer,代码行数:104,代码来源:postgis_viewer.py

示例4: PdfMaker

# 需要导入模块: from qgis.gui import QgsMapCanvas [as 别名]
# 或者: from qgis.gui.QgsMapCanvas import layerCount [as 别名]
class PdfMaker(object):
    """A generator that takes a QGIS project file and a layout template and makes a pdf."""

    def __init__(self, template_path, debug=False):
        """Constructor.

        :param template_path: Absolute path to a QGIS composer template file.
        :type template_path: str
        """
        gui_flag = True
        self.app = QgsApplication(sys.argv, gui_flag)

        # Make sure QGIS_PREFIX_PATH is set in your env if needed!
        self.app.initQgis()

        if debug:
            print QgsProviderRegistry.instance().pluginList()

        self.canvas = QgsMapCanvas()
        self.canvas.enableAntiAliasing(True)

        self.template_path = template_path

    def __del__(self):
        """Destructor."""
        del self.app

    def _load_template(self):
        """Load the template.

        :return: QgsComposition containing the loaded template.
        :rtype: QgsComposition
        """
        template_file = file(self.template_path)
        template_content = template_file.read()
        template_file.close()
        document = QDomDocument()
        document.setContent(template_content)
        composition = QgsComposition(self.canvas.mapSettings())
        # You can use this to replace any string like this [key]
        # in the template with a new value. e.g. to replace
        # [date] pass a map like this {'date': '1 Jan 2012'}
        substitution_map = {
            'DATE_TIME_START': 'foo',
            'DATE_TIME_END': 'bar'}
        composition.loadFromTemplate(document, substitution_map)
        return composition

    def _load_layers(self):
        """Manually load all the layers for our project.

        :return: A list of QgsMapLayer instances.
        :rtype: list
        """
        layers = []

        # First the RW layer

        host = 'db'
        port = '5432'
        user = 'docker'
        password = 'docker'
        dbname = 'gis'
        uri = QgsDataSourceURI()
        uri.setConnection(host, port, dbname, user, password)

        schema = 'public'
        table = 'flood_mapper_rw'
        geometry_column = 'geometry'
        where_clause = ''
        title = 'RW'
        uri.setDataSource(schema, table, geometry_column, where_clause)
        layer = QgsVectorLayer(uri.uri(), title, 'postgres')

        QgsMapLayerRegistry.instance().addMapLayer(layer, False)
        canvas_layer = QgsMapCanvasLayer(layer)
        layers.append(canvas_layer)

        # Now the JK layer
        path = './data/jk.shp'
        title = 'JK'
        layer = QgsVectorLayer(path, title, 'ogr')
        QgsMapLayerRegistry.instance().addMapLayer(layer, False)
        canvas_layer = QgsMapCanvasLayer(layer)
        layers.append(canvas_layer)

        return layers

    def make_pdf(self, pdf_path):
        """Generate a pdf for the given project and template files.

        :param pdf_path: Absolute path for the output PDF file.
        :type pdf_path: str

        """

        layers = self._load_layers()
        self.canvas.setLayerSet(layers)

        if self.canvas.layerCount() < 1:
#.........这里部分代码省略.........
开发者ID:Jannes123,项目名称:watchkeeper,代码行数:103,代码来源:pdf_report_generator_manual.py


注:本文中的qgis.gui.QgsMapCanvas.layerCount方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。