Select to view content in your preferred language

ReferenceError: zoomToSegment is not defined when click segment  directionFeatures[index]

4416
4
Jump to solution
09-13-2014 03:20 AM
lasinh
by
Occasional Contributor

this is my code. please help me. thanks you

 

<!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">

 

 

    require([

       "esri/map",   

     "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,

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

        var map, locator, routeTask, routeParams = [], segmentGraphic, directionFeatures, grid;

            dojo.connect(dojo.byId("directions"), "onclick", getDirections);       

            esri.config.defaults.io.proxyUrl = "/proxy";       

            map = new esri.Map("map", {

                basemap: "streets",

                center: [-117.185, 34.065],

                zoom: 13

            });

            //Add a geocoding server as the locator. This locator will be used to find the origin and destination coordinates by input addresses.

            locator = new esri.tasks.Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");

            locator.outSpatialReference = map.spatialReference;       

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

        }

 

 

        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>

0 Kudos
1 Solution

Accepted Solutions
RiyasDeen
Frequent Contributor

Hi Ia,

It is a scope issue, you are attaching onclick event directly to the dom node, when it is executed it'll be scoped to the document. But the actual implementation is within dojo ready function. When the actual call happens, your document won't even know the existence of zoomToSegment fucntion.

What i have done in the attached document is, moved the zoomToSegment function to global scope and all local variables in dojo ready like map, directionFeatures etc. to global scope as well for use by zoomToSegment .

View solution in original post

4 Replies
DanPatterson_Retired
MVP Emeritus

Can you provide a Place or Space where you would like this redirected.  Also, providing some tags for your post in the tags section would facilitate getting an answer

0 Kudos
RiyasDeen
Frequent Contributor

Hi Ia,

It is a scope issue, you are attaching onclick event directly to the dom node, when it is executed it'll be scoped to the document. But the actual implementation is within dojo ready function. When the actual call happens, your document won't even know the existence of zoomToSegment fucntion.

What i have done in the attached document is, moved the zoomToSegment function to global scope and all local variables in dojo ready like map, directionFeatures etc. to global scope as well for use by zoomToSegment .

lasinh
by
Occasional Contributor

thanks Risyas and Dan very much!!   delete.html worked great!!  i have problem, please help me.

how to show infotemplate in function below:

function showResults(featureSet) {

             

                  //remove all graphics on the maps graphics layer

                  myMap.graphics.clear();     

                  var resultFeatures = featureSet.features;

                  //Loop through each feature returned

                  for (var i = 0, il = resultFeatures.length; i < il; i++) {

                      //Get the current feature from the featureSet.

                      //Feature is a graphic

                      var attr = resultFeatures.attributes;

                      var title = attr.TEN;

                      var content = "Field ID : " + attr.OBJECTID

                    + "<br />Tên: " + attr.TEN

                    + "<br />Địa chỉ : " + attr.TEN

                      //initialize InfoTemplate

                      infoTemplate = new InfoTemplate("Kết quả tìm kiếm:", content);                

//                      myMap.infoWindow.setTitle(title);

//                      myMap.infoWindow.setContent(content);

//                      myMap.infoWindow.show(resultFeatures[0].geometry);

                     var graphic = resultFeatures;

                      graphic.setSymbol(symbol1);

                   //Set the infoTemplate.

                     graphic.setInfoTemplate(infoTemplate);

                      //                      //Add graphic to the map graphics layer.

                      //                      myMap.graphics.add(graphic);

                     myMap.graphics.add(graphic);

                      //                    

                      myMap.centerAndZoom(resultFeatures[0].geometry, 7);

                  }

              }

0 Kudos
lasinh
by
Occasional Contributor

how to show both symbol and infotemplate no click symbol

0 Kudos