Graphics Reference
In-Depth Information
Now, let's replace the GeometryInfoMapTool.canvasReleaseEvent() method
with code to identify the feature the user clicked on. Here's the necessary code:
def canvasReleaseEvent(self, event):
found_features = self.identify(event.x(), event.y(),
self.TopDownStopAtFirst,
self.VectorLayer)
if len(found_features) > 0:
layer = found_features[0].mLayer
feature = found_features[0].mFeature
geometry = feature.geometry()
As you can see, we call QgsMapToolIdentify.identify() to see which feature
the user clicked on. The parameters we're using tell the method to only return the top-most
vector feature at the point where the user clicked; the identify() method can also re-
turn all features at a given point or the pixel value if the user clicked on a raster layer, but
in our case, we only want the top-most vector feature.
Once we've found the clicked-on feature, we identify which map layer the feature is on,
and extract the feature's geometry. With this information, we can analyze the geometry
and display the calculated statistics, which is the whole purpose of our plugin.
A QGSGeometry object can represent a point, a line, a polygon, a number of points, a
number of lines, a number of polygons, or a collection of different types of geometries. To
analyze the statistics for any QGSGeometry object, we have to be ready to handle all
these different types of geometries. Fortunately, the basic logic is quite straightforward:
• If the geometry has multiple parts, we split the geometry into its component parts,
and process each part in turn
• For point geometries, we count the number of points
• For line geometries, we count the number of lines and calculate their total length
• For polygon geometries, we count the number of polygons and calculate their
total area and perimeter
Let's add two methods to our GeometryInfoMapTool class to analyze a geometry:
def analyzeGeometry(self, geometry, layer, info):
crs = layer.dataProvider().crs()
calculator = QgsDistanceArea()
calculator.setSourceCrs(crs)
Search WWH ::




Custom Search