Display Total time and Total distance from route

1230
4
Jump to solution
03-27-2014 08:23 AM
HeathAnderson
Occasional Contributor
I am working on a Java App where you can input more than two stops and solve for a route.  All I want is to return is the Total time and Total Distance from the route as text on the screen.  I don't know the code to do this for 2+ stops in a route service.  Can some one please point me in the right direction.
Reply
0 Kudos
1 Solution

Accepted Solutions
JonathanUihlein
Regular Contributor II
Hi Heath!

According to the documentation, routeTask.solve() returns a deferred.

https://developers.arcgis.com/javascript/jsapi/routetask-amd.html

Because of this, you can use .then() to trigger a callback function with the results from your solve.

             function solveRoute() {                 removeEventHandlers();                 routeTask.solve(routeParams).then(function(results){                    var totalDriveTime = results.routeResults[0].directions.totalDriveTime;                   var totalLength = results.routeResults[0].directions.totalLength;                   var totalTime = results.routeResults[0].directions.totalTime;                                      alert("Distance : "+totalLength+" miles\nEstimated Time : "+totalDriveTime+" minutes");                  });                 //alert("Distance : 3 miles\nEstimated Time : 60 minutes");              }


"results" is an object that represents the response of the solve request. This is where you will access your solve data.
Notice how the alert is called inside the callback function.

The "results" object has tons of information regarding the solve.
Below is an example function that logs certain properties to the console.

            function solveRoute() {                 removeEventHandlers();                 routeTask.solve(routeParams).then(function(results){                                    console.log("results", results);                   console.log("results.routeResults[0]", results.routeResults[0]);                   console.log("results.routeResults[0].route", results.routeResults[0].route);                   console.log("results.routeResults[0].directions", results.routeResults[0].directions);                                      console.log("results.routeResults[0].directions.totalDriveTime", results.routeResults[0].directions.totalDriveTime);                   console.log("results.routeResults[0].directions.totalLength", results.routeResults[0].directions.totalLength);                   console.log("results.routeResults[0].directions.totalTime", results.routeResults[0].directions.totalTime);                                      console.log("results.routeResults[0].directions.summary", results.routeResults[0].directions.summary);                   console.log("results.routeResults[0].directions.summary.envelope", results.routeResults[0].directions.summary.envelope);                                    });              }


Hope this helps. Let me know if you have any questions.

View solution in original post

Reply
0 Kudos
4 Replies
ThavitinaiduGulivindala
Occasional Contributor
Have a loot at "accumulateAttributeNames" section in the below link
http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#//02r300000036000000
Reply
0 Kudos
HeathAnderson
Occasional Contributor
I have the accumulate attribute names set to "Minutes" and "Miles".  What i can't seem to figure out is what code is needed to get those attributes to display in a text box or in an alert.

Here is my code

[HTML]<!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" type="text/css" href="http://js.arcgis.com/3.8/js/esri/css/esri.css">
    <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/dgrid/css/dgrid.css">
    <script src="//js.arcgis.com/3.8/"></script>

    <style>
        html, body, #map {
            padding: 0;
            margin: 0;
            height: 100%;
        }

        #LocateButton {
            position: absolute;
            top: 95px;
            left: 20px;
            z-index: 50;
        }

        #ParkRec, a, img {
            float: right;
            height: inherit;
            border: none;
        }

        #footer {
            position: absolute;
            bottom: 0px;
            width: 100%;
            height: 45px;
            z-index: 50;
            background-color: rgba(0, 63, 94, 0.7);
        }
       
        footer, #buttons {
            position: absolute;
            bottom: 25%;
            left: 20px;
            z-index: inherit;
   
        }
        #dialog {
          top: 15px;
          right: 15px;
          position: absolute;
          padding: 5px;
          width: 380px;
          background-color: #ffffff;
          border-radius: 5px;
          margin: 8px;
          box-shadow: 0px 1px 3px #888;
        }
        #dialog input{
          margin: 0.5em;
          width: 20em;
        }
        #grid{
          overflow-x:hidden;
          overflow-y:auto;
        }
        input#directions {
          margin: 0.5em auto;
          width:  8em;
          display: block;
        }
        .dgrid-row{
          padding:5px;
          margin-bottom:5px;
          min-height:50px;
          border-bottom: solid 1px #C0C0C0;
        }
        .dgrid-row .detail div {
          cursor: pointer;
        }
        .dgrid-row .detail div:hover{
          text-decoration:underline;
        }
        .distance{
          float:right;
          color:#C0C0C0;
          font-style:italic;
        }
    </style>
   
    <script>
        var map;

        require([
          "esri/urlUtils",
          "esri/config",
          "esri/map",
          "esri/SpatialReference",
          "esri/dijit/LocateButton",

          "esri/tasks/RouteTask",
          "esri/tasks/RouteParameters",
          "esri/tasks/RouteResult",
          "esri/tasks/FeatureSet",
          "esri/units",
          "esri/dijit/Directions",
          "esri/tasks/DirectionsFeatureSet",
          "esri/layers/ArcGISDynamicMapServiceLayer",

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

          "dojo/_base/Color",
          "dojo/_base/array",
          "dojo/on",
          "dojo/dom",
          "dojo/dom-construct",
          "dojo/number",
          "dgrid/Grid",
          "dijit/registry",

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

          "dojo/domReady!"
        ], function (
          urlUtils, esriConfig, Map, SpatialReference, LocateButton, RouteTask, RouteParameters, RouteResult, FeatureSet, esriUnits, Directions, DirectionsFeatureSet, ArcGISDynamicMapServiceLayer,
          Graphic, SimpleMarkerSymbol, SimpleLineSymbol,
          Color, array, on, dom, domConstruct, number, Grid, registry
        ) {
            var routeTask, routeParams, routes = [], segmentGraphic, directionFeatures, grid;
            var stopSymbol, barrierSymbol, routeSymbols;
            var mapOnClick_addStops_connect;


            urlUtils.addProxyRule({
                urlPrefix: "route.arcgis.com",
                proxyUrl: "/sproxy"
            });

            map = new Map("map", {
                basemap: "streets",
                center: [-88.4017, 44.2656],
                zoom: 13,
                logo: false
            });

            geoLocate = new LocateButton({
                map: map
            }, "LocateButton");
            geoLocate.startup();

            var layerTrails = new ArcGISDynamicMapServiceLayer("http://gis.appleton.org/arcgis/rest/services/Routing/ParkRouter_Paths/MapServer");
            map.addLayer(layerTrails);

            routeTask = new RouteTask("http://gis.appleton.org/arcgis/rest/services/Routing/ParkRouter/NAServer/Route");
            routeParams = new RouteParameters();
            routeParams.stops = new FeatureSet();
            routeParams.outSpatialReference = { "wkid": 102100 };
            routeParams.returnRoutes = true;
            routeParams.returnDirections = true;

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

            stopSymbol = new SimpleMarkerSymbol().setStyle(SimpleMarkerSymbol.STYLE_CIRCLE).setSize(15);
            stopSymbol.setColor(new dojo.Color([41, 196, 10, 1.0]));
            stopSymbol.outline.setWidth(0);

            routeSymbols = new SimpleLineSymbol().setColor(new Color([27, 128, 6, 1.0])).setWidth(4);

            //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("solveRoutesBtn"), "click", solveRoute);
            on(dom.byId("clearRoutesBtn"), "click", clearRoutes);

            //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(routeSymbols).value }
                    )
                  )
                );
            }

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

            //Solves the routes. Any errors will trigger the errorHandler function.
            function solveRoute() {
                removeEventHandlers();
                routeTask.solve(routeParams);
                alert("Distance : 3 miles\nEstimated Time : 60 minutes");

            }

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

                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"));
            }

        });


    </script>

   

  </head>
  <body>
    <div id="footer">
        <div id="buttons">
            <button id="addStopsBtn">Add Stops</button>
            <button id="clearStopsBtn">Clear Stops</button>
            <button id="solveRoutesBtn">Solve Routes</button>
            <button id="clearRoutesBtn">Clear Routes</button>
        </div>
    </div>
    <div id="map" class="map">
        <div id="LocateButton"></div>
    </div>
    <div id="dialog">
      <div id="directionsDetail" style="clear:both;">
        <div id="grid"></div>
      </div>
    </div>
  </body>
</html>[/HTML]
Reply
0 Kudos
JonathanUihlein
Regular Contributor II
Hi Heath!

According to the documentation, routeTask.solve() returns a deferred.

https://developers.arcgis.com/javascript/jsapi/routetask-amd.html

Because of this, you can use .then() to trigger a callback function with the results from your solve.

             function solveRoute() {                 removeEventHandlers();                 routeTask.solve(routeParams).then(function(results){                    var totalDriveTime = results.routeResults[0].directions.totalDriveTime;                   var totalLength = results.routeResults[0].directions.totalLength;                   var totalTime = results.routeResults[0].directions.totalTime;                                      alert("Distance : "+totalLength+" miles\nEstimated Time : "+totalDriveTime+" minutes");                  });                 //alert("Distance : 3 miles\nEstimated Time : 60 minutes");              }


"results" is an object that represents the response of the solve request. This is where you will access your solve data.
Notice how the alert is called inside the callback function.

The "results" object has tons of information regarding the solve.
Below is an example function that logs certain properties to the console.

            function solveRoute() {                 removeEventHandlers();                 routeTask.solve(routeParams).then(function(results){                                    console.log("results", results);                   console.log("results.routeResults[0]", results.routeResults[0]);                   console.log("results.routeResults[0].route", results.routeResults[0].route);                   console.log("results.routeResults[0].directions", results.routeResults[0].directions);                                      console.log("results.routeResults[0].directions.totalDriveTime", results.routeResults[0].directions.totalDriveTime);                   console.log("results.routeResults[0].directions.totalLength", results.routeResults[0].directions.totalLength);                   console.log("results.routeResults[0].directions.totalTime", results.routeResults[0].directions.totalTime);                                      console.log("results.routeResults[0].directions.summary", results.routeResults[0].directions.summary);                   console.log("results.routeResults[0].directions.summary.envelope", results.routeResults[0].directions.summary.envelope);                                    });              }


Hope this helps. Let me know if you have any questions.

View solution in original post

Reply
0 Kudos
HeathAnderson
Occasional Contributor
Awesome.  I understand now.  Thanks for your help.
Reply
0 Kudos