HOW TO

Replace layers that source data from a local disk with feature service layers

Last Published: April 25, 2020

Summary

It is not possible to directly replace layers that source data from a local disk with a feature service layer. However, it is possible to recreate the layer as a feature service layer into a map document and insert the new layer into the map document using the arcpy.mapping method, InsertLayer(). The old layer can be removed by using the RemoveLayer() method.

 

Procedure

The following code sample demonstrates how to replace layers by iterating through the list of layers in a map document (mxd), using the InsertLayer() method to insert the designated layers and remove the desired layers using the RemoveLayer() method.
  1. Iterate through layers that reference feature services in a map document and save to layer files using the SaveToLayerFile method:
Import arcpy
#Set the workspace to the desired output layer files.
arcpy.env.workspace = r"D:\Cases\01800498_SourceFeatureService"
  
#Specify the desired map document.
mxd = arcpy.mapping.MapDocument("CURRENT")
 
#Create a Python list of layers in the mxd
layers = arcpy.mapping.ListLayers(mxd)
 
#Iterate through the layer list and create a layer file for each layer in the list.
for layer in layers:
    arcpy.SaveToLayerFile_management(layer,  layer.name)
  1. Create a list of available feature service layer files. The list can be created from the variable created in step 1, layers.
serviceList = []
for layer in layers:
    serviceList.append(layer.name)
  1. Iterate between the list, and replace the layers using the InsertLayer() and RemoveLayer() methods.
for layer in layers:
    if layer.name in serviceList:
        serviceLayer = arcpy.mapping.Layer(ws + "\\" + layer.name + ".lyr")
        arcpy.mapping.InsertLayer(df, layer, serviceLayer, "AFTER")
        arcpy.mapping.RemoveLayer(df, layer)





 

Article ID: 000013565

Software:
  • ArcMap

Receive notifications and find solutions for new or common issues

Get summarized answers and video solutions from our new AI chatbot.

Download the Esri Support App

Related Information

Discover more on this topic

Get help from ArcGIS experts

Contact technical support

Download the Esri Support App

Go to download options