GEOG 485:
GIS Programming and Automation

Lesson 3 Practice Exercise D Solution


Below is one possible approach to Lesson 3 Practice Exercise D. Notice that the city name is stored near the top of the script in a variable so that it can be tested with other values. The SQL expression takes a little bit of work to create due to the string query using two different types of quotes.

Note that the Python code colorizer below makes a mistake in line 11 and paints the variable targetCity green when it should be black.

# Selects park and ride facilities in a given target city and
#  exports them to a new feature class

import arcpy
targetCity = "Federal Way"     # Name of target city
arcpy.env.workspace = "C:\\data\\Geog485\\Lesson3PracticeExercises\\Lesson3PracticeExerciseD\\Washington.gdb"
parkAndRide = "ParkAndRide"    # Name of P & R feature class
cities = "CityBoundaries"      # Name of city feature class

# Set up the SQL expression of the query for the target city
cityQuery = '"NAME" = ' + "'" + targetCity + "'"

# Make feature layers for the cities and park and rides
arcpy.MakeFeatureLayer_management(cities, "CitiesLayer", cityQuery)
arcpy.MakeFeatureLayer_management(parkAndRide, "ParkAndRideLayer")

# Select all park and rides in the target city
arcpy.SelectLayerByLocation_management("ParkAndRideLayer", "CONTAINED_BY", "CitiesLayer")

# Copy the features to a new feature class and clean up
arcpy.CopyFeatures_management("ParkAndRideLayer", "TargetParkAndRideFacilities")


See the video below for some line-by-line commentary on the above solution: