Run Service Area by button click!

2151
11
Jump to solution
11-26-2014 09:56 PM
ArcGISG_I_S
New Contributor

Dear all,

I am working on the sample existing in ArcGIS API for JavaScript "Basic Service Area"

The drive time polygon is given by a map click and i would like to have the polygon after a button click.

Below the code if someone could give me any support:

var map, serviceAreaTask, params, clickpoint;

    require([

      "esri/map", "esri/config",

      "esri/tasks/ServiceAreaTask", "esri/tasks/ServiceAreaParameters", "esri/tasks/FeatureSet",

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

      "esri/geometry/Point", "esri/graphic",

      "dojo/parser", "dojo/dom", "dijit/registry",

      "esri/Color", "dojo/_base/array",

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

      "dijit/form/HorizontalRule", "dijit/form/HorizontalRuleLabels", "dijit/form/HorizontalSlider",

      "dojo/domReady!",

  

     "esri/geometry/Extent",

     "esri/layers/GraphicsLayer",

     "esri/SpatialReference",

     "esri/InfoTemplate",

     "dojo/on"

  

    ], function(

      Map, esriConfig,

      ServiceAreaTask, ServiceAreaParameters, FeatureSet,

      SimpleMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol,

      Point, Graphic,

      parser, dom, registry,

      Color, arrayUtils,

  

   Extent, FeatureLayer, GraphicsLayer, SpatialReference,

      InfoTemplate, on

  

    ) {

      parser.parse();

      esriConfig.defaults.io.proxyUrl = "/proxy/";   

      map = new Map("map", {

        basemap: "streets",

        center: [-122.447, 37.781],

        zoom: 15

      });

     // map.on("click", mapClickHandler);

      params = new ServiceAreaParameters();

      params.defaultBreaks= [1];

      params.outSpatialReference = map.spatialReference;

      params.returnFacilities = false;

     

      serviceAreaTask = new ServiceAreaTask("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Network/USA/NAServer/Service Area");

           

      registry.byId("hslider").on("change", updateHorizontalLabel);

      updateHorizontalLabel();

      // Create function that updates label when changed

      function updateHorizontalLabel() {

        // Get access to nodes/widgets we need to get/set values

        var hSlider = registry.byId("hslider");

        var label = dom.byId("decValue");

        // Update label

        label.innerHTML = hSlider.get("value");

        params.defaultBreaks = [ hSlider.value / 60 ];

        if (clickpoint) {

          mapClickHandler(clickpoint);

        }

      }

     

      on(dojo.byId("AddDTP"), "click", function mapClickHandler(evt) {

        clickpoint = evt;

        map.graphics.clear(); //clear existing graphics

        //define the symbology used to display the results and input point

        var pointSymbol = new SimpleMarkerSymbol(

          "diamond",

          20,

          new SimpleLineSymbol(

            "solid",

            new Color([88,116,152]), 2

          ),

          new Color([88,116,152,0.45])

        );

        var inPoint = new Point(evt.mapPoint.x, evt.mapPoint.y, map.spatialReference);

        var location = new Graphic(inPoint, pointSymbol);

        map.graphics.add(location);

        var features = [];

        features.push(location);

        var facilities = new FeatureSet();

        facilities.features = features;

        params.facilities = facilities;

        //solve

        serviceAreaTask.solve(params,function(solveResult){

          var polygonSymbol = new SimpleFillSymbol(

            "solid", 

            new SimpleLineSymbol("solid", new Color([232,104,80]), 2),

            new Color([232,104,80,0.25])

          );

          arrayUtils.forEach(solveResult.serviceAreaPolygons, function(serviceArea){

            serviceArea.setSymbol(polygonSymbol);

            map.graphics.add(serviceArea);

          });

         

        }, function(err){

          console.log(err.message);

        });

      })

    });

Thank you in advance.

0 Kudos
1 Solution

Accepted Solutions
KenBuja
MVP Esteemed Contributor

It is working correctly...it's just placing the point in Portland, not in San Francisco. Your map's center is -122.447, 37.781 but you're placing the point at -122.65, 45.53.

Also, don't forget to mark the post that answered your initial question.

View solution in original post

0 Kudos
11 Replies
KenBuja
MVP Esteemed Contributor

The first problem that immediately pops out is that your function arguments must be in the same order as the require modules. The modules that don't need arguments have to be after any ones that do (highlighted in red). You've also left off the FeatureLayer module (highlighted in blue)

require([

      "esri/map", "esri/config",

      "esri/tasks/ServiceAreaTask", "esri/tasks/ServiceAreaParameters", "esri/tasks/FeatureSet",

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

      "esri/geometry/Point", "esri/graphic",

      "dojo/parser", "dojo/dom", "dijit/registry",

      "esri/Color", "dojo/_base/array",

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

      "dijit/form/HorizontalRule", "dijit/form/HorizontalRuleLabels", "dijit/form/HorizontalSlider",

      "dojo/domReady!",

  

    "esri/geometry/Extent",

     "esri/layers/GraphicsLayer",

     "esri/SpatialReference",

     "esri/InfoTemplate",

     "dojo/on"

  

    ], function(

      Map, esriConfig,

      ServiceAreaTask, ServiceAreaParameters, FeatureSet,

      SimpleMarkerSymbol, SimpleLineSymbol, SimpleFillSymbol,

      Point, Graphic,

      parser, dom, registry,

      Color, arrayUtils,

  

  Extent, FeatureLayer, GraphicsLayer, SpatialReference,

      InfoTemplate, on

0 Kudos
ArcGISG_I_S
New Contributor

Hi,

I added the "esri/layers/FeatureLayer", to the requiere list and i have a new order for the requiere module to be the same as my functions argument but still not working

Any help will be the most welcome.

Thank you in advance.

0 Kudos
KenBuja
MVP Esteemed Contributor

I imagine this is causing problems

on(dojo.byId("AddDTP"), "click", function mapClickHandler(evt) {

This function mapClickHandler only exists within this event. You're referring to it in your other function updateHorizontalLabel. Try moving that function outside the event.

What messages are showing up in your debugger?

0 Kudos
ArcGISG_I_S
New Contributor

Dear Ken,

Thanks for your help below is a print screen of the debugger:

debugger.png

Thanks a lot

0 Kudos
KenBuja
MVP Esteemed Contributor

So what's line 86 of your code?

0 Kudos
ArcGISG_I_S
New Contributor

Line 86 is like what you told me

on(dojo.byId("AddDTP"), "click", function mapClickHandler(evt) {

I think the function mapclickhandler is not recognize when i try to call it in updatehorizontallabel

But i dont know how to put this function outside ?

0 Kudos
HeikoHeijenga
Esri Contributor

Change line 86 (on(dojo.byId("AddDTP"), "click", function mapClickHandler(evt) {) to:

map.on("click, mapClickHandler);
function mapClickHandler(evt) { ...
0 Kudos
ArcGISG_I_S
New Contributor

Dear Heiko,

Thanks for your replay.

I already try that but this will run the area service by click on the map not after a button click.

The "AddDTP" is to use the button click, in the body of my code i have:

<button onclick="AddDTP();">Test</button>

So i want to run the task after a button click your solution will give me the possibility to run it by map click.

0 Kudos
ArcGISG_I_S
New Contributor

Dear All,

i tried to update the code now i can add the drive time polygon by a button click using Legacy Module, but when i tried to add a new button called show in order to add new point on the map using coordinate its not working could you please help

Below the full code the services are from esri sample so you can run the code on your own machine (Thanks a lot for the support)

The code:

<!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>Dispatch Algorithm Implementation</title>

 

  <link rel="stylesheet" href="http://js.arcgis.com/3.9/js/dojo/dijit/themes/claro/claro.css">

  <link rel="stylesheet" href="http://js.arcgis.com/3.9/js/esri/css/esri.css">

  <style>

    body,html,#main{margin:0;padding:0;height:100%;width:100%;}

  </style>

 

  <script>var dojoConfig = { parseOnLoad: true };</script>

  <script src="http://js.arcgis.com/3.9/"></script>

  <script>

    dojo.require("esri.map"); 

    dojo.require("esri.tasks.servicearea"); 

    dojo.require("dijit.dijit");

    dojo.require("dijit.layout.BorderContainer");

    dojo.require("dijit.layout.ContentPane");

    dojo.require("dijit.form.HorizontalSlider");

    dojo.require("dijit.form.HorizontalRuleLabels");

    dojo.require("dijit.form.HorizontalRule");

  dojo.require("dijit.form.Button");

  dojo.require("esri.graphic");

  dojo.require("esri.tasks.geometry");

  dojo.require("esri.layers.graphics");

  dojo.require("esri.Color");

  var mapOnClick_AddDTP_connect;

    var map, serviceAreaTask, params, clickpoint, gsvc;

    function init() {    

      esri.config.defaults.io.proxyUrl = "/proxy";

     

      map = new esri.Map("map", {

        basemap: "streets",

        center: [-122.447, 37.781],

        zoom: 14

      });

      params = new esri.tasks.ServiceAreaParameters();

      params.defaultBreaks= [1];

      params.outSpatialReference = map.spatialReference;

      params.returnFacilities = false;

     

      serviceAreaTask = new esri.tasks.ServiceAreaTask("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Network/USA/NAServer/Service Area");

   gsvc = new esri.tasks.GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");

           

      dojo.connect(dijit.byId("hslider"), "onChange", updateHorizontalLabel);

      updateHorizontalLabel();

  

    }

    // Create function that updates label when changed

    function updateHorizontalLabel() {

      // Get access to nodes/widgets we need to get/set values

      var hSlider = dijit.byId("hslider");

      var label = dojo.byId("decValue");

      // Update label

      label.innerHTML = hSlider.get("value");

      params.defaultBreaks = [hSlider.value/60];

      if (typeof clickpoint != 'undefined') {

        AddDT(clickpoint);

      };

    }

  function Show() {

        var m_mapPoint = [];

  m_mapPoint[1] = new esri.geometry.Point([-122.65,45.53],new esri.SpatialReference({ wkid:4326 }));  

        var param = new esri.tasks.ProjectParameters();

        // add array of points

        param.geometries = m_mapPoint;

            pt = m_mapPoint[1];              

            var symbol = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 20,

                          new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID,

                              new esri.Color([255, 0, 0]), 2), new esri.Color([0, 0, 0, 0])

                          );

                var graphic = new esri.Graphic(pt, symbol);                   

                map.graphics.add(graphic);

    }

  //Begins listening for click events to add DTP

  function AddDTP() {

        removeEventHandlers();

        mapOnClick_AddDTP_connect = dojo.connect(map, "onClick", AddDT);

      }

  

    //Clears DTP

      function ClearDTP() { 

  removeEventHandlers();

        for (var i=params.facilities.features.length-1; i>=0; i--) {

          map.graphics.remove(params.facilities.features.splice(i, 1)[0]);

        }

  map.graphics.clear();

      }

  //Stops listening for click events to add DTP

      function removeEventHandlers() {

        dojo.disconnect(mapOnClick_AddDTP_connect);

      } 

   

    function AddDT(evt) {

      clickpoint = evt;

      map.graphics.clear(); //clear existing graphics 

      //define the symbology used to display the results and input point

  

      var pointSymbol = new esri.symbol.PictureMarkerSymbol({

        "angle":0,

        "xoffset":0,

        "yoffset":10,

        "type":"esriPMS",

        "url":"http://icons.iconarchive.com/icons/aha-soft/standard-transport/256/police-car-icon.png",

        "contentType":"image/png",

        "width":30,

        "height":30

      }

       

      );

  

      var inPoint = new esri.geometry.Point(evt.mapPoint.x,evt.mapPoint.y,map.spatialReference);

      var location = new esri.Graphic(inPoint,pointSymbol);

      map.graphics.add(location);

      var features = [];

      features.push(location);

      var facilities = new esri.tasks.FeatureSet();

      facilities.features = features;

      params.facilities = facilities;

      //solve

      serviceAreaTask.solve(params,function(solveResult){

        var result = solveResult;

        var serviceAreaSymbol = new esri.symbol.SimpleFillSymbol(

          esri.symbol.SimpleFillSymbol.STYLE_SOLID, 

          new esri.symbol.SimpleLineSymbol(

            esri.symbol.SimpleLineSymbol.STYLE_SOLID,

            new dojo.Color([232,104,80]), 2

          ),

          new dojo.Color([232,104,80,0.25])

        );

        var polygonSymbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID,  new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID,

              new dojo.Color([232,104,80]), 2),new dojo.Color([232,104,80,0.25]));

        dojo.forEach(solveResult.serviceAreaPolygons, function(serviceArea){

          serviceArea.setSymbol(polygonSymbol);

          map.graphics.add(serviceArea);

        });

       

      },function(err){

        console.log(err.message);

      });

    }    

    dojo.ready(init);

  </script>

</head>

<body class="claro">

  <div data-dojo-type="dijit.layout.BorderContainer" data-dojo-props="design:'headline', gutters:false" style="width:100%;height:100%;margin:0px;">

    <div data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region:'left'">

      <b>Choose your threshold to find the appropriate dispatch:</b>

      <div style="width: 360px; margin: 10px">

        <!-- create rules and labels above horizontal slider -->

        <ol data-dojo-type="dijit.form.HorizontalRuleLabels"

          data-dojo-props="

            container: 'topDecoration',

            style: 'height: 1.2em; font-weight: bold; margin: 0 12px;'">

          <li>0</li>

          <li>0:20</li>

          <li>0:40</li>

          <li>1:00</li>

          <li>1:20</li>

   <li>1:40</li>

   <li>2:00</li>

        </ol>

        <div data-dojo-type="dijit.form.HorizontalRule"

          data-dojo-props="

            container: 'topDecoration',

            count: 7,

            style: 'height: 5px; margin: 0 12px;'">

        </div>

        <input id="hslider" value="60" type="range"

          data-dojo-type="dijit.form.HorizontalSlider"

          data-dojo-props="

            minimum: 0,

            maximum: 120,

            showButtons: false,

            discreteValues: 25">

        <div style="padding-top: 10px; text-align: center;">Travel time: <strong id="decValue"></strong> Seconds</div>

  <br><br>

  <label class="form_col" for="NumberPC">Please Enter a Number of Patrol Car:</label>

        <input name="NumberPC" id="NumberPC" type="text" size="10" />

  <br><br>

  <label class="form_col" for="zone">Zone :</label>

      <select name="zone" id="zone">

        <option value="none">Select your zone</option>

        <option value="z1">zone 1</option>

        <option value="z2">zone 2</option>

        <option value="z3">zone 3</option>

      </select>

  

  <br><br>

  <button onclick="AddDTP();">Dispatch</button>

  <button onclick="ClearDTP();">Clear Dispatch</button>

  <br><br>

  <button onclick="Show();">Show</button>

  <button onclick="Hide();">Hide</button>

      </div>

    </div>

    <div id="map" dojotype="dijit.layout.ContentPane" data-dojo-props="region:'center'"></div>   

  </div>

</body>

</html>

0 Kudos