1

Alright here I go again this forum has been good to me. I add a layer and replace its data with a shapefile I created using the following bit of python:

layer = arcpy.mapping.Layer("C:/GIS/images.lyr")
arcpy.mapping.AddLayer(df, layer)
lyr = arcpy.mapping.ListLayers(mxd,"images",df)[0]
lyr.replaceDataSource(projectlocation+projectname+"/Aerial/"+"/"+projectdate,"SHAPEFILE_WORKSPACE","images")
lyr.name = "Images"

I cannot figure out how to set the extents of the mxd to the new source data I can just get it to set it to the original extents of the shp the .lyr from saved from. Any help is greatly appreciated.

1
2

You should be able to just add this line after the code you have in your question.

df.extent = lyr.getSelectedExtent()

If that does not work let me know and I will set up a test.

1
  • That just seems to set the extent to full extents (I have a grid that covers all of western canada and I am trying to set the extents of my mxd that I create to just a point layer that I add). Thank you for the pointer though.
    – jtgis
    May 15 '13 at 14:11
2

My first thoughts were also about lyr.getExtent() but what if you do it this way? Get the source of the layer and describe it.

lyrdesc = arcpy.Describe(lyr)
source = lyrdesc.catalogPath
shpdesc = arcpy.Describe(source)

df.extent = shpdesc.extent

If neither of these work there may be an issue with the extent of the new shp you are adding.

Edit: Actually you could probably just do this and not need to do the .catalogPath stuff. Probably a slightly cleaner option but both have the same effect, though not really much difference.

shpdir = projectlocation + projectname + "/Aerial//" + projectdate
lyr.replaceDataSource(shpdir, "SHAPEFILE_WORKSPACE", "images")
shpdesc = arcpy.Describe(shpdir + "//images.shp")
df.extent = shpdesc.extent

Not sure how the variables are named in the rest of your code, but the slashes might be off in mine, depending on that.

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.