Feature properties

You can get the first feature using the code as follows:

item=scf.getFeatures().next()

The previous code uses getFeatures().next() to get the first feature and assigns it to the item variable. If you remove the .next(), you get a QgsFeatureIterator, which allows you to iterate through all of the features. For the following examples we will use a single feature.

To get the geometry, assign it to a variable as shown:

g = item.geometry()

To get the type, you can use the following code:

g.type() 
0

The previous code returns 0 for points. Knowing that the features are points, we can see the coordinates using asPoint() as shown in the following code:

item.geometry().asPoint()
(-106.652,35.0912)

item.geometry().asPoint()[0]
-106.65153503418

item.geometry().asPoint()[1]
35.0912475585134

If we try the same code on the streets layer, we will get a type of 1 and the coordinates of the Polyline as shown in the following code:

street = streets.getFeatures().next().geometry().type()
1

street.geometry().asPolyline()
[(-106.729,35.1659), (-106.729,35.1659), (-106.729,35.1658), (-106.729,35.1658), (-106.73,35.1658), (-106.73,35.1658), (-106.73,35.1658), (-106.73,35.1658)]

To get information about the fields in the features, use fields() as shown in the following code:

item.fields().count()
4

You can get a field name and type by using .name() and .typeName() for each of the four fields. Using field 2, the following code will show you how to get the name and type:

item.fields()[2].name()
u'Type'
item.fields()[2].typeName()
u'String'

Knowing the name of the field, you can get the value of the field for the first record. Or, you could always use the numerical index as shown in the following code:

item["Type"]
u'Other'

item[0]
1572.0

item[1]
3368133L

item[2]
u'Other'

item[3]
u'Acknowledged'

Now that you know how to access the geometry and attributes of a feature, you can iterate through the features using getFeatures(). The following code will iterate through the features and print the ID of all of the records with a Status of 'Closed':

for f in scf.getFeatures():
if f["Status"]=='Closed':
print(f["ID"])

The previous code uses the getFeatures() to return an iterator. It then checks if the Status attribute is equal to 'Closed' and then prints the attribute ID if it is. The output is shown as follows:

 3888698
3906283
3906252
3882952
3904754
3904463
3904344
3904289
3903243
3903236
3902993
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset