Tuesday, July 17, 2012

Create a Map Service Layer (10.1)

At 10.1, you can use JSON to create maps and add map services to that layer.  This means you can create map service layer indirectly.  There is no direct way to create a map service layer in 10.1, but by using the ConvertWebMapToMapDocument() you can.  Information about the function can be found here.


ConvertWebMapToMapDocument() described in the help is as follows:


Converts a web map (in JSON format) that you intend to print or export to a map document. The map document can be further modified before finally being printed or exported.


You notice that the help does not directly mention the creation of the map service layer, but when you drill down into the supported JSON syntax, you can see how you can use this method to generate your map service layer.


A JSON map consists of the following:

   "mapOptions": {}, 
   "operationalLayers": [], 
   "baseMap": [], 
   "exportOptions": {}, 
   "layoutOptions": {} 
}

Using the JSON library and dictionaries, you can easily match this structure. As shown below:
import json
from arcpy import mapping
mapService = {} 
operationalLayer = [] 
layer = {} 
layer["id"] = str(webmapID) 
layer["url"] = str(url) 
layer["title"] = str(title) 
layer["opacity"] = str(opacity) 
layer["visibility"] = str(visibility) 
layer["minScale"] = str(minScale) 
layer["maxScale"]= str(maxScale) 
operationalLayer.append(layer) 
mapService["operationalLayers"] = operationalLayer 
jsonDump = json.dumps(mapService) 
result = mapping.ConvertWebMapToMapDocument(jsonDump)

Now we have a MapDocument object that has our map service layer in it.  Using the other rmapping module functions, loop through the TOC and save the layer to disk.

mxd = result.mapDocument
layers = mapping.ListLayers(mxd)
for layer in layers:
    layer.saveACopy(saveLayer)
    break

That's it, now we have create a map service layer saved to disk.  If you have to deal with security, you can add a token to your operational layer.


Enjoy