0

I'm creating a tool that when you type in the city name it will select the city, zoom in and label it. I have the zoom and label working but can't figure out the SQL Query needed to select the city I type in the tool in ArcMap. My code in below.

I'm still new at this

import arcpy as ARCPY

def citySelect():

    mxd = ARCPY.mapping.MapDocument("CURRENT")
    df = ARCPY.mapping.ListDataFrames(mxd)[0]
    city = ARCPY.GetParameter(0)
    cities = ("N:/Lab13/Lab13/cities.lyr")
    ARCPY.SelectLayerByAttribute_management("cities", "NEW_SELECTION",''' "CITY_NAME" = ' city ' ''')
    print city[0]
    layers = arcpy.mapping.ListLayers(mxd, "", df)
    citiesLayer = layers[0]
    df.zoomToSelectedFeatures()
    citiesLayer.showLabels =True
    ARCPY.RefreshActiveView()

citySelect()
2
  • 1
    You have a different potential issue too. You have a variable cities which is pointing to a layer file, but SelectLayerByAttribute_management uses a quoted string "cities" which implies you're have access to a layer straight from the map table of contents--which may not be available depending on the context of how you are running this. Commented May 2, 2015 at 0:14
  • This is an aside to your issue, but I think import arcpy as ARCPY makes your code awkward to read when everyone here seems to use the simpler import arcpy. Commented May 2, 2015 at 3:20

2 Answers 2

3

The call to SelectLayerByAttribute could be handled like this: ARCPY.SelectLayerByAttribute_management('cities', "NEW_SELECTION", "CITY_NAME = '{}'".format(city))

1
  • Ok thanks for the response! I'm going to try to get to the lab to try it tomorrow Commented May 2, 2015 at 1:25
0

I think you should use arcpy.GetParameterAsText(0) to pull in the city name and guarantee that it is a string.

You can then print it to confirm its name before using it in SelectLayerByAttribute.

Changing:

ARCPY.SelectLayerByAttribute_management("cities", "NEW_SELECTION",''' "CITY_NAME" = ' city ' ''')

to:

ARCPY.SelectLayerByAttribute_management("cities", "NEW_SELECTION",'"CITY_NAME" = ' + "'" + city + "'")

should then work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.