Graphics Reference
In-Depth Information
We'll use this object to calculate the true length and area of the shapefile's features in
meters and square meters respectively.
We're now ready to scan through the contents of the shapefile, processing each feature in
turn:
for feature in
provider.getFeatures(QgsFeatureRequest()):
...
For each feature, we want to calculate a label that identifies that feature. We'll do this by
looking for an attribute called "name" , "NAME" , or "Name" , and using that attribute's
value as the feature label. If there is no attribute with one of these field names, we'll fall
back to using the feature's ID instead. Here is the relevant code:
if "name" in attr_names:
feature_label = feature.attribute("name")
elif "Name" in attr_names:
feature_label = feature.attribute("Name")
elif "NAME" in attr_names:
feature_label = feature.attribute("NAME")
else:
feature_label = str(feature.id())
Next, we need to obtain the geometry object associated with the feature. The geometry
object represents a polygon, line, or point. Getting a reference to the feature's underlying
geometry object is simple:
geometry = feature.geometry()
We can now use the QgsDistanceArea calculator we initialized earlier to calculate the
length of a line feature and the area of a polygon feature. To do this, we'll first have to
identify the type of feature we are dealing with:
if geometry.type() == QGis.Line:
...
elif geometry.type() == QGis.Polygon:
...
else:
...
Search WWH ::




Custom Search