Select to view content in your preferred language

Get Driving Directions code advice

994
4
Jump to solution
02-12-2014 09:18 AM
AveryGomez
Emerging Contributor
Hello,

I am working on the get driving directions sample code and am trying to execute a routing task when clicking "get directions," but I am unable to see anything working on my application.

I have entered the following code
//Execute a routing task when clicking "get direction".
    getDirections:function () {
     console.log("hello where are you");
     
      routeParams.stops.features = [];
      this.map.graphics.clear();

    //Get origin address.
      var optionsFrom = {
        address:{"SingleLine":dojo.byId("fromTxf").value},
        outFields:["*"]
      }
      var fromAddress = locator.addressToLocations(optionsFrom);
   
      //Get destination address.
      var optionsTo = {
        address:{"SingleLine":dojo.byId("toTxf").value},
        outFields:["*"],
      }
      var toAddress = locator.addressToLocations(optionsTo);

      //Create a deferred list with the dojo.deferred objects of fromAddress and toAddress, then find the route.
     /* all([fromAddress,toAddress]).always(function(results){
     });
    }*/
      var dList = new dojo.DeferredList([fromAddress,toAddress]);
      dList.then(configureRoute);
    }


However, I show that "Deferred" has been deprecated, so I was trying to use the "dojo/promise/all" but I am still not getting any results.
var  //Create a deferred list with the dojo.deferred objects of fromAddress and toAddress, then find the route.
      var all = new All([fromAddress,toAddress]);
      all.always(configureRoute);
    
    };
Should I just use deferred or switch to the new version promise/all?

I am stuck and looking for some help with any of you expertise. Please let me know what you think.. thanks..
0 Kudos
1 Solution

Accepted Solutions
JohnGravois
Deactivated User
here's a working fiddle of the original published sample AMD, new route task, and promise-ified.  we'll be updating the live sample in the resource center shortly as well.

View solution in original post

0 Kudos
4 Replies
JohnGravois
Deactivated User
since the locator task itself already returns a Dojo.deferred (and because a promise is a property of that class), switching to promises would look like this:

require(["dojo/promise/all"...
...
var fromAddress = locator.addressToLocations(optionsFrom);
...
all([fromAddress.promise, toAddress.promise]).then(configureRoute);
0 Kudos
JohnGravois
Deactivated User
here's a working fiddle of the original published sample AMD, new route task, and promise-ified.  we'll be updating the live sample in the resource center shortly as well.
0 Kudos
AveryGomez
Emerging Contributor
Thank John for the help. The JSFiddle sample you sent me is exactly the route I was going. I fixed my code a bit to the sample you sent me, but I am still not able to see anything work. I am calling other nested folders to get my "DrivingDirections.js" folder working and am attaching some of my code in hopes maybe you see something out of place?





  //anonymous function to load CSS files required for this module
  ( function() {
      var css = [require.toUrl("parking/digit/DrivingDirections/css/DrivingDirections.css")], head = document.getElementsByTagName("head").item(0), link;
      for (var i = 0, il = css.length; i < il; i++) {
        link = document.createElement("link");
        link.type = "text/css";
        link.rel = "stylesheet";
        link.href = css.toString();
        head.appendChild(link);
      }
    }());

  
  return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, Evented], {
    templateString : template,
    widgetsInTemplate : true,
    baseClass : 'DrivingDirections',
    options : {
      map : null,
      extent : null
    },
   

    constructor : function(options) {
      declare.safeMixin(this, options);
      this.set("map", options.map);
    },
    startup : function(){
     on(dom.byId("directions"), "click", this.getDirections);
    },
    postCreate : function() {
     if (writeLog)
          console.log("Driving Directions");
//fill in the blank with a task function from index11.html...

//function init() {
     // on(dojo.byId("directions"), "onclick", getDirections);
     //on(dom.byId("directions"), "click", getDirections);
     
      //Set up the URL to the proxy page.
     // esri.config.defaults.io.proxyUrl = "/proxy"; //Proxy added on Controller.js
     
      //Create a map with an initial extent. Change the extent to match the area you would like to show.
    //map added on Controller.js
    /*  map = new esri.Map("map", {
        basemap: "streets",
        center: [-98.49946448681641, 29.4205708789947],
        zoom: 13,
        sliderStyle: "big"
      });*/



      //Add a geocoding server as the locator. This locator will be used to find the origin and destination coordinates by input addresses.
      locator = new Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");
      locator.outSpatialReference = map.spatialReference;
     
      //Fire errorHandler if the locator return en error.
      on(this.locator, "error", errorHandler);
      //locator.on("error", errorHandler);

      //Add a network analyst server with related parameters to execute the routing task.
      routeTask = new RouteTask("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route");
      routeParams = new RouteParameters();
      routeParams.stops = new FeatureSet();
      routeParams.returnRoutes = false;
      routeParams.returnDirections = true;
      routeParams.directionsLengthUnits = units.MILES;
      routeParams.outSpatialReference = new SpatialReference({ wkid:102100 });

      //Show the route when the routing task is solved successfully, otherwise fire errorHandler.
      // on(this.routeTask, "SolveComplete", showRoute);
      // on(this.routeTask, "error", errorHandler);
     
     
     
      //routeTask.on("solve-complete", showRoute);
    //}
   // dojo.ready(init);
  
  
  
  
  
  

   
   
   
    //Check if the origin and destination addresses are executed successfully
    //and solve the routing task.
    function configureRoute(results) {
     
      //Configure symbols to be used for destinations and route segments.
      var fromSymbol = new PictureMarkerSymbol({
        "angle":0,
        "xoffset":0,
        "yoffset":10,
        "type":"esriPMS",
        "url":"http://static.arcgis.com/images/Symbols/Transportation/GreenSquareDaymark.png",
        "contentType":"image/png",
        "width":24,
        "height":24
      });
      var toSymbol = new PictureMarkerSymbol({
        "angle":0,
        "xoffset":0,
        "yoffset":12,
        "type":"esriPMS",
        "url":"http://static.arcgis.com/images/Symbols/Transportation/RedSquareDaymark.png",
        "contentType":"image/png",
        "width":24,
        "height":24
      });
     
      var fromStop = checkCandidate(results[0][1]);
      if (fromStop===null) {
        errorHandler("The origin address is invalid");
      } else {
        var fromGraphic = new Graphic(fromStop.location, fromSymbol, { address:fromStop.address });
        routeParams.stops.features[0] = map.graphics.add(fromGraphic);
      };
     
      var toStop = checkCandidate(results[1][1]);
      if (toStop===null) {
        errorHandler("The destination address is invalid");
      } else {
        var toGraphic = new Graphic(toStop.location, toSymbol, { address:toStop.address });
        routeParams.stops.features[1] = map.graphics.add(toGraphic);
      };

      if (fromStop!==null && toStop!==null) {
        routeTask.solve(routeParams, showRoute, errorHandler);
      }
    }
     
    //Handle all the coordinate candidates of the origin and destination addresses and
    //return the candidate with the highest score.
    function checkCandidate(candidate){
      var stop = null, score = 0;
      dom.forEach(candidate, function(candidate){
        if(candidate.score > score){
         stop = candidate;
         score = candidate.score;
        }
      });
      return stop;
    }

    //Show the result of the routing task.
    function showRoute(solveResult) {
      var data = [];
      if(grid) grid.refresh();
     
      var directions = solveResult.routeResults[0].directions;
      directionFeatures = directions.features;
      var routeSymbol = new SimpleLineSymbol().setColor(new Color([0,0,255,0.5])).setWidth(4);
     
      //Add route to the map.
      var routeGraphic = new Graphic(directions.mergedGeometry, routeSymbol);
      map.graphics.add(routeGraphic);
      routeGraphic.getDojoShape().moveToBack();
      map.setExtent(directions.extent, true);
     
      //Display the directions.
      var directionsInfo = solveResult.routeResults[0].directions.features;
      var totalDistance = number.format(directions.totalLength);
      var totalLength = number.format(directions.totalTime);
      data = array.map(directionsInfo,function(feature,index){
        return {
          "detail": feature.attributes.text,
          "distance": number.format(feature.attributes.length,{places:2}),
          "index": index
        }
      });
      grid = new Grid({
        renderRow:renderList,
        showHeader:false
      },"grid");
      grid.renderArray(data);
    }
   
    function renderList(obj,options){
      var template = "<div class='detail'><div style='max-width:70%;float:left;'><a  href='#' onclick='zoomToSegment(${index});'> ${detail}</a></div><span style='float:right;' class='distance'>${distance} mi</span></div>";      
      return domConstruct.create("div",{innerHTML:esri.substitute(obj,template)});
    }
    //Display any errors that were caught when attempting to solve the route.
    function errorHandler(err) {
      alert("An error occured\n" + err);
    }
   
    function zoomToSegment(index) {
      var segment = directionFeatures[index];
      var segmentSymbol = new SimpleLineSymbol().setColor(new Color([255,0,0,0.5])).setWidth(8);

      map.setExtent(segment.geometry.getExtent(), true);
      if (! segmentGraphic) {
       //segmentGraphic = map.graphics.add(new esri.Graphic(segment.geometry, segmentSymbol)
        segmentGraphic = map.graphics.add(new Graphic(segment.geometry, segmentSymbol));
      } else {
        segmentGraphic.setGeometry(segment.geometry);
      }
    }   
//end of copy and paste for driving directions from index11.html



// startup : function() {
      // // map not defined
      // if (writeLog)
        // console.log('LayerSearch::startup');
      // if (!this.map) {
        // this.destroy();
        // if (writeLog)
          // console.log('LayerSearch::map required');
      // }
    // },
    // destroy : function() {
      // this.inherited(arguments);
    // }


},


///had .promise info here//

//Execute a routing task when clicking "get direction".
    getDirections:function () {
    // function getDirections() {
     console.log("hello where are you");
     
      routeParams.stops.features = [];
      map.graphics.clear();

    //Get origin address
      var optionsFrom = {
        address:{"SingleLine":dom.byId("fromTxf").value},
        outFields:["*"]
      }
      var fromDeferred = new deferred();
      var fromAddress = locator.addressToLocations(optionsFrom);
   
      //Get destination address.
      var optionsTo = {
        address:{"SingleLine":dom.byId("toTxf").value},
        outFields:["*"],
      }
      var toAddress = locator.addressToLocations(optionsTo);

      //Create a deferred list with the dojo.deferred objects of fromAddress and toAddress, then find the route.
      all([fromAddress.promise,toAddress.promise]).then(configureRoute);
     
    }
  
    /*  var dList = new dojo.DeferredList([fromAddress,toAddress]);
      dList.then(configureRoute);
    }*/
   
   
   


  });//end declare
 

  });//end define


And help would be very appreciated.. thank you so much for responding..
0 Kudos
JohnGravois
Deactivated User
perhaps because http://tasks.arcgisonline.com routing services were retired the other day?
0 Kudos