this is my code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Driving Directions</title>
<link rel="stylesheet" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.5/js/dojo/dijit/themes/claro/claro.css" />
<link rel="stylesheet" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.5/js/dgrid/css/dgrid.css" />
<link rel="stylesheet" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.5/js/esri/css/esri.css" />
<style type="text/css">
html, body
{
font-family: Arial,Helvetica,sans-serif;
height: 100%;
margin: 0;
}
#map
{
height: 100%;
overflow: hidden;
}
#dialog
{
top: 15px;
right: 15px;
position: absolute;
padding: 5px;
width: 300px;
background-color: #ffffff;
border-radius: 5px;
margin: 8px;
box-shadow: 0px 5px 3px #888;
}
#dialog img, #dialog input
{
vertical-align: bottom;
}
#dialog input
{
margin: 6px;
}
#grid
{
overflow-x: hidden;
overflow-y: auto;
}
.dgrid-row
{
padding: 5px;
margin-bottom: 5px;
min-height: 50px;
border-bottom: solid 1px #C0C0C0;
}
.detail a
{
color: #000;
text-decoration: none;
cursor: pointer;
}
.detail a:hover
{
text-decoration: underline;
}
.distance
{
float: right;
color: #C0C0C0;
font-style: italic;
}
</style>
<script type="text/javascript"> var dojoConfig = { parseOnLoad: true };</script>
<script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis/3.5/"></script>
<script src="http://js.arcgis.com/3.10/" type="text/javascript"></script>
<script type="text/javascript">
var map, locator, routeTask, routeParams = [], segmentGraphic, directionFeatures, grid;
require([
"esri/map",
"dijit/registry",
"esri/geometry/webMercatorUtils",
"esri/graphic",
"esri/tasks/locator",
"esri/tasks/route",
"esri/utils",
"dojo/DeferredList",
"dgrid/Grid",
"dojo/ready",
"dojo/dom",
"dojo/mouse",
"dojo/dom-construct",
"dojo/query",
"esri/graphic",
"esri/geometry/Point",
"dgrid/Selection",
"dojo/store/Memory",
"dojo/_base/array",
"dgrid/Keyboard",
"dgrid/List",
"dojo/dom-style",
"dijit/registry",
"esri/tasks/query",
"esri/Color",
"esri/symbols/SimpleMarkerSymbol",
"esri/InfoTemplate",
"dojo/_base/Color",
"esri/renderers/SimpleRenderer",
"esri/layers/FeatureLayer",
"esri/symbols/SimpleFillSymbol",
"esri/symbols/SimpleLineSymbol",
"esri/InfoTemplate",
"esri/tasks/QueryTask",
"dojo/_base/declare",
"dojo/number",
"dojo/on",
"dojo/parser",
"dijit/layout/BorderContainer",
"dijit/layout/ContentPane"
], function (
Map,
registry,
webMercatorUtils,
graphic,
locator,
route,
utils,
DeferredList,
Grid,
ready,
dom,
mouse,
domConstruct,
query,
graphic,
Point,
Selection,
Memory,
array,
Keyboard,
List,
domStyle,
registry,
Query,
Color,
SimpleMarkerSymbol,
InfoTemplate,
Color1,
SimpleRenderer,
FeatureLayer,
SimpleFillSymbol,
SimpleLineSymbol,
InfoTemplate,
QueryTask,
declare,
dojoNum,
on,
parser,
BorderContainer,
ContentPane
) {
ready(function () {
parser.parse();
dojo.connect(dojo.byId("directions"), "onclick", getDirections);
esri.config.defaults.io.proxyUrl = "/proxy";
map = new esri.Map("map", {
basemap: "streets",
center: [-95.273, 38.95],
zoom: 14
});
locator = new esri.tasks.Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");
locator.outSpatialReference = map.spatialReference;
var infoTemplate = new InfoTemplate("Location", "123");
var symbol = new SimpleMarkerSymbol(
SimpleMarkerSymbol.STYLE_CIRCLE,
15,
new SimpleLineSymbol(
SimpleLineSymbol.STYLE_SOLID,
new Color([0, 0, 255, 0.5]),
8
),
new Color([0, 0, 255])
);
locator.on("location-to-address-complete", function (evt) {
if (evt.address.address) {
var address = evt.address.address;
esri.geometry.webMercatorToGeographic
var location = webMercatorUtils.geographicToWebMercator(evt.address.location);
//this service returns geocoding results in geographic - convert to web mercator to display on map
// var location = webMercatorUtils.geographicToWebMercator(evt.location);
var graphic = new Graphic(location, symbol, address, infoTemplate);
map.graphics.add(graphic);
map.infoWindow.setTitle(graphic.getTitle());
map.infoWindow.setContent(graphic.getContent());
//display the info window with the address information
var screenPnt = map.toScreen(location);
map.infoWindow.resize(200, 100);
map.infoWindow.show(screenPnt, map.getInfoWindowAnchor(screenPnt));
}
});
map.on("click", function (evt) {
map.graphics.clear();
locator.locationToAddress(webMercatorUtils.webMercatorToGeographic(evt.mapPoint), 100);
});
//Add a geocoding server as the locator. This locator will be used to find the origin and destination coordinates by input addresses.
//Fire errorHandler if the locator return en error.
dojo.connect(locator, "onError", errorHandler);
//Add a network analyst server with related parameters to execute the routing task.
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.returnRoutes = false;
routeParams.returnDirections = true;
routeParams.directionsLengthUnits = esri.Units.MILES;
routeParams.outSpatialReference = new esri.SpatialReference({ wkid: 102100 });
//Show the route when the routing task is solved successfully, otherwise fire errorHandler.
dojo.connect(routeTask, "onSolveComplete", showRoute);
dojo.connect(routeTask, "onError", errorHandler);
//Execute a routing task when clicking "get direction".
function getDirections() {
routeParams.stops.features = [];
map.graphics.clear();
//Get origin address.
var optionsFrom = {
address: { "SingleLine": dojo.byId("fromTxf").value },
outFields: ["Loc_name"]
}
var fromAddress = locator.addressToLocations(optionsFrom);
//Get destination address.
var optionsTo = {
address: { "SingleLine": dojo.byId("toTxf").value },
outFields: ["Loc_name"]
}
var toAddress = locator.addressToLocations(optionsTo);
//Create a deferred list with the dojo.deferred objects of fromAddress and toAddress, then find the route.
var dList = new dojo.DeferredList([fromAddress, toAddress]);
dList.then(configureRoute);
}
//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 esri.symbol.PictureMarkerSymbol({
"angle": 0,
"xoffset": 0,
"yoffset": 10,
"type": "esriPMS",
"url": "Images/GreenPin1LargeB.png",
"contentType": "image/png",
"width": 40,
"height": 40
});
var toSymbol = new esri.symbol.PictureMarkerSymbol({
"angle": 0,
"xoffset": 0,
"yoffset": 12,
"type": "esriPMS",
"url": "Images/RedPin1LargeB.png",
"contentType": "image/png",
"width": 40,
"height": 40
});
var fromStop = getCandidate(results[0][1]);
if (fromStop === null) {
errorHandler("The origin address is invalid");
} else {
var fromGraphic = new esri.Graphic(fromStop.location, fromSymbol, { address: fromStop.address });
routeParams.stops.features[0] = map.graphics.add(fromGraphic);
};
var toStop = getCandidate(results[1][1]);
if (toStop === null) {
errorHandler("The destination address is invalid");
} else {
var toGraphic = new esri.Graphic(toStop.location, toSymbol, { address: toStop.address });
routeParams.stops.features[1] = map.graphics.add(toGraphic);
};
if (fromStop !== null && toStop !== null) {
routeTask.solve(routeParams);
}
}
//Handle all the coordinate candidates of the origin and destination addresses and
//return the candidate with the highest score.
function getCandidate(candidates) {
var stop = null, score = 0;
dojo.forEach(candidates, 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 esri.symbol.SimpleLineSymbol().setColor(new dojo.Color([0, 0, 255, 0.5])).setWidth(4);
//Add route to the map.
var routeGraphic = new esri.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 = dojo.number.format(directions.totalLength);
var totalLength = dojo.number.format(directions.totalTime);
data = dojo.map(directionsInfo, function (feature, index) {
return {
"detail": feature.attributes.text.replace("Turn right on ", "Rẽ phải vào ").replace("Turn left on ", "Rẽ trái vào ").replace("Continue on ", "Tiếp tục trên ").replace("Start at ", "Bắt đầu ở ").replace("Finish at ", "Kết thúc ở ").replace("Go north on ", "Đi về phía Bắc ").replace("Go south on ", "Đi về phía Nam ").replace("Go east on ", "Đi về phía Đông ").replace("Go west on ", "Đi về phía Tây").replace("At exit ", "Tại lối ra số ").replace("take ramp on the right to ", "rẽ phải vào đường nối ").replace("Turn right onto ramp and go on ", "Rẽ phải vào đường nối và đi vào ").replace(" on the right", " bên phải").replace(" on the left", " bên trái").replace("toward", "hướng"),
"distance": dojo.number.format(feature.attributes.length, { places: 2 }),
"index": index
}
});
grid = new dgrid.Grid({
renderRow: renderList,
showHeader: true
}, "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} Km</span></div>";
return dojo.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);
}
// var locator = new Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");
});
});
function zoomToSegment(index) {
var segment = directionFeatures[index];
var segmentSymbol = new esri.symbol.SimpleLineSymbol().setColor(new dojo.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));
} else {
segmentGraphic.setGeometry(segment.geometry);
}
}
</script>
</head>
<body class="claro">
<div id="map">
</div>
<div id="dialog">
<div>
<label for="fromTxf">
<img src="Images/GreenPin1LargeB.png" width="40px" height="40px" /></label>
<input type="text" id="fromTxf" value="380 New York St, Redlands, CA 92373" size="36" />
</div>
<div>
<label for="toTxf">
<img src="Images/RedPin1LargeB.png" width="40px" height="40px" /></label>
<input type="text" id="toTxf" value="900 Bermuda Dr, Redlands, CA 92374" size="36" />
<%--1799 Independence Ave, Redlands, CA 92374--%>
<%-- 1767 Somerset Ln, Redlands, CA 92374--%>
</div>
<input id="directions" type="button" value="Hiện kết quả" style="float: right;" />
<div id="directionsDetail" style="clear: both;">
<div id="grid">
</div>
</div>
</div>
</body>
</html>
Solved! Go to Solution.
Hi Ia,
Javascript is case sensitive. Your requires module name for esri/graphic is graphic but you are calling it as new Graphic in you code. Change the module name to Graphic.
Also you are requiring the module esri/graphic multiple times not a good practice.
Below is how your requires should be (formatted for my comfort)
require([
"esri/map","dijit/registry","esri/geometry/webMercatorUtils","esri/tasks/locator","esri/tasks/route","esri/utils",
"dojo/DeferredList","dgrid/Grid","dojo/ready","dojo/dom","dojo/mouse","dojo/dom-construct","dojo/query","esri/graphic",
"esri/geometry/Point","dgrid/Selection","dojo/store/Memory","dojo/_base/array","dgrid/Keyboard","dgrid/List","dojo/dom-style",
"dijit/registry","esri/tasks/query","esri/Color","esri/symbols/SimpleMarkerSymbol","esri/InfoTemplate","dojo/_base/Color",
"esri/renderers/SimpleRenderer","esri/layers/FeatureLayer","esri/symbols/SimpleFillSymbol","esri/symbols/SimpleLineSymbol",
"esri/InfoTemplate","esri/tasks/QueryTask","dojo/_base/declare","dojo/number","dojo/on","dojo/parser",
"dijit/layout/BorderContainer","dijit/layout/ContentPane"
], function (
Map,registry,webMercatorUtils,locator,route,utils,
DeferredList,Grid,ready,dom,mouse,domConstruct,query,Graphic,
Point,Selection,Memory,array,Keyboard,List,domStyle,
registry,Query,Color,SimpleMarkerSymbol,InfoTemplate,Color1,
SimpleRenderer,FeatureLayer,SimpleFillSymbol,SimpleLineSymbol,
InfoTemplate,QueryTask,declare,dojoNum,on,parser,
BorderContainer,ContentPane
) {
Hi Ia,
Javascript is case sensitive. Your requires module name for esri/graphic is graphic but you are calling it as new Graphic in you code. Change the module name to Graphic.
Also you are requiring the module esri/graphic multiple times not a good practice.
Below is how your requires should be (formatted for my comfort)
require([
"esri/map","dijit/registry","esri/geometry/webMercatorUtils","esri/tasks/locator","esri/tasks/route","esri/utils",
"dojo/DeferredList","dgrid/Grid","dojo/ready","dojo/dom","dojo/mouse","dojo/dom-construct","dojo/query","esri/graphic",
"esri/geometry/Point","dgrid/Selection","dojo/store/Memory","dojo/_base/array","dgrid/Keyboard","dgrid/List","dojo/dom-style",
"dijit/registry","esri/tasks/query","esri/Color","esri/symbols/SimpleMarkerSymbol","esri/InfoTemplate","dojo/_base/Color",
"esri/renderers/SimpleRenderer","esri/layers/FeatureLayer","esri/symbols/SimpleFillSymbol","esri/symbols/SimpleLineSymbol",
"esri/InfoTemplate","esri/tasks/QueryTask","dojo/_base/declare","dojo/number","dojo/on","dojo/parser",
"dijit/layout/BorderContainer","dijit/layout/ContentPane"
], function (
Map,registry,webMercatorUtils,locator,route,utils,
DeferredList,Grid,ready,dom,mouse,domConstruct,query,Graphic,
Point,Selection,Memory,array,Keyboard,List,domStyle,
registry,Query,Color,SimpleMarkerSymbol,InfoTemplate,Color1,
SimpleRenderer,FeatureLayer,SimpleFillSymbol,SimpleLineSymbol,
InfoTemplate,QueryTask,declare,dojoNum,on,parser,
BorderContainer,ContentPane
) {
Thank riyas very much!!! my code worked very good!! thank you!!!
Please mark Riyas post as the correct answer and move this thread to the Javascript space