fcbassongis

Geometries from Javascript API to Python

Discussion created by fcbassongis Champion on Jan 28, 2016

I'm working on a geoprocessing tool to export my online web application's map graphics to any other format via ArcGIS Server.  I want to be able to send the geometries to the server and return a KML, Shapefile or whatever format I prefer.  Since there is no standard method in the API to convert geometries to other formats, I have created my own procedure.

 

An example of the list of geometries being sent from the web app to the server look like this with Web Mercator coordinates:

[
   [[2097634.02,-4008451.29],[2097514.11,-4008426.54],[2097543.19,-4008329.14],[2097671.5,-4008357.4],[2097634.02,-4008451.29]],
   ...
]

 

 

The geometries list is built on the web app side with the following function:

function exportGeometries(){
  var exportGeoms = '[';
  // each graphic feature geometry
  for (g=0; g <= map.graphics.graphics.length - 1; g++){
       exportGeoms += (g > 0 ? ',' : '');
       rings = map.graphics.graphics[g].geometry.rings;
       // each ring in the geometry
       polyring = '[';
       for (r=0; r <= rings.length - 1; r++){
            ring = rings[r];
            // each point in the ring
            for (pnt=0; pnt <= ring.length - 1; pnt++){
                 polyring += (pnt > 0 ? ',' : '');
                 polyring += '[' + ring[pnt][0] + ',' + ring[pnt][1] + ']';
            }
       }
       polyring += ']';
       exportGeoms += polyring;
  }
  exportGeoms += ']';
}

 

The Python script tool on the server side needs to be able to read the list of geometries.  Just using arcpy.GetParameter() to read the list of geometries as a list object is not sufficient, because Python receives it as a unicode object. I've found a python module (ast) that converts the unicode object to a standard list object that can be iterated in Python with a for loop to create a new feature class that can be converted:

 

import arcpy, ast
geometries = arcpy.GetParameter(0)
geomList = ast.literal_eval(geometries)

sr = arcpy.SpatialReference(102100)
newfc = arcpy.CreateFeatureclass_management(arcpy.env.scratchWorkspace, "webgeom", "POLYGON","","","",sr)
cur = arcpy.da.InsertCursor(newfc, ("SHAPE@"))

for polyring in geometries:
   array = arcpy.Array()
   for p in polyring:      
      array.add(arcpy.Point(p[0],p[1]))
   polygon = arcpy.Polygon(array,sr)
   cur.insertRow([polygon])   
)

 

The new Feature Class can now be converted to any other format with the standard toolbox tools.  The Python script can be integrated into the final model or script that is published as a GP service that saves the converted object on the web server and returns a URL link as output.

Outcomes