Graphics Reference
In-Depth Information
Working with geospatial data in the
console
So far, we have used the QGIS Console as a glorified Python interpreter, running standard
Python programs and manipulating the QGIS user interface. But QGIS is a Geographical
Information System (GIS), and one of the main uses of a GIS is to manipulate and query
geospatial data. So, let's write some Python code to work with geospatial data directly
within the QGIS Console.
In the previous chapter, we loaded three shapefiles into a QGIS project using Python. Here
is a typical instruction we used to load a shapefile into a QGIS map layer:
layer = iface.addVectorLayer("/path/to/shapefile.shp",
"layer_name", "ogr")
While this is useful if you want to create a QGIS project programmatically, you may just
want to load a shapefile so you can analyze its contents, without putting the data into a map
layer. To do this, we have to get an appropriate data provider and ask it to open the
shapefile, like this:
registry = QgsProviderRegistry.instance()
provider = registry.provider("ogr","/path/to/shapefile.shp")
if not provider.isValid():
print "Invalid shapefile."
return
The isValid() method will return False if the shapefile cannot be loaded; this allows
us to fail gracefully if there is an error.
Once we have the data provider, we can ask it for the list of fields used to hold the attribute
values for each of the shapefile's features:
for field in provider.fields():
print field.name(), field.typeName()
We can also scan through the features within the shapefile using a Qg-
sFeatureRequest object. For example:
Search WWH ::




Custom Search