Creating a City Select and Zoom tool using arcpy

2750
7
05-02-2016 10:03 AM
GarrettPullis
New Contributor II

Working on creating a lab which will allow me to type in a city name into a parameter and it will select that city, add it to the TOC and zoom into it. I'm having trouble getting around certain errors. Please help!

import arcpy

from arcpy import mapping

#set workspace

mxd = arcpy.mapping.MapDocument("CURRENT")

#set the dataframe

df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]

cities = arcpy.mapping.ListLayers(mxd, "Cities")[0]

#Establish variables

cityName = arcpy.GetParameterAsText(0)

#Set variable as the parameter for the city search

arcpy.SelectLayerByAttribute_management("Cities", "NEW_SELECTION", " CITY_NAME = 'cityName' ")

df.zoomToSelectedFeatures()

arcpy.RefreshActiveView()

0 Kudos
7 Replies
DanPatterson_Retired
MVP Emeritus

Garrett

Code Formatting... the basics++

And the error messages you are getting would be useful, it could be in a number of those lines.

0 Kudos
WesMiller
Regular Contributor III
import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")
#set the dataframe
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
cities = arcpy.mapping.ListLayers(mxd, "Cities")[0]
#Establish variables
cityName = arcpy.GetParameterAsText(0)
#Set variable as the parameter for the city search
arcpy.SelectLayerByAttribute_management(cities, "NEW_SELECTION", "CITY_NAME = '{}' ".format(cityName))
df.zoomToSelectedFeatures()
arcpy.RefreshActiveView()
0 Kudos
GarrettPullis
New Contributor II

The interesting thing was I wasn't receiving any errors. The script would

run through and complete, but nothing would happen in ArcMap. Prior to that

there was an error saying GetParameter wasn't defined. Besides that it

runs, but nothing happens.

0 Kudos
AdrianWelsh
MVP Honored Contributor

Garrett,

If it isn't doing anything, can you tell if the active view got refreshed? After you run the script, are your items being selected (maybe manually refresh your view just to see)?

0 Kudos
GarrettPullis
New Contributor II

The only thing that we were able to make it do was select all the cities

rather than the one particular city that we input

0 Kudos
WesMiller
Regular Contributor III

Change this line

cityName = arcpy.GetParameterAsText(0)

to

cityName = 'A Known City Name'

0 Kudos
WesMiller
Regular Contributor III

In your original script this line

arcpy.SelectLayerByAttribute_management("Cities", "NEW_SELECTION", " CITY_NAME = 'cityName' ")

would have run successful without selecting anything unless you have a value of 'cityName'

This line

cityName = arcpy.GetParameterAsText(0)

is used for an external variable most common would be model builder

0 Kudos