[Qgis-developer] Getting center of layer in lat/long

Mark Coletti mcoletti at gmail.com
Mon Sep 8 14:36:55 PDT 2014


Ok, I figured it out on my own.  Here're the code snippets for computing
the center of a layer in geographic coordinates, and then doing the same
for the current viewport.

First by layer:

        layerCenter = layer.extent().center()

        if layer.crs().geographicFlag() : # if already lat/long, do nothing
            return layerCenter
        else :
            sourceCRC = layer.crs() # get the coordinate reference system
being used
            # 4326 is WGS 84
            coordinateTransform = QgsCoordinateTransform(sourceCRC.toWkt(),
QgsCoordinateReferenceSystem(4326).toWkt())
            return coordinateTransform.transform(layerCenter)

And now the center of the viewport in geographic coordinates:

        layerCenter = mapCanvas.extent().center()

        if mapCanvas.mapSettings().hasCrsTransformEnabled() : # if
projected, do inverse projection to geographic coordinates
            sourceCRC = mapCanvas.mapSettings().destinationCrs() # get the
coordinate reference system being used
            # 4326 is WGS 84
            coordinateTransform = QgsCoordinateTransform(sourceCRC.toWkt(),
QgsCoordinateReferenceSystem(4326).toWkt())
            inverseLayerCenter = coordinateTransform.transform(layerCenter)
            return inverseLayerCenter
        else :
            return layerCenter


Do you think these would make for good additions to the "Code Snippets"
section
<http://docs.qgis.org/2.2/en/docs/pyqgis_developer_cookbook/snippets.html>
for the online documentation?

Cheers,

Mark
-- 
mcoletti at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/qgis-developer/attachments/20140908/6447eee1/attachment.html>


More information about the Qgis-developer mailing list