Select to view content in your preferred language

Could any one ask this question on StackFlow

2957
6
Jump to solution
06-23-2016 11:14 AM
Pedro_LuizCumino
Deactivated User


This is the link for the question!

Thanks in advance!

0 Kudos
1 Solution

Accepted Solutions
RobertScheitlin__GISP
MVP Emeritus

Pedro,

  Here is your code working:

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
    <title>Multiple Routes</title>

    <link rel="stylesheet" href="https://js.arcgis.com/3.17/dijit/themes/claro/claro.css">
    <link rel="stylesheet" href="https://js.arcgis.com/3.17/esri/css/esri.css">

    <script src="https://js.arcgis.com/3.17/"></script>
    <script>
        var map;
        // var sensors = getSensors();
        var sensorIndex = 0;
        require([
            "esri/urlUtils",
            "esri/config",
            "esri/map",
            "esri/geometry/webMercatorUtils",
            "esri/graphic",
            "esri/SpatialReference",
            "esri/geometry/Point",
            "esri/tasks/RouteTask",
            "esri/tasks/RouteParameters",
            "esri/tasks/FeatureSet",
            "esri/symbols/SimpleMarkerSymbol",
            "esri/symbols/SimpleLineSymbol",
            "esri/Color",
            "dojo/_base/array",
            "dojo/on",
            "dojo/dom",
            "dijit/registry",
            "dijit/layout/BorderContainer",
            "dijit/layout/ContentPane",
            "dijit/form/HorizontalSlider",
            "dijit/form/HorizontalRuleLabels",
            "dojo/domReady!"
        ], function(
            urlUtils,
            esriConfig,
            Map,
            webMercatorUtils,
            Graphic,
            SpatialReference,
            Point,
            RouteTask,
            RouteParameters,
            FeatureSet,
            SimpleMarkerSymbol,
            SimpleLineSymbol,
            Color,
            array,
            on,
            dom,
            registry,
            BorderContainer,
            ContentPane,
            HorizontalSlider,
            HorizontalRuleLabels
        ) {
            var map, routeTask, routeParams, routes = [];
            var stopSymbol, barrierSymbol, routeSymbols;
            var mapOnClick_addStops_connect, mapOnClick_addBarriers_connect;

            var x = -48.48;
            var y = -1.45;
            map = new Map("map", {
                basemap: "streets",
                center: [x, y],
                zoom: 15
            });
            routeTask = new RouteTask("https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World");

            routeParams = new RouteParameters();
            routeParams.stops = new FeatureSet();
            routeParams.barriers = new FeatureSet();
            routeParams.outSpatialReference = {
                "wkid": 102100
            };

            routeTask.on("solve-complete", showRoute);
            routeTask.on("error", errorHandler);

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

            barrierSymbol = new SimpleMarkerSymbol().setStyle(SimpleMarkerSymbol.STYLE_X).setSize(10);
            barrierSymbol.outline.setWidth(3).setColor(new Color([255, 0, 0]));

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

            //button click event listeners can't be added directly in HTML when the code is wrapped in an AMD callback
            on(dom.byId("addStopsBtn"), "click", addStops);
            on(dom.byId("clearStopsBtn"), "click", clearStops);
            on(dom.byId("addBarriersBtn"), "click", addBarriers);
            on(dom.byId("clearBarriersBtn"), "click", clearBarriers);
            on(dom.byId("solveRoutesBtn"), "click", solveRoute);
            on(dom.byId("clearRoutesBtn"), "click", clearRoutes);

            function addBarriers() {
                removeEventHandlers();
                addBarrier();
            }

            //Adds a barrier
            function addBarrier() {
                var eventsArray = [];
                sensorArryay = getSensors();
                routeParams.barriers = new FeatureSet();
                for (var i = 0; i < sensorArryay.length; i++) {
                    var pnt = new Point(sensorArryay.contextElement.attributes[2].value, sensorArryay.contextElement.attributes[1].value, new SpatialReference(4326))
                    routeParams.barriers.features.push(map.graphics.add(new esri.Graphic(webMercatorUtils.geographicToWebMercator(pnt), barrierSymbol)));
                }
            }

            //Begins listening for click events to add stops
            function addStops() {
                removeEventHandlers();
                mapOnClick_addStops_connect = map.on("click", 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: dom.byId("routeName").value
                            }
                        )
                    )
                );
            }

            //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]);
                }
            }

            //Stops listening for click events to add barriers and stops (if they've already been wired)
            function removeEventHandlers() {
                if (mapOnClick_addStops_connect) {
                    mapOnClick_addStops_connect.remove();
                }
                if (mapOnClick_addBarriers_connect) {
                    mapOnClick_addBarriers_connect.remove();
                }
            }

            //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(evt) {
                clearRoutes();
                array.forEach(evt.result.routeResults, function(routeResult, i) {
                    routes.push(
                        map.graphics.add(
                            routeResult.route.setSymbol(routeSymbols[routeResult.routeName])
                        )
                    );
                });

                var msgs = ["Server messages:"];
                array.forEach(evt.result.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"));
            }
        });

        function getSensors() {
            var result = '{"contextResponses":[{"contextElement":{"type":"StreetFixed","isPattern":"false","id":"StreetFixed1","attributes":[{"name":"aircondition","type":"float","value":"66.1"},{"name":"lat","type":"float","value":"-1.4519538"},{"name":"lng","type":"float","value":"-48.4781193"},{"name":"temperature","type":"float","value":"29.8"}]},"statusCode":{"code":"200","reasonPhrase":"OK"}},{"contextElement":{"type":"StreetFixed","isPattern":"false","id":"StreetFixed2","attributes":[{"name":"aircondition","type":"float","value":"66.1"},{"name":"lat","type":"float","value":"-1.4519062"},{"name":"lng","type":"float","value":"-48.476207"},{"name":"temperature","type":"float","value":"29.8"}]},"statusCode":{"code":"200","reasonPhrase":"OK"}},{"contextElement":{"type":"StreetFixed","isPattern":"false","id":"StreetFixed3","attributes":[{"name":"aircondition","type":"float","value":"66.1"},{"name":"lat","type":"float","value":"-1.4518047"},{"name":"lng","type":"float","value":"-48.4744374"},{"name":"temperature","type":"float","value":"29.8"}]},"statusCode":{"code":"200","reasonPhrase":"OK"}},{"contextElement":{"type":"StreetFixed","isPattern":"false","id":"StreetFixed4","attributes":[{"name":"aircondition","type":"float","value":"66.1"},{"name":"lat","type":"float","value":"-1.4517104"},{"name":"lng","type":"float","value":"-48.4726244"},{"name":"temperature","type":"float","value":"29.8"}]},"statusCode":{"code":"200","reasonPhrase":"OK"}}]}';
            // var request = new XMLHttpRequest();
            // request.open('GET', '/getSensors', false); // `false` makes the request synchronous
            // request.send(null);
            //
            // if (request.status === 200) {
            //     result = JSON.parse(request.responseText).contextResponses;
            //     // console.log(result);
            //     console.log("getSensors done!");
            // }
            return JSON.parse(result).contextResponses;
        }

        function eventFire(el, etype) {
            if (el.fireEvent) {
                el.fireEvent('on' + etype);
            } else {
                var evObj = document.createEvent('Events');
                evObj.initEvent(etype, true, false);
                el.dispatchEvent(evObj);
            }
        }
    </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 id="addStopsBtn">Add Stops</button>
    <button id="clearStopsBtn">Clear Stops</button>
    <button id="addBarriersBtn">Add Barriers</button>
    <button id="clearBarriersBtn">Clear Barriers</button>
    <button id="solveRoutesBtn">Solve Routes</button>
    <button id="clearRoutesBtn">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>

View solution in original post

6 Replies
RobertScheitlin__GISP
MVP Emeritus

Pedro,

  Are you clearing the maps graphics in your code some where? Maybe it would be good to post your whole modified code.

0 Kudos
Pedro_LuizCumino
Deactivated User

Here is the .js code used to run the service:

var map;
// var sensors = getSensors();
var sensorIndex = 0;
require([
  "esri/urlUtils",
  "esri/config",
  "esri/map",
  "esri/geometry/webMercatorUtils",
  "esri/graphic",
  "esri/tasks/RouteTask",
  "esri/tasks/RouteParameters",
  "esri/tasks/FeatureSet",
  "esri/symbols/SimpleMarkerSymbol",
  "esri/symbols/SimpleLineSymbol",
  "esri/Color",




  "dojo/_base/array",
  "dojo/on",
  "dojo/dom",




  "dijit/registry",
  "dijit/layout/BorderContainer",
  "dijit/layout/ContentPane",
  "dijit/form/HorizontalSlider",
  "dijit/form/HorizontalRuleLabels",




  "dojo/domReady!"
  ], function (
  urlUtils,
  esriConfig,
  Map,
  webMercatorUtils,
  Graphic,
  RouteTask,
  RouteParameters,
  FeatureSet,
  SimpleMarkerSymbol,
  SimpleLineSymbol,           
  Color,




  array,
  on,
  dom,




  registry,
  BorderContainer,
  ContentPane,
  HorizontalSlider,
  HorizontalRuleLabels
  ) {
  var map, routeTask, routeParams, routes = [];
  var stopSymbol, barrierSymbol, routeSymbols;
  var mapOnClick_addStops_connect, mapOnClick_addBarriers_connect;




  var x = -48.48;
  var y = -1.45;
  map = new Map("map", {
  basemap: "streets",
  center: [x, y],
  zoom: 15
  });
  routeTask = new RouteTask("https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World");




  routeParams = new RouteParameters();
  routeParams.stops = new FeatureSet();
  routeParams.barriers = new FeatureSet();
  routeParams.outSpatialReference = {"wkid":102100};




  routeTask.on("solve-complete", showRoute);
  routeTask.on("error", errorHandler);




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




  barrierSymbol = new SimpleMarkerSymbol().setStyle(SimpleMarkerSymbol.STYLE_X).setSize(10);
  barrierSymbol.outline.setWidth(3).setColor(new Color([255,0,0]));




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




        //button click event listeners can't be added directly in HTML when the code is wrapped in an AMD callback
        on(dom.byId("addStopsBtn"), "click", addStops);
        on(dom.byId("clearStopsBtn"), "click", clearStops);
        on(dom.byId("addBarriersBtn"), "click", addBarriers);
        on(dom.byId("clearBarriersBtn"), "click", clearBarriers);
        on(dom.byId("solveRoutesBtn"), "click", solveRoute);
        on(dom.byId("clearRoutesBtn"), "click", clearRoutes);        




        document.getElementById("map").addEventListener("click", function(evt){
  // console.log("This is a CLONE event: ");
  // console.log(evt);
  // console.log(" - - - - - - -");
  // evt = changeParams(evt, sensorIndex);
  // console.log(evt);
  // console.log("\n");
  // console.log("\n");
  // console.log("\n");
  // console.log("=======");
  // addBarrier(evt);




  // sensorIndex++;
  // if(sensorIndex > sensors.length)
  // sensorIndex = 0;
});




        function addBarriers() {
        removeEventHandlers();
        mapOnClick_addBarriers_connect = on(map, "click", addBarrier);
        }


   //Adds a barrier
   function addBarrier(evt) {
    var eventsArray = [];
    sensorArryay = getSensors();
    routeParams.barriers = new FeatureSet();
    for(var i = 0; i < sensorArryay.length; i++){
    var obj = jQuery.extend(true, {}, evt);
    eventsArray.push(obj);
    }
    for (var i = 0; i < sensorArryay.length; i++) {
    [eventsArray.mapPoint.x,eventsArray.mapPoint.y]=webMercatorUtils.lngLatToXY(
    sensorArryay.contextElement.attributes[2].value,
    sensorArryay.contextElement.attributes[1].value
    );  routeParams.barriers.features.push(map.graphics.add(new esri.Graphic(eventsArray.mapPoint,barrierSymbol)));
    }
   }


        //Begins listening for click events to add stops
        function addStops() {
        removeEventHandlers();
        mapOnClick_addStops_connect = map.on("click", 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:dom.byId("routeName").value }
        )
        )
        );
        }




        //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]);
        }
        }




        //Stops listening for click events to add barriers and stops (if they've already been wired)
        function removeEventHandlers() {        
        if (mapOnClick_addStops_connect) {
        mapOnClick_addStops_connect.remove();
        }
        if (mapOnClick_addBarriers_connect) {
        mapOnClick_addBarriers_connect.remove();
        }
        }




        //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(evt) {
        clearRoutes();




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




        var msgs = ["Server messages:"];
        array.forEach(evt.result.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"));
        }
    });




function getSensors(){
  var result;
  var request = new XMLHttpRequest();
  request.open('GET', '/getSensors', false);  // `false` makes the request synchronous
  request.send(null);




  if (request.status === 200) {
  result = JSON.parse(request.responseText).contextResponses;
  // console.log(result);
  console.log("getSensors done!");
}
return result;
}




function eventFire(el, etype){
  if (el.fireEvent) {
  el.fireEvent('on' + etype);
  } else {
  var evObj = document.createEvent('Events');
  evObj.initEvent(etype, true, false);
  el.dispatchEvent(evObj);
  }
}
0 Kudos
RobertScheitlin__GISP
MVP Emeritus

Pedro,

What does your sensor data look like? As I do not have access to your sensor service I need to replicate the data to test your app. Can you un-comment the console.log(result) and copy that data and post for me?

0 Kudos
Pedro_LuizCumino
Deactivated User

As you may suppose, I'm using a local server to request the sensors from a cloud server. The getSensor() method returns this JSON file shown below. You may create a sample of this.

This is the array of sensors in JSON format:

{ "contextResponses": [4] 0: { "contextElement": { "type": "StreetFixed" "isPattern": "false" "id": "StreetFixed1" "attributes": [4] 0:   { "name": "aircondition" "type": "float" "value": "66.1" }- 1:   { "name": "lat" "type": "float" "value": "-1.4519538" }- 2:   { "name": "lng" "type": "float" "value": "-48.4781193" }- 3:   { "name": "temperature" "type": "float" "value": "29.8" }- - }- "statusCode":  { "code": "200" "reasonPhrase": "OK" }- }- 1:   { "contextElement":  { "type": "StreetFixed" "isPattern": "false" "id": "StreetFixed2" "attributes": [4] 0:   { "name": "aircondition" "type": "float" "value": "66.1" }- 1:   { "name": "lat" "type": "float" "value": "-1.4519062" }- 2:   { "name": "lng" "type": "float" "value": "-48.476207" }- 3:   { "name": "temperature" "type": "float" "value": "29.8" }- - }- "statusCode":  { "code": "200" "reasonPhrase": "OK" }- }- 2:   { "contextElement":  { "type": "StreetFixed" "isPattern": "false" "id": "StreetFixed3" "attributes": [4] 0:   { "name": "aircondition" "type": "float" "value": "66.1" }- 1:   { "name": "lat" "type": "float" "value": "-1.4518047" }- 2:   { "name": "lng" "type": "float" "value": "-48.4744374" }- 3:   { "name": "temperature" "type": "float" "value": "29.8" }- - }- "statusCode":  { "code": "200" "reasonPhrase": "OK" }- }- 3:   { "contextElement":  { "type": "StreetFixed" "isPattern": "false" "id": "StreetFixed4" "attributes": [4] 0:   { "name": "aircondition" "type": "float" "value": "66.1" }- 1:   { "name": "lat" "type": "float" "value": "-1.4517104" }- 2:   { "name": "lng" "type": "float" "value": "-48.4726244" }- 3:   { "name": "temperature" "type": "float" "value": "29.8" }- - }- "statusCode":  { "code": "200" "reasonPhrase": "OK" }- }- - }

Here is the uncomment code as requested:

function getSensors(){      var result;      var request = new XMLHttpRequest();      request.open('GET', '/getSensors', false);   if (request.status === 200)         {   result = JSON.parse(request.responseText).contextResponses;    console.log(result);    console.log("getSensors done!"); } return result; }

Thanks!

0 Kudos
RobertScheitlin__GISP
MVP Emeritus

Pedro,

  Here is your code working:

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
    <title>Multiple Routes</title>

    <link rel="stylesheet" href="https://js.arcgis.com/3.17/dijit/themes/claro/claro.css">
    <link rel="stylesheet" href="https://js.arcgis.com/3.17/esri/css/esri.css">

    <script src="https://js.arcgis.com/3.17/"></script>
    <script>
        var map;
        // var sensors = getSensors();
        var sensorIndex = 0;
        require([
            "esri/urlUtils",
            "esri/config",
            "esri/map",
            "esri/geometry/webMercatorUtils",
            "esri/graphic",
            "esri/SpatialReference",
            "esri/geometry/Point",
            "esri/tasks/RouteTask",
            "esri/tasks/RouteParameters",
            "esri/tasks/FeatureSet",
            "esri/symbols/SimpleMarkerSymbol",
            "esri/symbols/SimpleLineSymbol",
            "esri/Color",
            "dojo/_base/array",
            "dojo/on",
            "dojo/dom",
            "dijit/registry",
            "dijit/layout/BorderContainer",
            "dijit/layout/ContentPane",
            "dijit/form/HorizontalSlider",
            "dijit/form/HorizontalRuleLabels",
            "dojo/domReady!"
        ], function(
            urlUtils,
            esriConfig,
            Map,
            webMercatorUtils,
            Graphic,
            SpatialReference,
            Point,
            RouteTask,
            RouteParameters,
            FeatureSet,
            SimpleMarkerSymbol,
            SimpleLineSymbol,
            Color,
            array,
            on,
            dom,
            registry,
            BorderContainer,
            ContentPane,
            HorizontalSlider,
            HorizontalRuleLabels
        ) {
            var map, routeTask, routeParams, routes = [];
            var stopSymbol, barrierSymbol, routeSymbols;
            var mapOnClick_addStops_connect, mapOnClick_addBarriers_connect;

            var x = -48.48;
            var y = -1.45;
            map = new Map("map", {
                basemap: "streets",
                center: [x, y],
                zoom: 15
            });
            routeTask = new RouteTask("https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World");

            routeParams = new RouteParameters();
            routeParams.stops = new FeatureSet();
            routeParams.barriers = new FeatureSet();
            routeParams.outSpatialReference = {
                "wkid": 102100
            };

            routeTask.on("solve-complete", showRoute);
            routeTask.on("error", errorHandler);

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

            barrierSymbol = new SimpleMarkerSymbol().setStyle(SimpleMarkerSymbol.STYLE_X).setSize(10);
            barrierSymbol.outline.setWidth(3).setColor(new Color([255, 0, 0]));

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

            //button click event listeners can't be added directly in HTML when the code is wrapped in an AMD callback
            on(dom.byId("addStopsBtn"), "click", addStops);
            on(dom.byId("clearStopsBtn"), "click", clearStops);
            on(dom.byId("addBarriersBtn"), "click", addBarriers);
            on(dom.byId("clearBarriersBtn"), "click", clearBarriers);
            on(dom.byId("solveRoutesBtn"), "click", solveRoute);
            on(dom.byId("clearRoutesBtn"), "click", clearRoutes);

            function addBarriers() {
                removeEventHandlers();
                addBarrier();
            }

            //Adds a barrier
            function addBarrier() {
                var eventsArray = [];
                sensorArryay = getSensors();
                routeParams.barriers = new FeatureSet();
                for (var i = 0; i < sensorArryay.length; i++) {
                    var pnt = new Point(sensorArryay.contextElement.attributes[2].value, sensorArryay.contextElement.attributes[1].value, new SpatialReference(4326))
                    routeParams.barriers.features.push(map.graphics.add(new esri.Graphic(webMercatorUtils.geographicToWebMercator(pnt), barrierSymbol)));
                }
            }

            //Begins listening for click events to add stops
            function addStops() {
                removeEventHandlers();
                mapOnClick_addStops_connect = map.on("click", 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: dom.byId("routeName").value
                            }
                        )
                    )
                );
            }

            //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]);
                }
            }

            //Stops listening for click events to add barriers and stops (if they've already been wired)
            function removeEventHandlers() {
                if (mapOnClick_addStops_connect) {
                    mapOnClick_addStops_connect.remove();
                }
                if (mapOnClick_addBarriers_connect) {
                    mapOnClick_addBarriers_connect.remove();
                }
            }

            //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(evt) {
                clearRoutes();
                array.forEach(evt.result.routeResults, function(routeResult, i) {
                    routes.push(
                        map.graphics.add(
                            routeResult.route.setSymbol(routeSymbols[routeResult.routeName])
                        )
                    );
                });

                var msgs = ["Server messages:"];
                array.forEach(evt.result.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"));
            }
        });

        function getSensors() {
            var result = '{"contextResponses":[{"contextElement":{"type":"StreetFixed","isPattern":"false","id":"StreetFixed1","attributes":[{"name":"aircondition","type":"float","value":"66.1"},{"name":"lat","type":"float","value":"-1.4519538"},{"name":"lng","type":"float","value":"-48.4781193"},{"name":"temperature","type":"float","value":"29.8"}]},"statusCode":{"code":"200","reasonPhrase":"OK"}},{"contextElement":{"type":"StreetFixed","isPattern":"false","id":"StreetFixed2","attributes":[{"name":"aircondition","type":"float","value":"66.1"},{"name":"lat","type":"float","value":"-1.4519062"},{"name":"lng","type":"float","value":"-48.476207"},{"name":"temperature","type":"float","value":"29.8"}]},"statusCode":{"code":"200","reasonPhrase":"OK"}},{"contextElement":{"type":"StreetFixed","isPattern":"false","id":"StreetFixed3","attributes":[{"name":"aircondition","type":"float","value":"66.1"},{"name":"lat","type":"float","value":"-1.4518047"},{"name":"lng","type":"float","value":"-48.4744374"},{"name":"temperature","type":"float","value":"29.8"}]},"statusCode":{"code":"200","reasonPhrase":"OK"}},{"contextElement":{"type":"StreetFixed","isPattern":"false","id":"StreetFixed4","attributes":[{"name":"aircondition","type":"float","value":"66.1"},{"name":"lat","type":"float","value":"-1.4517104"},{"name":"lng","type":"float","value":"-48.4726244"},{"name":"temperature","type":"float","value":"29.8"}]},"statusCode":{"code":"200","reasonPhrase":"OK"}}]}';
            // var request = new XMLHttpRequest();
            // request.open('GET', '/getSensors', false); // `false` makes the request synchronous
            // request.send(null);
            //
            // if (request.status === 200) {
            //     result = JSON.parse(request.responseText).contextResponses;
            //     // console.log(result);
            //     console.log("getSensors done!");
            // }
            return JSON.parse(result).contextResponses;
        }

        function eventFire(el, etype) {
            if (el.fireEvent) {
                el.fireEvent('on' + etype);
            } else {
                var evObj = document.createEvent('Events');
                evObj.initEvent(etype, true, false);
                el.dispatchEvent(evObj);
            }
        }
    </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 id="addStopsBtn">Add Stops</button>
    <button id="clearStopsBtn">Clear Stops</button>
    <button id="addBarriersBtn">Add Barriers</button>
    <button id="clearBarriersBtn">Clear Barriers</button>
    <button id="solveRoutesBtn">Solve Routes</button>
    <button id="clearRoutesBtn">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>
Pedro_LuizCumino
Deactivated User

Thank you Robert!

I'll check out to see how does it work looking at the references.

0 Kudos