//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);
}
var //Create a deferred list with the dojo.deferred objects of fromAddress and toAddress, then find the route.Should I just use deferred or switch to the new version promise/all?
var all = new All([fromAddress,toAddress]);
all.always(configureRoute);
};
Solved! Go to Solution.
require(["dojo/promise/all"... ... var fromAddress = locator.addressToLocations(optionsFrom); ... all([fromAddress.promise, toAddress.promise]).then(configureRoute);
//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