Region Tool

This is a bit of python code that makes a tool for drawing rectangles on Qgis map canvasses and getting the coordinates out.

Download

Get this:
regionTool.py
and do an import regionTool somewhere.

Usage

I have a 'draw rectangle' button on my plugin's dialog. When clicked, the button calls this routine, which hides the dialog (self.a), then creates a new regionTool and sets it as the active tool on the canvas. It also saves the current tool so we can reset it once we've got our rectangle. Because map tools don't seem to be QObject things, I had to tack on a QObject object to my tool in order to do signals. This seems a bit odd. Maybe I screwed up. Anyway, here's the code:

   def updateBoundsFromRegion(self):
      self.a.hide()
      mc = self.iface.getMapCanvas()      
      self.r = regionTool.regionTool(mc)
      QObject.connect(self.r.o, SIGNAL("finished()"), self.doneRectangle)
      self.saveTool = mc.mapTool()
      mc.setMapTool(self.r)

When the rectangle is finished the tool emits the finished() signal, which is connected to this routine with the connect in the previous function:

  def doneRectangle(self):
      self.a.show()
      self.iface.getMapCanvas().setMapTool(self.saveTool)
      self.updateBounds(self.r.bb)

This shows the dialog back again and resets the map tool to the saved one. It then calls another method which processes the resulting rectangle - you need to write this for yourself to do whatever you want to do with the rectangle your user has just drawn - for example you may want to print the coordinates, or zoom to that region, or count the number of points in another coverage within that rectangle. Give your method a meaningful name and call it here. Mine is called 'updateBounds' because it updates the bounding rectangle that I will use for an analysis later.

Legal stuff

Ah, I think I wrote this, although the icon was ripped out of Qgis. But honestly, if you are a lawyer and are worried about that, please go to www.youtube.com and spot the copyright violations there.

(c) Barry Rowlingson 2007, Code is free for any re-use or modification.