Select to view content in your preferred language

Geoprocessing Service from Python Toolbox to create a web map?

797
1
08-30-2013 07:47 AM
ionarawilson1
Deactivated User
Hi guys, I have created a python toolbox for 8 tools. One of the tools calculates a plan id based on the county where the polygon is drawn and the year from a date entered by the user.

I would like to create a web app with all these tools. My web app already has editing capabilities and the feature service created for these tools can be already be edited in the web app.

But I need to calculate that PlanID field (the field is already in the database), so I am guessing I need to convert my toolbox script to a geoprocessing service.

If so, how can I do that, since I already have the editor part working in the web app, so I don't need that part of the script to enter the data, just the part that after getting the data, it calculates the planid based on the county where the polygon created is. Here is the python tool script ( I deleted some parts like some of the parameters and messages so it would fit here)
What would I need to change in my code for it to work? Can you please take a look at the python code and give me some advice on what to do? Any idea, or general idea on where to go from here would be awesome! The javascript code is in the following post.
Thank you!!!

class Stewardship(object):
    
    def getParameterInfo(self):
        """Define parameter definitions"""
    

        param1 = arcpy.Parameter(
        displayName = "Forester",
       
        name = "Forester",
        datatype = "String",
        parameterType = "Required",
       
        direction = "Input"
        )

              

        params = [param0, param1, param2, param3, param4, param5, param6, param7, param8, param9, 

param10, param11, param12, param13, param14]
        return params
   
    def execute(self, parameters, messages):
      
            
              
        Status =  parameters[2].valueAsText
        DateStart =  parameters[3].valueAsText
       

# This is to send the data input to the database
        with arcpy.da.UpdateCursor("Stewardship", ("Status", "Office", "Forester", 

"DateStart","PlanLength", "PlanEQIP", "RecipientLast", "RecipientFirst",
     "MailAddress", "City" , "State", "ZipCode", "Phone", "Email", "Underserved")) as rows:
        # row comes back as a tuple in the order specified here, so Office is row[0], Forester is row[1]
            for row in rows:
                row[0] = StatusCode
                row[1] = OfficeCode
             rows.updateRow(row)
        
       

# This is to save only the year to the FFY field from the DateStart field
        with arcpy.da.UpdateCursor("Stewardship", ("FFY")) as rows:
      
            Datestarstr1 = str(DateStart)

            arcpy.AddMessage(Datestarstr1)
            if len(Datestarstr1) == 9:
            # if for example 6/28/2013 or 10/4/2013
                yearonly = DateStart[5:9]


            if len(Datestarstr1) == 8:
                yearonly = DateStart[4:8]
            if len(Datestarstr1) > 9:
             # if for example 10/10/2013
                yearonly = DateStart[6:10]

                
            for row in rows:
                row[0] = yearonly


                rows.updateRow(row)
        
        

# This is to create centroids of the stewardship boundaries to select the county that contains the 

centroid (stewardship), to be used to create the PlanID

        Countieslayer = 'Counties FL'  # this is a string that represents the Counties feature layer
        Stewardshiplayer = 'Stewardship FL'  # this is a string that represents the Stewardship feature 

layer
        Stewardshipcentroidslayer = 'Stewardship centroid FL'  # this is a string that represents the 

Stewardship feature layer
        if arcpy.Exists(Countieslayer):
            arcpy.Delete_management(Countieslayer)
            # make feature layer
        arcpy.MakeFeatureLayer_management("Counties", "Countieslayer")

        if arcpy.Exists(Stewardshiplayer):
            arcpy.Delete_management(Stewardshiplayer)
            # make feature layer
        arcpy.MakeFeatureLayer_management("Stewardship", "Stewardshiplayer")


create the layer after creating centroids
        outstewardshipcentroids = "StewardshipCentroids2"
     
        if arcpy.Exists(outstewardshipcentroids):
            arcpy.Delete_management(outstewardshipcentroids)
            # make feature layer
        # Create centroid
        arcpy.FeatureToPoint_management("Stewardshiplayer",  outstewardshipcentroids,"INSIDE")

        if arcpy.Exists("Stewardshipcentroidslayer"):
            arcpy.Delete_management("Stewardshipcentroidslayer")
            # make feature layer
        arcpy.MakeFeatureLayer_management(outstewardshipcentroids, "Stewardshipcentroidslayer")

        arcpy.SelectLayerByLocation_management("Countieslayer", "CONTAINS", outstewardshipcentroids, "", 

"NEW_SELECTION")

    # To get the code of the county from the counties layer to send it to the County field in 

Stewardship
        # Takes the first row of the cursor (there is only one object in the county centroid).
        # The first index is the first row, the next [0] index is the first attribute, which there is 

only one (FIPS_TXT)
        countycode = tuple(arcpy.da.SearchCursor("Countieslayer", "FIPS_TXT"))[0][0]
        urows = arcpy.da.UpdateCursor("StewardshipLayer", "County")
        for urow in urows:
            urow[0] = countycode
            urows.updateRow(urow)

        del urows, urow
        
    # To add 1 to the year if month starts in October

        import time
        from datetime import datetime, date
        #sim_date_counter = 1

        with arcpy.da.UpdateCursor("Stewardshiplayer", ("FFY")) as rows:
          for row in rows:
            #get the value of the date

            FFY = row[0]
            FFYnumber = int(FFY)
            #convert to string
            DateStartstr = str(DateStart)
            arcpy.AddMessage(DateStartstr)
            # Get only the month
            # To get only the first two characters:
            DateStart2 = DateStartstr[0:2]
            arcpy.AddMessage(DateStart2)
            if "/" in DateStart2:
                        # if for example 6/28/2013
                    DateStart3 = DateStart[0:1]
                    FFYnumbercount = FFYnumber
                    arcpy.AddMessage(DateStart3)
                    arcpy.AddMessage(FFYnumbercount)
            if "/" not in DateStart2:
                 # if for example 10/10/2013
                DateStart4 = int(DateStart2)
                FFYnumbercount = FFYnumber + 1

                arcpy.AddMessage(DateStart4)
                arcpy.AddMessage(FFYnumbercount)
            row[0] = str(FFYnumbercount)

            rows.updateRow(row)
        
        trows = arcpy.SearchCursor("Stewardshiplayer")

        for row in trows:

                   FFYtxt = row.getValue("FFY")
                   Countytxt = row.getValue("County")
      
        del trows, row

    # we list the layer to create a layer feature without a selection (because it is selected by the 

user)
        lyr = arcpy.mapping.ListLayers(arcpy.mapping.MapDocument('CURRENT'), 'Stewardship')[0]

        arcpy.MakeFeatureLayer_management(lyr.dataSource, "TMP")
    # To get the total ammount of records, not only the selected
        result = int(arcpy.GetCount_management("TMP").getOutput(0))


    # write a query to get the county and year using the FFY and County of the object id of the 

Stewardship layer (the one that is selected)

        query = "FFY" +"=" + "'"+ str(FFYtxt)+"'" + "AND " + "County" +"=" + "'"+ str(Countytxt)+"'"

        # select all the records that have the FFYcounty the same as the FFYCounty of the hightest 

ObjectID
        arcpy.SelectLayerByAttribute_management("TMP",  "NEW_SELECTION", query )
        result = int(arcpy.GetCount_management("TMP").getOutput(0))


    # if there are more than 1 records with the same ffy and county
        # select only the record witht the highest sequencenumber (sort first, then select)
        if  result > 1:
            maxValue4 = arcpy.SearchCursor("TMP", "", "", "", "SequenceNumber D").next().getValue

("SequenceNumber")
  
            query = "SequenceNumber = "
            arcpy.SelectLayerByAttribute_management("TMP",  "SUBSET_SELECTION", "SequenceNumber = " + 

str(maxValue4))
            result = int(arcpy.GetCount_management("TMP").getOutput(0))


    #  to get the sequence number
        
        rows = arcpy.SearchCursor("TMP")

        for row in rows:

               Seqnum = row.SequenceNumber
               
        del rows, row

    # If the sequence number is equal or higher than 1 it means there are other records with the same 

FFY and County, so we add 1 to the number
       # rows = arcpy.UpdateCursor("Stewardshiplayer")


        with arcpy.da.UpdateCursor("Stewardshiplayer", ("Sequencenumber")) as rows:


            if Seqnum >= 1:
   
                    vsn = Seqnum + 1
            else:
 
                    vsn = 1
            for row in rows:


            #get the value of the date


               row[0] = vsn

               rows.updateRow(row)
    
    # we Create the Plan ID concatenating the FFY, the county and the Sequence number, adding zeros in 

front of the sequence number if necessary to make the lenght always 3
        with arcpy.da.UpdateCursor("Stewardship", ("PlanID")) as rowsffycounty2:
            for row in rowsffycounty2:
                row[0] = str(FFYtxt) + "-" + str(Countytxt) + "-" + str(vsn).zfill(3)

                rowsffycounty2.updateRow(row)

        

        
    
        return

0 Kudos
1 Reply
ionarawilson1
Deactivated User
And here is the javascript with the editor and the feature service:

[HTML]
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=7, IE=9, IE=10">
    <!--The viewport meta tag is used to improve the presentation and behavior of the samples
      on iOS devices-->
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
    <title>SARS JAVA SCRIPT TEST</title>

    <link rel="stylesheet" href="http://js.arcgis.com/3.6/js/dojo/dijit/themes/claro/claro.css">
    <link rel="stylesheet" href="http://js.arcgis.com/3.6/js/esri/css/esri.css" />
    <style>
      html,body{height:100%;width:100%;margin:0;overflow:hidden;}
      #map{
        padding:0;
      }
      #header{
        font-size: 1.1em;
        font-family: sans-serif;
        padding-left: 1em;
        padding-top:4px;
        color:#660000;
      }
      .templatePicker {
        border: none;
      }

      .dj_ie .infowindow .window .top .right .user .content { position: relative; }
      .dj_ie .simpleInfoWindow .content {position: relative;}
    </style>
   
    <script src="http://js.arcgis.com/3.6/"></script>
    <script>
      var map;
     
      require([
        "esri/map", "esri/dijit/BasemapGallery", "esri/arcgis/utils",

        "esri/toolbars/edit",

        "esri/layers/ArcGISTiledMapServiceLayer",
        "esri/layers/FeatureLayer",

        "esri/symbols/SimpleMarkerSymbol",
        "esri/symbols/SimpleLineSymbol",

        "esri/dijit/editing/Editor",
        "esri/dijit/editing/TemplatePicker",

        "esri/config",
        "dojo/i18n!esri/nls/jsapi",

        "dojo/_base/array", "dojo/parser", "dojo/keys",

        "dijit/layout/BorderContainer", "dijit/layout/ContentPane", "dijit/TitlePane",

        "dojo/domReady!"
      ], function(
        Map, BasemapGallery, arcgisUtils, Edit,
        ArcGISTiledMapServiceLayer, FeatureLayer,
        SimpleMarkerSymbol, SimpleLineSymbol,
        Editor, TemplatePicker,
        esriConfig, jsapiBundle,
        arrayUtils, parser, keys
      ) {
        parser.parse();      

        // snapping is enabled for this sample - change the tooltip to reflect this
        jsapiBundle.toolbars.draw.start = jsapiBundle.toolbars.draw.start +  "<br>Press <b>ALT</b> to enable snapping";
      
        // refer to "Using the Proxy Page" for more information:  https://developers.arcgis.com/en/javascript/jshelp/ags_proxy.html
        esriConfig.defaults.io.proxyUrl = "/proxy";   

        //This service is for development and testing purposes only. We recommend that you create your own geometry service for use within your applications.
        esriConfig.defaults.geometryService = new esri.tasks.GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");
       
        map = new Map("map", {
          basemap: "hybrid",
        
          center: [-98.57, 30.98],
          zoom: 6,
          slider: true
        });
 
  map.on("layers-add-result", initEditor);
 
  
      
        //add boundaries and place names
  /*      var labels = new ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer");
        map.addLayer(labels);*/

        var rivers = new FeatureLayer("http://tfsgis-iisd01:6080/arcgis/rest/services/SARS_AUG13/SARS_AUG13/FeatureServer/1",{
          mode: FeatureLayer.MODE_ONDEMAND,
          outFields: ['*']
        });

        var waterbodies = new FeatureLayer("http://tfsgis-iisd01:6080/arcgis/rest/services/SARS_AUG13/SARS_AUG13/FeatureServer/0",{
          mode: FeatureLayer.MODE_ONDEMAND,
          outFields: ['*']
        });


        map.addLayers([waterbodies,rivers]);

        function initEditor(evt) {

          var templateLayers = arrayUtils.map(evt.layers, function(result){
            return result.layer;
          });
          var templatePicker = new TemplatePicker({
            featureLayers: templateLayers,
            grouping: true,
            rows: "auto",
            columns: 3
          }, "templateDiv");
          templatePicker.startup();

          var layers = arrayUtils.map(evt.layers, function(result) {
            return { featureLayer: result.layer };
          });
          var settings = {
            map: map,
            templatePicker: templatePicker,
            layerInfos: layers,
            toolbarVisible: true,
            createOptions: {
              polylineDrawTools:[ Editor.CREATE_TOOL_FREEHAND_POLYLINE ],
              polygonDrawTools: [ Editor.CREATE_TOOL_FREEHAND_POLYGON,
                Editor.CREATE_TOOL_CIRCLE,
                Editor.CREATE_TOOL_TRIANGLE,
                Editor.CREATE_TOOL_RECTANGLE
              ]
            },
            toolbarOptions: {
              reshapeVisible: true
            }
          };

          var params = {settings: settings};   
          var myEditor = new Editor(params,'editorDiv');
          //define snapping options
          var symbol = new SimpleMarkerSymbol(
            SimpleMarkerSymbol.STYLE_CROSS,
            15,
            new SimpleLineSymbol(
              SimpleLineSymbol.STYLE_SOLID,
              new Color([255, 0, 0, 0.5]),
              5
            ),
            null
          );
          map.enableSnapping({
            snapPointSymbol: symbol,
            tolerance: 20,
            snapKey: keys.ALT
          });
   
          myEditor.startup();
        }
 
  //add the basemap gallery, in this case we'll display maps from ArcGIS.com including bing maps
        var basemapGallery = new BasemapGallery({
          showArcGISBasemaps: true,
          map: map
        }, "basemapGallery");
        basemapGallery.startup();
       
        basemapGallery.on("error", function(msg) {
          console.log("basemap gallery error:  ", msg);
        });
      });
    </script>
  </head>
  <body class="claro">
    <div id="main" data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design:'headline'" style="height:width:100%;height:100%;">
      <div data-dojo-type="dijit/layout/ContentPane" id="header" data-dojo-props="region:'top'">
       Spatial Accomplishment Report System
      </div>
      <div data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'left'" style="width: 300px;overflow:hidden;">
        <div id="templateDiv"></div>
        <div id="editorDiv"></div>
      </div>
      <div data-dojo-type="dijit/layout/ContentPane" id="map" data-dojo-props="region:'center'">
     <div style="position:absolute; right:22px; top:23px; z-Index:999;">
          <div data-dojo-type="dijit/TitlePane"
               data-dojo-props="title:'Switch Basemap', closable:false,  open:false">
            <div data-dojo-type="dijit/layout/ContentPane" style="width:380px; height:280px; overflow:auto;">
            <div id="basemapGallery" ></div></div>
          </div>
        </div>

      </div>
     
     
  </div>

    </div>
  </body>
</html>
[/HTML]
0 Kudos