Polygon Barriers JavaScript app

3457
6
Jump to solution
02-13-2014 12:24 AM
ArcGISG_I_S
New Contributor
Good Morning,

I am developing a GIS Web app using JavaScript, now i have the possibility to edit points in the Map and click on a button to have the polygon.
What i should do now is to ad two other button one for add stops and the other to solve road, and i should consider the polygon as a barrier so when i click on solve road the app should give me a road between the two stops and avoid the polygon already created

Below the code of creating the polygon (Need help on the second part please):

<!DOCTYPE html> <html>   <head>     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">   <!--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>Foggy Buffer Zone</title>    <link rel="stylesheet" href="http://js.arcgis.com/3.7/js/dojo/dijit/themes/claro/claro.css">   <link rel="stylesheet" href="http://js.arcgis.com/3.7/js/esri/css/esri.css">      <style>       html, body { height: 100%; width: 100%; margin: 0; padding: 0; }       #mapu { padding:0; }       #titlePane {         width:200px;         height:300px;       }       .claro .dijitTitlePaneTitle {         background: #A4BDA7;         font-weight:600;         color:#33292B;       }       .dijitButtonNode {         background-color: #A4BDA7 !important;         border: 1px solid #646750 !important;         color:#33292B !important;       }     </style>    <script src="http://js.arcgis.com/3.7/"></script>   <script>   require(["dojo/dom",           "dojo/dom-attr",           "dojo/_base/array",           "dojo/_base/Color",           "dojo/parser",            "esri/config",           "esri/map",           "esri/graphic",                "esri/tasks/GeometryService",           "esri/tasks/BufferParameters",                "esri/toolbars/draw",                "esri/symbols/SimpleMarkerSymbol",           "esri/symbols/SimpleLineSymbol",           "esri/symbols/SimpleFillSymbol",                      "dijit/layout/BorderContainer",           "dijit/layout/ContentPane",     "dijit/TitlePane"     ],          function(dom, domAttr, array, Color, parser, esriConfig, Map,   Graphic, GeometryService, BufferParameters, Draw, SimpleMarkerSymbol,   SimpleLineSymbol, SimpleFillSymbol)    {       var map, geo, tb;           parser.parse();          map = new Map("map", {         basemap: "streets",         center: [54.407, 24.462],         zoom: 13,       });      esriConfig.defaults.io.proxyUrl = "/proxy";     esriConfig.defaults.io.alwaysUseProxy = false;       geo = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");        map.on("load", initToolbar);    /*   **  Initialize the drawing toolbar  */  function initToolbar(evtObj) {       app.tb = new Draw(evtObj.map);       app.tb.on("draw-end", drawPoint);     }   // Array where points are saved  var list = new Array();    /*     ** Draw point  */  function drawPoint(evtObj) {        // Get the click geometry     var geometry = evtObj.geometry;           // Point symbol       var symbol = new SimpleMarkerSymbol(    {     "angle":0,         "xoffset":0,         "yoffset":12,         "type":"esriPMS",         "url":"http://www.iconexperience.com/_img/v_collection_png/512x512/shadow/cloud.png",         "contentType":"image/png",         "width":24,         "height":24         }    );        // Add point to the map       var graphic = new Graphic(geometry, symbol);       app.map.graphics.add(graphic);     // Store the point geometry    list.push(geometry)  }    /*     **  Create the polygon around points  */  function drawEndHandler(){         app.tb.deactivate();            geo.convexHull(list,function(result){             var symbol;             switch(result.type){               case "point":                 symbol = new esri.symbol.SimpleMarkerSymbol();                 break;               case "polyline":                 symbol = new esri.symbol.SimpleLineSymbol();                 break;               case "polygon":                 symbol = new esri.symbol.SimpleFillSymbol();                 break;             }             map.graphics.add(new esri.Graphic(result,symbol));           },function(error){             console.log("An error occured during convex hull calculation");           });             }       app = {       map: map,       tb: tb,       geo: geo,     drawPolygon: drawEndHandler     };   });       function drawClick(){  app.drawPolygon();   }      /*   ** Click on Point button   */   function pointClick(){     app.tb.activate(esri.toolbars.Draw.POINT);  app.map.hideZoomSlider();   }      /*   ** Click on Clear Graphics button   */   function clearGraphicsClick(){     app.map.graphics.clear();   }   </script>  </head>  <body class="claro">   <div data-dojo-type="dijit.layout.BorderContainer" data-dojo-props="gutters:'false',design:'headline'" style="width: 100%; height: 100%;">       <div id="map" data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region:'center'"  style="overflow:hidden;">       <div style="position:absolute; right:20px; top:10px; z-Index:999;">         <div id="titlePane" data-dojo-type="dijit.TitlePane" data-dojo-props="title:'Fog Warning System', closable:'false', open:'true'">             <p style="padding:5px 2px;color:#33292B;">Add foggy point and create the polygon.</p>    <button data-dojo-type="dijit.form.Button" onclick="pointClick();">Report Fog</button>      <button data-dojo-type="dijit.form.Button" type="button" onclick="clearGraphicsClick();">Clear</button>    <button id="point" data-dojo-type="dijit.form.Button" type="button" onclick="drawClick();">Draw The Foggy Zone</button>                      </div>       </div>       </div>     </div>     </body> </html>
0 Kudos
1 Solution

Accepted Solutions
RobertoPepato
Occasional Contributor II
Hello ilyass,

I found the cause of your problem. You didn't have initialized the toolbar before use it. I wrote a jsfiddle for your application here, so you can check if it works for you now.

PS: I changed your app a bit. You'll see that I'm using some new functions and discarding some of yours. This is just to not affect other parts of your code that are already working. I've commented everything I've changed (look for "pepatosp" in the code) to facilitate the localization of changes.

Here is the updated code:

<!DOCTYPE html> <html>   <head>     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">     <!--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>Multiple Routes</title>      <link rel="stylesheet" href="http://js.arcgis.com/3.8/js/dojo/dijit/themes/claro/claro.css">     <link rel="stylesheet" href="http://js.arcgis.com/3.8/js/esri/css/esri.css">          <script src="http://js.arcgis.com/3.8/"></script>     <script>       dojo.require("esri.map");       dojo.require("esri.tasks.route");       dojo.require("esri.toolbars.draw");       dojo.require("esri.tasks.geometry");       dojo.require("esri.toolbars.draw")        // Changed by pepatosp       var map, Draw, routeTask, routeParams, routes = [];       var drawToolbar;       // end of changes       var stopSymbol, barrierSymbol, polygonBarrierSymbol, routeSymbols;       var mapOnClick_addStops_connect, mapOnClick_addBarriers_connect, mapOnClick_addPolygonBarriers_connect;        function init() {         esri.config.defaults.io.proxyUrl = "/proxy";                  esri.config.defaults.geometryService = new esri.tasks.GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");          map = new esri.Map("map", {           basemap: "streets",           center: [-122.416, 37.802],           zoom: 15         });          // Initialize the toolbar // changed by pepatosp         function createToolBar() {           drawToolbar = new esri.toolbars.Draw(map);           drawToolbar.on("draw-end", addToMap);         }          function activateTool() {           drawToolbar.activate(esri.toolbars.Draw.POLYGON);           map.hideZoomSlider();         }          function addToMap(evt) {           drawToolbar.deactivate();           routeParams.polygonBarriers.features.push(             map.graphics.add(new esri.Graphic(evt.geometry, polygonBarrierSymbol))           );         }          map.on("load", createToolBar);          var node = dojo.byId("addPolygons");          dojo.connect(node, "click", activateTool);           routeTask = new esri.tasks.RouteTask("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route");         routeParams = new esri.tasks.RouteParameters();         routeParams.stops = new esri.tasks.FeatureSet();         routeParams.barriers = new esri.tasks.FeatureSet();         routeParams.polygonBarriers = new esri.tasks.FeatureSet();         routeParams.outSpatialReference = {"wkid":102100};         dojo.connect(routeTask, "onSolveComplete", showRoute);         dojo.connect(routeTask, "onError", errorHandler);          stopSymbol = new esri.symbol.SimpleMarkerSymbol().setStyle(esri.symbol.SimpleMarkerSymbol.STYLE_CROSS).setSize(15);         stopSymbol.outline.setWidth(3);          barrierSymbol = new esri.symbol.SimpleMarkerSymbol().setStyle(esri.symbol.SimpleMarkerSymbol.STYLE_X).setSize(10);         barrierSymbol.outline.setWidth(3).setColor(new dojo.Color([255,0,0]));                  var polygonBarrierSymbol = new esri.symbol.SimpleFillSymbol();          routeSymbols = {           "Route 1": new esri.symbol.SimpleLineSymbol().setColor(new dojo.Color([0,0,255,0.5])).setWidth(5),           "Route 2": new esri.symbol.SimpleLineSymbol().setColor(new dojo.Color([0,255,0,0.5])).setWidth(5),           "Route 3": new esri.symbol.SimpleLineSymbol().setColor(new dojo.Color([255,0,255,0.5])).setWidth(5)         };       }        dojo.ready(init);        //Begins listening for click events to add stops       function addStops() {         removeEventHandlers();         mapOnClick_addStops_connect = dojo.connect(map, "onClick", addStop);       }        //Clears all stops       function clearStops() {         removeEventHandlers();         for (var i=routeParams.stops.features.length-1; i>=0; i--) {           map.graphics.remove(routeParams.stops.features.splice(i, 1)[0]);         }       }        //Adds a stop. The stop is associated with the route currently displayed in the dropdown       function addStop(evt) {         routeParams.stops.features.push(           map.graphics.add(             new esri.Graphic(               evt.mapPoint,               stopSymbol,               { RouteName:dojo.byId("routeName").value }             )           )         );       }            //Begins listening for click events to add Polygon Barriers        function addPolygonBarriers() {         removeEventHandlers();         mapOnClick_addPolygonBarriers_connect = dojo.connect(map, "onClick", addPolygonBarrier);       }            //Clears all Polygon Barriers       function clearPolygonBarriers() {         removeEventHandlers();         for (var i=routeParams.polygonBarriers.features.length-1; i>=0; i--) {           map.graphics.remove(routeParams.polygonBarriers.features.splice(i, 1)[0]);         }       }            //Adds a Polygon Barrier.       function addPolygonBarrier(evt) {         drawToolbar.activate(esri.toolbars.Draw.POLYGON);         var drawEnd_connect = dojo.connect(drawToolbar, "onDrawEnd", function(geometry) {           routeParams.polygonBarriers.features.push(             map.graphics.add(new esri.Graphic(geometry, polygonBarrierSymbol))           );         });       }        //Begins listening for click events to add barriers       function addBarriers() {         removeEventHandlers();         mapOnClick_addBarriers_connect = dojo.connect(map, "onClick", addBarrier);       }        //Clears all barriers       function clearBarriers() {         removeEventHandlers();         for (var i=routeParams.barriers.features.length-1; i>=0; i--) {           map.graphics.remove(routeParams.barriers.features.splice(i, 1)[0]);         }       }        //Adds a barrier       function addBarrier(evt) {         routeParams.barriers.features.push(           map.graphics.add(             new esri.Graphic(               evt.mapPoint,               barrierSymbol             )           )         );       }        //Stops listening for click events to add Polygon Barriers, barriers and stops       function removeEventHandlers() {         dojo.disconnect(mapOnClick_addStops_connect);         dojo.disconnect(mapOnClick_addBarriers_connect);         dojo.disconnect(mapOnClick_addPolygonBarriers_connect);       }        //Solves the routes. Any errors will trigger the errorHandler function.       function solveRoute() {         removeEventHandlers();         routeTask.solve(routeParams);       }        //Clears all routes       function clearRoutes() {         for (var i=routes.length-1; i>=0; i--) {           map.graphics.remove(routes.splice(i, 1)[0]);         }         routes = [];       }        //Draws the resulting routes on the map       function showRoute(solveResult) {         clearRoutes();          dojo.forEach(solveResult.routeResults, function(routeResult, i) {           routes.push(             map.graphics.add(               routeResult.route.setSymbol(routeSymbols[routeResult.routeName])             )           );         });          var msgs = ["Server messages:"];         dojo.forEach(solveResult.messages, function(message) {           msgs.push(message.type + " : " + message.description);         });         if (msgs.length > 1) {           alert(msgs.join("\n - "));         }       }        //Reports any errors that occurred during the solve       function errorHandler(err) {         alert("An error occured\n" + err.message + "\n" + err.details.join("\n"));       }     </script>    </head>   <body class="claro">      Select route name: <select id="routeName">       <option value="Route 1">Route 1</option>        <option value="Route 2">Route 2</option>       <option value="Route 3">Route 3</option>     </select> to      <button onclick="addStops();">Add Stops</button>     <button onclick="clearStops();">Clear Stops</button>     <button onclick="addBarriers();">Add Barriers</button>     <button onclick="clearBarriers();">Clear Barriers</button>     <!-- changed by pepatosp     <button onclick="addPolygonBarriers();">Add PolyBarriers</button>     -->     <button id="addPolygons">Add PolyBarriers</button>     <button onclick="clearPolygonBarriers();">Clear PolyBarriers</button>     <button onclick="solveRoute();">Solve Routes</button>     <button onclick="clearRoutes();">Clear Routes</button>      <br /><br />     <div id="map" style="width:600px; height:400px; border:1px solid #000;"></div>      <ol>       <li>Select a route name from the drop down.</li>       <li>Click 'Add stops', then click on map to add stops to route.</li>        <li>Click the 'Add Barriers', then click on map to add barriers.</li>       <li>Optionally, repeat the above steps to add more routes.</li>       <li>Click the 'Solve Routes' to solve.</li>     </ul>     <p>Any server error messages will be displayed in an alert box.</p>   </body> </html>


Let me know if it helps.

View solution in original post

0 Kudos
6 Replies
RobertoPepato
Occasional Contributor II
Good Morning,

I am developing a GIS Web app using JavaScript, now i have the possibility to edit points in the Map and click on a button to have the polygon.
What i should do now is to ad two other button one for add stops and the other to solve road, and i should consider the polygon as a barrier so when i click on solve road the app should give me a road between the two stops and avoid the polygon already created

Below the code of creating the polygon (Need help on the second part please):

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <!--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>Foggy Buffer Zone</title>

  <link rel="stylesheet" href="http://js.arcgis.com/3.7/js/dojo/dijit/themes/claro/claro.css">
  <link rel="stylesheet" href="http://js.arcgis.com/3.7/js/esri/css/esri.css">
  
  <style>
      html, body { height: 100%; width: 100%; margin: 0; padding: 0; }
      #mapu { padding:0; }
      #titlePane {
        width:200px;
        height:300px;
      }
      .claro .dijitTitlePaneTitle {
        background: #A4BDA7;
        font-weight:600;
        color:#33292B;
      }
      .dijitButtonNode {
        background-color: #A4BDA7 !important;
        border: 1px solid #646750 !important;
        color:#33292B !important;
      }
    </style>

  <script src="http://js.arcgis.com/3.7/"></script>
  <script>
  require(["dojo/dom",
          "dojo/dom-attr",
          "dojo/_base/array",
          "dojo/_base/Color",
          "dojo/parser",

          "esri/config",
          "esri/map",
          "esri/graphic",
    
          "esri/tasks/GeometryService",
          "esri/tasks/BufferParameters",
    
          "esri/toolbars/draw",
    
          "esri/symbols/SimpleMarkerSymbol",
          "esri/symbols/SimpleLineSymbol",
          "esri/symbols/SimpleFillSymbol",
          
          "dijit/layout/BorderContainer",
          "dijit/layout/ContentPane",
    "dijit/TitlePane"
    ],
    
    function(dom, domAttr, array, Color, parser, esriConfig, Map, 
 Graphic, GeometryService, BufferParameters, Draw, SimpleMarkerSymbol, 
 SimpleLineSymbol, SimpleFillSymbol)
 
 {
      var map, geo, tb;
      
   parser.parse();   
      map = new Map("map", {
        basemap: "streets",
        center: [54.407, 24.462],
        zoom: 13,
      });
   
 esriConfig.defaults.io.proxyUrl = "/proxy";
    esriConfig.defaults.io.alwaysUseProxy = false;   
 
 geo = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");
  
    map.on("load", initToolbar);
 
 /* 
 **  Initialize the drawing toolbar
 */
 function initToolbar(evtObj) {
      app.tb = new Draw(evtObj.map);
      app.tb.on("draw-end", drawPoint);
    }

 // Array where points are saved
 var list = new Array();
 
 /*
    ** Draw point
 */
 function drawPoint(evtObj) { 
      // Get the click geometry 
   var geometry = evtObj.geometry;  
    
   // Point symbol
      var symbol = new SimpleMarkerSymbol(
   {
    "angle":0,
        "xoffset":0,
        "yoffset":12,
        "type":"esriPMS",
        "url":"http://www.iconexperience.com/_img/v_collection_png/512x512/shadow/cloud.png",
        "contentType":"image/png",
        "width":24,
        "height":24
        }
   );
   
   // Add point to the map
      var graphic = new Graphic(geometry, symbol);
      app.map.graphics.add(graphic);

   // Store the point geometry
   list.push(geometry)
 }
 
 /*
    **  Create the polygon around points
 */
 function drawEndHandler(){
        app.tb.deactivate();

          geo.convexHull(list,function(result){
            var symbol;
            switch(result.type){
              case "point":
                symbol = new esri.symbol.SimpleMarkerSymbol();
                break;
              case "polyline":
                symbol = new esri.symbol.SimpleLineSymbol();
                break;
              case "polygon":
                symbol = new esri.symbol.SimpleFillSymbol();
                break;
            }
            map.graphics.add(new esri.Graphic(result,symbol));
          },function(error){
            console.log("An error occured during convex hull calculation");
          });        
    }
 
    app = {
      map: map,
      tb: tb,
      geo: geo,
    drawPolygon: drawEndHandler
    };
  });
   
  function drawClick(){
 app.drawPolygon();
  }
  
  /*
  ** Click on Point button
  */
  function pointClick(){
    app.tb.activate(esri.toolbars.Draw.POINT);
 app.map.hideZoomSlider();
  }
  
  /*
  ** Click on Clear Graphics button
  */
  function clearGraphicsClick(){
    app.map.graphics.clear();
  }
  </script>

</head>

<body class="claro">
  <div data-dojo-type="dijit.layout.BorderContainer" data-dojo-props="gutters:'false',design:'headline'" style="width: 100%; height: 100%;">
      <div id="map" data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region:'center'"  style="overflow:hidden;">
      <div style="position:absolute; right:20px; top:10px; z-Index:999;">
        <div id="titlePane" data-dojo-type="dijit.TitlePane" data-dojo-props="title:'Fog Warning System', closable:'false', open:'true'">
            <p style="padding:5px 2px;color:#33292B;">Add foggy point and create the polygon.</p>
   <button data-dojo-type="dijit.form.Button" onclick="pointClick();">Report Fog</button>  
   <button data-dojo-type="dijit.form.Button" type="button" onclick="clearGraphicsClick();">Clear</button>
   <button id="point" data-dojo-type="dijit.form.Button" type="button" onclick="drawClick();">Draw The Foggy Zone</button>
            
        </div>
      </div>
      </div>
    </div>
   
</body>
</html>


Hello,

The key classes to do the job are RouteTask and RouteParameters (specially the polygonBarriers property). You can find documentation here and here

Here goes a sample code that I get from Esri site. I think that it is just what you're looking for.

require([
  "esri/map", "esri/tasks/RouteParameters", "esri/tasks/FeatureSet", "esri/symbols/SimpleFillSymbol",
  "esri/toolbars/Draw", "dojo/_base/connect", "esri/graphic", "esri/tasks/DataFile", ... 
], function(Map, FeatureSet, SimpleFillSymbol, Draw, connect, Graphic, DataFile, ... ) {
  var map = new Map( ... );
  var routeParams = new RouteParameters();
  routeParams.polygonBarriers = new FeatureSet();

  //Create a symbol for the barriers
  var polygonBarrierSymbol = new SimpleFillSymbol();

  //Use the draw toolbar to generate polygons to add as barriers.
  drawToolbar.activate(Draw.POLYGON);
  var drawEnd_connect = connect.connect(drawToolbar, "onDrawEnd", function(geometry) {
    routeParams.polygonBarriers.features.push(
    map.graphics.add(new Graphic(geometry, polygonBarrierSymbol))
  );

  //Requires ArcGIS Server 10.1 or greater
  var networkServiceUrl = 'http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Network/USA/MapServer/';
  routeParams.polygonBarriers = new DataFile({
    url: networkServiceUrl + "/7/query?where=1%3D1&outFields=Name,RouteName&f=json"}
  );
  ...
});
0 Kudos
ArcGISG_I_S
New Contributor
Good Morning,

Thanks you pepatosp for your feedback, could you please tell me how can i define the polygon already created before as a PolygonBarriers??

Thanks for your help 🙂
0 Kudos
RobertoPepato
Occasional Contributor II
Good Morning,

Thanks you pepatosp for your feedback, could you please tell me how can i define the polygon already created before as a PolygonBarriers??

Thanks for your help 🙂


I think that you have at least two options to add your polygons as barriers:

1 - Initialize the polygonBarriers property of your routeTask parameters with a FeatureSet object. When you create the polygons, add them to the FeatureSet as well (this is exactly what the sample provided before does).

2 - Assuming that you have already created your polygons and on the graphic layer while not adding them to the FeatureSet, create a piece of code that loop through these polygons on the GraphicsLayer and add them to the FeatureSet.

Let me know if it helps.
0 Kudos
ArcGISG_I_S
New Contributor
Good Morning Pepatosp,

Thank you so much for your time and your help.
Your feedbacks help me a lot actually as you said i do the first option i use that part of code to the routing code in order to get the polygon barrier like we already have the point barrier.
The code do not give me a good result the add stop and point barrier and solve rout work fine but when i want to add a polygon barrier and draw it in the ma its not working
Below the code that i am using if you could check it and tell which part i am missing, you can run it in your machine i am using only arcgis online services:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <!--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>Multiple Routes</title>

    <link rel="stylesheet" href="http://js.arcgis.com/3.8/js/dojo/dijit/themes/claro/claro.css">
    <link rel="stylesheet" href="http://js.arcgis.com/3.8/js/esri/css/esri.css">
    
    <script src="http://js.arcgis.com/3.8/"></script>
    <script>
      dojo.require("esri.map");
      dojo.require("esri.tasks.route");
      dojo.require("esri.toolbars.draw");
      dojo.require("esri.tasks.geometry");

      var map, Draw, drawToolbar, routeTask, routeParams, routes = [];
      var stopSymbol, barrierSymbol, polygonBarrierSymbol, routeSymbols;
      var mapOnClick_addStops_connect, mapOnClick_addBarriers_connect, mapOnClick_addPolygonBarriers_connect;

      function init() {
        esri.config.defaults.io.proxyUrl = "/proxy";
        
        esri.config.defaults.geometryService = new esri.tasks.GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");

        map = new esri.Map("map", {
          basemap: "streets",
          center: [-122.416, 37.802],
          zoom: 15
        });

        routeTask = new esri.tasks.RouteTask("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route");
        routeParams = new esri.tasks.RouteParameters();
        routeParams.stops = new esri.tasks.FeatureSet();
        routeParams.barriers = new esri.tasks.FeatureSet();
        routeParams.polygonBarriers = new esri.tasks.FeatureSet();
        routeParams.outSpatialReference = {"wkid":102100};
        dojo.connect(routeTask, "onSolveComplete", showRoute);
        dojo.connect(routeTask, "onError", errorHandler);

        stopSymbol = new esri.symbol.SimpleMarkerSymbol().setStyle(esri.symbol.SimpleMarkerSymbol.STYLE_CROSS).setSize(15);
        stopSymbol.outline.setWidth(3);

        barrierSymbol = new esri.symbol.SimpleMarkerSymbol().setStyle(esri.symbol.SimpleMarkerSymbol.STYLE_X).setSize(10);
        barrierSymbol.outline.setWidth(3).setColor(new dojo.Color([255,0,0]));
        
        var polygonBarrierSymbol = new esri.symbol.SimpleFillSymbol();

        routeSymbols = {
          "Route 1": new esri.symbol.SimpleLineSymbol().setColor(new dojo.Color([0,0,255,0.5])).setWidth(5),
          "Route 2": new esri.symbol.SimpleLineSymbol().setColor(new dojo.Color([0,255,0,0.5])).setWidth(5),
          "Route 3": new esri.symbol.SimpleLineSymbol().setColor(new dojo.Color([255,0,255,0.5])).setWidth(5)
        };
      }

      dojo.ready(init);

      //Begins listening for click events to add stops
      function addStops() {
        removeEventHandlers();
        mapOnClick_addStops_connect = dojo.connect(map, "onClick", addStop);
      }

      //Clears all stops
      function clearStops() {
        removeEventHandlers();
        for (var i=routeParams.stops.features.length-1; i>=0; i--) {
          map.graphics.remove(routeParams.stops.features.splice(i, 1)[0]);
        }
      }

      //Adds a stop. The stop is associated with the route currently displayed in the dropdown
      function addStop(evt) {
        routeParams.stops.features.push(
          map.graphics.add(
            new esri.Graphic(
              evt.mapPoint,
              stopSymbol,
              { RouteName:dojo.byId("routeName").value }
            )
          )
        );
      }
      
   //Begins listening for click events to add Polygon Barriers 
      function addPolygonBarriers() {
        removeEventHandlers();
        mapOnClick_addPolygonBarriers_connect = dojo.connect(map, "onClick", addPolygonBarrier);
      }
      
   //Clears all Polygon Barriers
      function clearPolygonBarriers() {
        removeEventHandlers();
        for (var i=routeParams.polygonBarriers.features.length-1; i>=0; i--) {
          map.graphics.remove(routeParams.polygonBarriers.features.splice(i, 1)[0]);
        }
      }
      
   //Adds a Polygon Barrier.
      function addPolygonBarrier(evt) {
      drawToolbar.activate(esri.toolbars.Draw.POLYGON);
      var drawEnd_connect = dojo.connect(drawToolbar, "onDrawEnd", function(geometry) {
      routeParams.polygonBarriers.features.push(
      map.graphics.add(new esri.Graphic(geometry, polygonBarrierSymbol))
      );
      });
      }

      //Begins listening for click events to add barriers
      function addBarriers() {
        removeEventHandlers();
        mapOnClick_addBarriers_connect = dojo.connect(map, "onClick", addBarrier);
      }

      //Clears all barriers
      function clearBarriers() {
        removeEventHandlers();
        for (var i=routeParams.barriers.features.length-1; i>=0; i--) {
          map.graphics.remove(routeParams.barriers.features.splice(i, 1)[0]);
        }
      }

      //Adds a barrier
      function addBarrier(evt) {
        routeParams.barriers.features.push(
          map.graphics.add(
            new esri.Graphic(
              evt.mapPoint,
              barrierSymbol
            )
          )
        );
      }

      //Stops listening for click events to add Polygon Barriers, barriers and stops
      function removeEventHandlers() {
        dojo.disconnect(mapOnClick_addStops_connect);
        dojo.disconnect(mapOnClick_addBarriers_connect);
        dojo.disconnect(mapOnClick_addPolygonBarriers_connect);
      }

      //Solves the routes. Any errors will trigger the errorHandler function.
      function solveRoute() {
        removeEventHandlers();
        routeTask.solve(routeParams);
      }

      //Clears all routes
      function clearRoutes() {
        for (var i=routes.length-1; i>=0; i--) {
          map.graphics.remove(routes.splice(i, 1)[0]);
        }
        routes = [];
      }

      //Draws the resulting routes on the map
      function showRoute(solveResult) {
        clearRoutes();

        dojo.forEach(solveResult.routeResults, function(routeResult, i) {
          routes.push(
            map.graphics.add(
              routeResult.route.setSymbol(routeSymbols[routeResult.routeName])
            )
          );
        });

        var msgs = ["Server messages:"];
        dojo.forEach(solveResult.messages, function(message) {
          msgs.push(message.type + " : " + message.description);
        });
        if (msgs.length > 1) {
          alert(msgs.join("\n - "));
        }
      }

      //Reports any errors that occurred during the solve
      function errorHandler(err) {
        alert("An error occured\n" + err.message + "\n" + err.details.join("\n"));
      }
    </script>

  </head>
  <body class="claro">

    Select route name: <select id="routeName">
      <option value="Route 1">Route 1</option>

      <option value="Route 2">Route 2</option>
      <option value="Route 3">Route 3</option>
    </select> to 
    <button onclick="addStops();">Add Stops</button>
    <button onclick="clearStops();">Clear Stops</button>
    <button onclick="addBarriers();">Add Barriers</button>
    <button onclick="clearBarriers();">Clear Barriers</button>
    <button onclick="addPolygonBarriers();">Add PolyBarriers</button>
    <button onclick="clearPolygonBarriers();">Clear PolyBarriers</button>
    <button onclick="solveRoute();">Solve Routes</button>
    <button onclick="clearRoutes();">Clear Routes</button>

    <br /><br />
    <div id="map" style="width:600px; height:400px; border:1px solid #000;"></div>
     <ol>
      <li>Select a route name from the drop down.</li>
      <li>Click 'Add stops', then click on map to add stops to route.</li>

      <li>Click the 'Add Barriers', then click on map to add barriers.</li>
      <li>Optionally, repeat the above steps to add more routes.</li>
      <li>Click the 'Solve Routes' to solve.</li>
    </ul>
    <p>Any server error messages will be displayed in an alert box.</p>
  </body>
</html>


Thank you very much 🙂
0 Kudos
RobertoPepato
Occasional Contributor II
Hello ilyass,

I found the cause of your problem. You didn't have initialized the toolbar before use it. I wrote a jsfiddle for your application here, so you can check if it works for you now.

PS: I changed your app a bit. You'll see that I'm using some new functions and discarding some of yours. This is just to not affect other parts of your code that are already working. I've commented everything I've changed (look for "pepatosp" in the code) to facilitate the localization of changes.

Here is the updated code:

<!DOCTYPE html> <html>   <head>     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">     <!--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>Multiple Routes</title>      <link rel="stylesheet" href="http://js.arcgis.com/3.8/js/dojo/dijit/themes/claro/claro.css">     <link rel="stylesheet" href="http://js.arcgis.com/3.8/js/esri/css/esri.css">          <script src="http://js.arcgis.com/3.8/"></script>     <script>       dojo.require("esri.map");       dojo.require("esri.tasks.route");       dojo.require("esri.toolbars.draw");       dojo.require("esri.tasks.geometry");       dojo.require("esri.toolbars.draw")        // Changed by pepatosp       var map, Draw, routeTask, routeParams, routes = [];       var drawToolbar;       // end of changes       var stopSymbol, barrierSymbol, polygonBarrierSymbol, routeSymbols;       var mapOnClick_addStops_connect, mapOnClick_addBarriers_connect, mapOnClick_addPolygonBarriers_connect;        function init() {         esri.config.defaults.io.proxyUrl = "/proxy";                  esri.config.defaults.geometryService = new esri.tasks.GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");          map = new esri.Map("map", {           basemap: "streets",           center: [-122.416, 37.802],           zoom: 15         });          // Initialize the toolbar // changed by pepatosp         function createToolBar() {           drawToolbar = new esri.toolbars.Draw(map);           drawToolbar.on("draw-end", addToMap);         }          function activateTool() {           drawToolbar.activate(esri.toolbars.Draw.POLYGON);           map.hideZoomSlider();         }          function addToMap(evt) {           drawToolbar.deactivate();           routeParams.polygonBarriers.features.push(             map.graphics.add(new esri.Graphic(evt.geometry, polygonBarrierSymbol))           );         }          map.on("load", createToolBar);          var node = dojo.byId("addPolygons");          dojo.connect(node, "click", activateTool);           routeTask = new esri.tasks.RouteTask("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route");         routeParams = new esri.tasks.RouteParameters();         routeParams.stops = new esri.tasks.FeatureSet();         routeParams.barriers = new esri.tasks.FeatureSet();         routeParams.polygonBarriers = new esri.tasks.FeatureSet();         routeParams.outSpatialReference = {"wkid":102100};         dojo.connect(routeTask, "onSolveComplete", showRoute);         dojo.connect(routeTask, "onError", errorHandler);          stopSymbol = new esri.symbol.SimpleMarkerSymbol().setStyle(esri.symbol.SimpleMarkerSymbol.STYLE_CROSS).setSize(15);         stopSymbol.outline.setWidth(3);          barrierSymbol = new esri.symbol.SimpleMarkerSymbol().setStyle(esri.symbol.SimpleMarkerSymbol.STYLE_X).setSize(10);         barrierSymbol.outline.setWidth(3).setColor(new dojo.Color([255,0,0]));                  var polygonBarrierSymbol = new esri.symbol.SimpleFillSymbol();          routeSymbols = {           "Route 1": new esri.symbol.SimpleLineSymbol().setColor(new dojo.Color([0,0,255,0.5])).setWidth(5),           "Route 2": new esri.symbol.SimpleLineSymbol().setColor(new dojo.Color([0,255,0,0.5])).setWidth(5),           "Route 3": new esri.symbol.SimpleLineSymbol().setColor(new dojo.Color([255,0,255,0.5])).setWidth(5)         };       }        dojo.ready(init);        //Begins listening for click events to add stops       function addStops() {         removeEventHandlers();         mapOnClick_addStops_connect = dojo.connect(map, "onClick", addStop);       }        //Clears all stops       function clearStops() {         removeEventHandlers();         for (var i=routeParams.stops.features.length-1; i>=0; i--) {           map.graphics.remove(routeParams.stops.features.splice(i, 1)[0]);         }       }        //Adds a stop. The stop is associated with the route currently displayed in the dropdown       function addStop(evt) {         routeParams.stops.features.push(           map.graphics.add(             new esri.Graphic(               evt.mapPoint,               stopSymbol,               { RouteName:dojo.byId("routeName").value }             )           )         );       }            //Begins listening for click events to add Polygon Barriers        function addPolygonBarriers() {         removeEventHandlers();         mapOnClick_addPolygonBarriers_connect = dojo.connect(map, "onClick", addPolygonBarrier);       }            //Clears all Polygon Barriers       function clearPolygonBarriers() {         removeEventHandlers();         for (var i=routeParams.polygonBarriers.features.length-1; i>=0; i--) {           map.graphics.remove(routeParams.polygonBarriers.features.splice(i, 1)[0]);         }       }            //Adds a Polygon Barrier.       function addPolygonBarrier(evt) {         drawToolbar.activate(esri.toolbars.Draw.POLYGON);         var drawEnd_connect = dojo.connect(drawToolbar, "onDrawEnd", function(geometry) {           routeParams.polygonBarriers.features.push(             map.graphics.add(new esri.Graphic(geometry, polygonBarrierSymbol))           );         });       }        //Begins listening for click events to add barriers       function addBarriers() {         removeEventHandlers();         mapOnClick_addBarriers_connect = dojo.connect(map, "onClick", addBarrier);       }        //Clears all barriers       function clearBarriers() {         removeEventHandlers();         for (var i=routeParams.barriers.features.length-1; i>=0; i--) {           map.graphics.remove(routeParams.barriers.features.splice(i, 1)[0]);         }       }        //Adds a barrier       function addBarrier(evt) {         routeParams.barriers.features.push(           map.graphics.add(             new esri.Graphic(               evt.mapPoint,               barrierSymbol             )           )         );       }        //Stops listening for click events to add Polygon Barriers, barriers and stops       function removeEventHandlers() {         dojo.disconnect(mapOnClick_addStops_connect);         dojo.disconnect(mapOnClick_addBarriers_connect);         dojo.disconnect(mapOnClick_addPolygonBarriers_connect);       }        //Solves the routes. Any errors will trigger the errorHandler function.       function solveRoute() {         removeEventHandlers();         routeTask.solve(routeParams);       }        //Clears all routes       function clearRoutes() {         for (var i=routes.length-1; i>=0; i--) {           map.graphics.remove(routes.splice(i, 1)[0]);         }         routes = [];       }        //Draws the resulting routes on the map       function showRoute(solveResult) {         clearRoutes();          dojo.forEach(solveResult.routeResults, function(routeResult, i) {           routes.push(             map.graphics.add(               routeResult.route.setSymbol(routeSymbols[routeResult.routeName])             )           );         });          var msgs = ["Server messages:"];         dojo.forEach(solveResult.messages, function(message) {           msgs.push(message.type + " : " + message.description);         });         if (msgs.length > 1) {           alert(msgs.join("\n - "));         }       }        //Reports any errors that occurred during the solve       function errorHandler(err) {         alert("An error occured\n" + err.message + "\n" + err.details.join("\n"));       }     </script>    </head>   <body class="claro">      Select route name: <select id="routeName">       <option value="Route 1">Route 1</option>        <option value="Route 2">Route 2</option>       <option value="Route 3">Route 3</option>     </select> to      <button onclick="addStops();">Add Stops</button>     <button onclick="clearStops();">Clear Stops</button>     <button onclick="addBarriers();">Add Barriers</button>     <button onclick="clearBarriers();">Clear Barriers</button>     <!-- changed by pepatosp     <button onclick="addPolygonBarriers();">Add PolyBarriers</button>     -->     <button id="addPolygons">Add PolyBarriers</button>     <button onclick="clearPolygonBarriers();">Clear PolyBarriers</button>     <button onclick="solveRoute();">Solve Routes</button>     <button onclick="clearRoutes();">Clear Routes</button>      <br /><br />     <div id="map" style="width:600px; height:400px; border:1px solid #000;"></div>      <ol>       <li>Select a route name from the drop down.</li>       <li>Click 'Add stops', then click on map to add stops to route.</li>        <li>Click the 'Add Barriers', then click on map to add barriers.</li>       <li>Optionally, repeat the above steps to add more routes.</li>       <li>Click the 'Solve Routes' to solve.</li>     </ul>     <p>Any server error messages will be displayed in an alert box.</p>   </body> </html>


Let me know if it helps.
0 Kudos
ArcGISG_I_S
New Contributor
Hello Mr Pepatosp,

Thank you very much what you give not only help me but this is exactly what i want thanks a lot for your support.

Thank you 🙂
0 Kudos