Graphics Reference
In-Depth Information
Calculating the distance between two user-defined
points
In our final example of using the PyQGIS library, we'll write some code that, when run,
starts listening for mouse events from the user. If the user clicks on a point, drags the
mouse, and then releases the mouse button again, we will display the distance between
those two points. This is a good example of how to add your own map interaction logic to
QGIS, using the QgsMapTool class.
This is the basic structure for our QgsMapTool subclass:
class DistanceCalculator(QgsMapTool):
def __init__(self, iface):
QgsMapTool.__init__(self, iface.mapCanvas())
self.iface = iface
def canvasPressEvent(self, event):
...
def canvasReleaseEvent(self, event):
...
To make this map tool active, we'll create a new instance of it and pass it to the mapCan-
vas.setMapTool() method. Once this is done, our canvasPressEvent() and
canvasReleaseEvent() methods will be called whenever the user clicks or releases
the mouse button over the map canvas.
Let's start with the code that responds when the user clicks on the canvas. In this method,
we're going to convert from the pixel coordinates that the user clicked on to the corres-
ponding map coordinates (that is, a latitude and longitude value). We'll then remember
these coordinates so that we can refer to them later. Here is the necessary code:
def canvasPressEvent(self, event):
transform = self.iface.mapCanvas().getCoordinateTransform()
self._startPt = transform.toMapCoordinates(event.pos().x(),
event.pos().y())
Search WWH ::




Custom Search