Graphics Reference
In-Depth Information
for feature in provider.getFeatures(QgsFeatureRequest()):
print feature.attribute("name")
Of course, this is just a taste of what can be done using the QGIS libraries to query and
manipulate geospatial data. However, let's use what we've learned to build a simple pro-
gram that calculates and displays information about the contents of a shapefile. Shapefiles
hold geospatial features such as polygons, lines and points, and each feature can have any
number of attributes associated with it. We'll write a program that opens and scans
through a shapefile, identifying the features and calculating the length of each line feature
and the area of each polygon feature. We'll also calculate the total length and area across
all the features.
One of the challenges we'll have to deal with is the fact that the shapefile can be in any
map projection. This means that our calculation of the area and length has to take the map
projection into account; if, for example, we simply calculated the linear length of a feature
in a shapefile that uses the EPSG 4326 projection (that is, lat/long coordinates), then the
calculated length will be in degrees of latitude and longitude—which is a completely
meaningless figure. We'll want to calculate the feature lengths in kilometers, and the areas
in square kilometers. This is possible but requires us to do a bit more work.
Let's get started with our program. Start by creating a new Python script and enter the fol-
lowing:
from PyQt4.QtGui import *
To make the program easier to use, we're going to define a function and place all our pro-
gram logic inside this function, like this:
def analyze_shapefile():
...
analyze_shapefile()
Now, let's start writing the contents of the analyze_shapefile() function. So far,
we've been hardwiring the name of the shapefile, but this time, let's use QGIS's graphical
interface to prompt the user to select a shapefile:
def analyze_shapefile():
filename =
QFileDialog.getOpenFileName(iface.mainWindow(),
Search WWH ::




Custom Search