4

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")

arcpy.RefreshActiveView()
arcpy.RefreshTOC()

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

df.scale *= 1.1
arcpy.RefreshActiveView()
arcpy.mapping.ExportToJPEG(mxd, r"C:\caredev.jpg", df,
                           df_export_width=1600,
                           df_export_height=1200,
                           world_file=True)
del mxd, df
8

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()
6

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 ')
df.zoomToSelectedFeatures()
  • 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.