Using a different status bar CRS than the map

Sometimes, you may want to display a different coordinate system for the mouse coordinates in the status bar than what the source data is. With this recipe, you can set a different coordinate system without changing the data coordinate reference system or the CRS for the map.

Getting ready

Download the zipped shapefile and unzip it to your qgis_data/ms directory from the following:

https://geospatialpython.googlecode.com/files/MSCities_Geo.zip

How to do it...

We will load our layer, establish a message in the status bar, create a special event listener to transform the map coordinates at the mouse's location to our alternate CRS, and then connect the map signal for the mouse's map coordinates to our listener function. To do this, we need to perform the following steps:

  1. First, we need to import the Qt core library:
    from PyQt4.QtCore import *
    
  2. Then, we will set up the path to the shapefile and load it as a layer:
    pth = "/qgis_data/ms/MSCities_Geo_Pts.shp"
    lyr = QgsVectorLayer(pth, "Cities", "ogr")
    
  3. Now, we add the layer to the map:
    QgsMapLayerRegistry.instance().addMapLayer(lyr)
    
  4. Next, we create a default message that will be displayed in the status bar and will be replaced by the alternate coordinates later, when the event listener is active:
    msg = "Alternate CRS ( x: %s, y: %s )"
    
  5. Then, we display our default message in the left-hand side of the status bar as a placeholder:
    iface.mainWindow().statusBar().showMessage(msg % ("--", "--"))
    
  6. Now, we create our custom event-listener function to transform the mouse's map location to our custom CRS, which in this case is EPSG 3815:
    def listen_xyCoordinates(point):
        crsSrc = iface.mapCanvas().mapRenderer().destinationCrs()
        crsDest = QgsCoordinateReferenceSystem(3815)   
        xform = QgsCoordinateTransform(crsSrc, crsDest)
        xpoint = xform.transform(point)
        iface.mainWindow().statusBar().showMessage(msg % (xpoint.x(), xpoint.y()))
    
  7. Next, we connect the map canvas signal that is emitted when the mouse coordinates are updated to our custom event listener:
    QObject.connect(iface.mapCanvas(), SIGNAL("xyCoordinates(const QgsPoint &)"), listen_xyCoordinates)
    
  8. Finally, verify that when you move the mouse around the map, the status bar is updated with the transformed coordinates.

How it works...

The coordinate transformation engine in QGIS is very fast. Normally, QGIS tries to transform everything to WGS84 Geographic, but sometimes you need to view coordinates in a different reference system.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset