[GIS] Arcpy zoom to selected features not working

arcgis-10.2arcpyzoom

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

Best Answer

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