Using a spatial filter to select features

This example uses the Natural Earth Dataset introduced in Chapter 4Data Types, Storage, and Conversion, under the Reading and writing vector data with GeoPandas section. We'll use latitude-longitude coordinates to create a spatial filter in the form of a bounding box. This box selects only the data inside of this box. This is a way to work with a subset of our data. We'll use OGR's SpatialFilterRec method, which takes four values—minx, miny, maxx and maxy, to create a bounding box. Our (random) example is to select the cities in our bounding box (which shows the state of Texas, as well as parts of Oklahoma and Mexico). To filter our results even further, we only want the cities in the US. This means we have to filter our search results with an extra if/else statement in our for loop.

The website www.mapsofworld.com gives the following four values for our example code: -102 (minx), 26 (miny), -94 (maxx), and 36 (maxy) for the state of Texas. Here is the script:

In: # import the modules
from osgeo import ogr
import os
# reference the shapefile and specify driver type
shapefile =
r"C:datagdalNE10m_cultural e_10m_populated_places.shp"
driver = ogr.GetDriverByName("ESRI Shapefile")
# open the data source with driver, zero means open in read-only
mode
dataSource = driver.Open(shapefile, 0)
# use the GetLayer() function for referencing the layer that holds
the data
layer = dataSource.GetLayer()
# pass in the coordinates for the data frame to the
SetSpatialFilterRect() function. This filter creates a rectangular
extent and selects the features
inside the extent
layer.SetSpatialFilterRect(-102, 26, -94, 36)
for feature in layer:
# select only the cities inside of the USA
# we can do this through a SQL query:
# we skip the cities that are not in the USA,
# and print the names of the cities that are
if feature.GetField("ADM0NAME") != "United States of
America":
continue
else:
print(feature.GetField("NAME"))

Out: Ardmore
McAlester
Bryan
San Marcos
Longview
..................Content has been hidden....................

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