Graphics Reference
In-Depth Information
When the canvasReleaseEvent() method is called, we'll want to do the same with
the point at which the user released the mouse button:
def canvasReleaseEvent(self, event):
transform =
self.iface.mapCanvas().getCoordinateTransform()
endPt = transform.toMapCoordinates(event.pos().x(),
event.pos().y())
Now that we have the two desired coordinates, we'll want to calculate the distance
between them. We can do this using a QgsDistanceArea object:
crs =
self.iface.mapCanvas().mapRenderer().destinationCrs()
distance_calc = QgsDistanceArea()
distance_calc.setSourceCrs(crs)
distance_calc.setEllipsoid(crs.ellipsoidAcronym())
distance_calc.setEllipsoidalMode(crs.geographicFlag())
distance = distance_calc.measureLine([self._startPt,
endPt]) / 1000
Notice that we divide the resulting value by 1000. This is because the Qg-
sDistanceArea object returns the distance in meters, and we want to display the dis-
tance in kilometers.
Finally, we'll display the calculated distance in the QGIS message bar:
messageBar = self.iface.messageBar()
messageBar.pushMessage("Distance = %d km" % distance,
level=QgsMessageBar.INFO,
duration=2)
Now that we've created our map tool, we need to activate it. We can do this by adding the
following to the end of our script:
calculator = DistanceCalculator(iface)
iface.mapCanvas().setMapTool(calculator)
Search WWH ::




Custom Search