I'm writing a python script to automatically take some snapshots of my ArcMap in 10.2, but I can't get the zoom to selected features tool to work properly.

I have a layer called carereport, which I then make a feature layer of by providing a gid value. If I right-click on this new layer and click 'Zoom to layer', the tool works fine. But when I run the following arcpy script, it stays very zoomed out. It's as if some other features are selected, but I can't see where.

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

arcpy.MakeFeatureLayer_management("carereport", "Siteslyr", """gid = 2739""")

addLayer = arcpy.mapping.Layer(r"Siteslyr")
arcpy.mapping.AddLayer(df, addLayer, "AUTO_ARRANGE")


lyr = arcpy.mapping.ListLayers(mxd, "Siteslyr", df)[0]

df.scale *= 1.1
arcpy.mapping.ExportToJPEG(mxd, r"C:\caredev.jpg", df,
del mxd, df

Your code is not actually selecting anything, you are making a subset view of your data with the MakeFeatureLayer tool.

You need to run the selectbyattribute tool on your layer.

The desktop help suggests if you want to zoom to selected features in a specific layer you should use this code:

df.extent = lyr.getSelectedExtent()

This now zooms in:

mxd = arcpy.mapping.MapDocument('CURRENT')
df = arcpy.mapping.ListDataFrames(mxd, "Layers") [0]
lyr = arcpy.mapping.ListLayers(mxd, "Siteslyr", df)[0]
arcpy.SelectLayerByAttribute_management(lyr, "NEW_SELECTION", ' "gid" = 2739 ')
  • 1
    Refreshing the view could be needed : arcpy.RefreshActiveView() – Marc_Alx Feb 24 '17 at 8:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.