Tuesday, 30 June 2015

zoom - Choosing and zooming to features using SQL query in ArcPy with ArcGIS Pro?


When using ArcPy with the ArcGIS 10.x architecture there is a simple coding pattern that I find I use frequently:


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

df = arcpy.mapping.ListDataFrames(mxd,"Layers")[0]
lyr = arcpy.mapping.ListLayers(mxd,"ne_10m_admin_0_countries",df)[0]
lyr.definitionQuery = '"ADMIN" = ' + "'Chile'"
df.extent = lyr.getSelectedExtent()
arcpy.RefreshActiveView()

To see it in action:



  1. Start ArcMap with a Blank map

  2. Add a layer using a shapefile like ne_10m_admin_0_countries.shp from Natural Earth


  3. Copy/paste the code above into the Python window and you should see the country of Chile zoomed to


However, when I try to do something similar using ArcPy with ArcGIS Pro what I find is:



  1. Start ArcGIS Pro

  2. Choose Map.aptx to open a map

  3. Add a layer using a shapefile like ne_10m_admin_0_countries.shp from Natural Earth

  4. Copy/paste code like below into the Python pane


The definition query works great but then the Map class does not have a method available to perform a zoom to the extent of the features thus defined.



import arcpy
aprx = arcpy.mp.ArcGISProject("CURRENT")
mapx = aprx.listMaps("Map")[0]
lyr = mapx.listLayers("ne_10m_admin_0_countries")[0]
lyr.definitionQuery = '"ADMIN" = ' + "'Chile'"

Is there a simple way to choose and zoom to features using an SQL query in ArcPy with ArcGIS Pro?


As a workaround I've been investigating how to perhaps incorporate Layout and MapFrame classes into my coding pattern and, although the latter has a zoomToAllLayers method that looks more hopeful, I have not yet been able to find a way to do this.



Answer



I can't see a way of doing this using the Map class either.



The code below works, but you're required to have a Layout and Map Frame present in your Project. It's strange that you can't do this in the Map view because you're able to right click on the layer in the Contents pane and click Zoom to Layer, but not through arcpy?


The zooming for the following code actually occurs on the Layout view, and not the Map view.


import arcpy

aprx = arcpy.mp.ArcGISProject("CURRENT")
mapx = aprx.listMaps("Map")[0]
lyr = mapx.listLayers("ne_10m_admin_0_countries")[0]
lyr.definitionQuery = '"ADMIN" = ' + "'Chile'"

lyt = aprx.listLayouts()[0]

mf = lyt.listElements('MAPFRAME_ELEMENT')[0]

mf.camera.setExtent(mf.getLayerExtent(lyr, False, True))

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...