AnsweredAssumed Answered

Select from layer to buffer from checkbox and then buffer it.

Question asked by Aditi13Roy on Jul 11, 2016
Latest reply on Nov 28, 2017 by rscheitlin

Hello, Everyone. I am stuck in the code. I have list of layers in a dynamic layer checkbox and i want to select the layers to buffer whose result will be shown into the combobox. I am posting the code below. Please help. Thanks in advance.

-aditi

 

 

 

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

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

    <!--<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>

    <link rel="stylesheet" type="text/css" href="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/resources/dojo.css" />

    <link rel="stylesheet" type="text/css" href="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dijit/themes/tundra/tundra.css" />-->

 

 

    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no" />

    <title>Ground Water</title>

    <link rel="stylesheet" href="http://js.arcgis.com/3.15/dojo/resources/dojo.css" />

    <link rel="stylesheet" href="http://js.arcgis.com/3.15/dijit/themes/claro/claro.css" />

    <link rel="stylesheet" href="http://js.arcgis.com/3.15/dgrid/css/dgrid.css" />

    <link rel="stylesheet" href="http://js.arcgis.com/3.15/esri/css/esri.css" />

    <style type="text/css">

        html,

        body,

        #map {

            padding: 0;

            margin: 0;

            height: 100%;

        }

 

 

 

 

        #rightPane {

            padding: 0;

            width: 420px;

            font-family: "Verdana";

            font-size: "4";

        }

 

 

        .details {

            font-size: 14px;

            font-weight: 600;

            padding-bottom: 20px;

        }

 

 

        #button1 {

            margin: 2px;

            cursor: pointer;

        }

 

 

        #search {

            display: block;

            position: absolute;

            z-index: 2;

            top: 20px;

            left: 60px;

        }

 

 

        #header {

            border: solid #00ffff 3px;

            background-color: #00ffff;

          

        }

        #titlePane {

            width: 240px;

        }

        .esriScalebar {

            padding: 20px 20px;

        }

 

 

        #map {

            padding: 0;

        }

 

 

        .dgrid {

            border: none;

            height: 100%;

        }

 

 

        .dgrid-column-0 {

            width: 35px;

        }

 

 

        .dgrid-row-odd {

            background: #FFFDF3;

        }

 

 

        td div img:hover {

            cursor: pointer;

        }

 

 

        #titlePane {

            width: 240px;

        }

       

        .claro .dijitTitlePaneTitle {

            background: #fff;

            font-weight: 600;

            border: none;

            border-bottom: solid 1px #29201A;

            border-top: solid 1px #29201A;

        }

 

 

        .claro .dijitTitlePaneTitleHover {

            background: #eee;

        }

 

 

        .claro .dijitTitlePaneTitleActive {

            background: #808775;

        }

 

 

        .claro .dijitTitlePaneContentOuter {

            border-right: none;

            border-bottom: none;

            border-left: none;

        }

    </style>

    <script src="http://js.arcgis.com/3.15/"></script>

    <script>

        var map, geocoder, grid, tb, hospital, hydrant;

        var  cred = "esri_jsapi_id_manager_data"; // cookie/local storage name

        var showDialog2, myDialog2;

        var layer, visibleLayerIds = [];

 

 

        require([

            "dojo/_base/unload",

    "dojo/cookie",

    "dojo/json",

    "dojo/parser", "esri/config", "esri/IdentityManager",

            "esri/map", 'esri/dijit/Basemap',

           'esri/dijit/BasemapLayer',

         

            "esri/InfoTemplate",

            "esri/dijit/Geocoder",

            "esri/graphic",

            "dojo/query",

            "esri/config",

            "esri/geometry/normalizeUtils",

            "esri/tasks/GeometryService",

            "esri/tasks/BufferParameters",

            "esri/toolbars/draw",

            "dijit/registry",

            "esri/symbols/SimpleLineSymbol",

            "esri/symbols/SimpleFillSymbol",

            "esri/symbols/SimpleMarkerSymbol",

            "esri/renderers/SimpleRenderer",

            "esri/dijit/Measurement",

            "esri/layers/FeatureLayer",

            "esri/layers/ArcGISDynamicMapServiceLayer",

             "dojo/dom-construct",

            "dijit/form/CheckBox",

            "esri/geometry/screenUtils",

            "esri/dijit/PopupTemplate",

            "esri/request",

            "esri/tasks/query",

            "esri/geometry/Point",

            "esri/graphic",

            "esri/symbols/PictureMarkerSymbol",

            "dojo/on",

            "dojo/_base/array",

            "dojo/promise/all",

            "esri/Color",

            "dojo/_base/array",

            "dgrid/OnDemandGrid", "dgrid/Selection", "dojo/store/Memory",

            "dijit/form/Button",

            "dojo/parser", "dojo/_base/declare", "dojo/dom", "dojox/grid/DataGrid", "dojo/data/ItemFileReadStore",

            "dijit/TitlePane", "dijit/layout/BorderContainer", "dijit/layout/ContentPane", "dijit/layout/AccordionContainer",

            "dijit/Dialog", "dijit/form/TextBox", "dijit/DialogUnderlay", "dijit/form/ComboBox", "esri/layers/ImageParameters",

            "dojo/domReady!"

        ], function (baseUnload,

    cookie,

    JSON,

    parser, esriConfig, esriId,

          Map, Basemap, BasemapLayer,

          InfoTemplate,

          Geocoder,

          Graphic, query, esriConfig, normalizeUtils, GeometryService, BufferParameters, Draw, registry, SimpleLineSymbol, SimpleFillSymbol, SimpleMarkerSymbol,

          SimpleRenderer,

          Measurement,

          FeatureLayer,

          ArcGISDynamicMapServiceLayer,

           domConstruct,

        CheckBox,

         screenUtils,

          PopupTemplate,

          esriRequest,

          Query,

          Point,

          Graphic,

          PictureMarkerSymbol,

          on,

          array,

          All,

          Color,

          arrayUtils,

          Grid, Selection, Memory,

          Button,

          parser, declare, dom, DataGrid, ItemFileReadStore, Dialog, TextBox, DialogUnderlay, ComboBox,ImageParameters

        ) {

            parser.parse();

 

 

            esriConfig.defaults.geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");

            esriConfig.defaults.io.proxyUrl = "/proxy/";

            esriConfig.defaults.io.alwaysUseProxy = false;

 

 

            // store credentials/serverInfos before the page unloads

            baseUnload.addOnUnload(storeCredentials);

 

 

            // look for credentials in local storage

            loadCredentials();

 

 

            parser.parse();

 

 

            esriConfig.defaults.io.proxyUrl = "proxy.ashx";

 

 

            on(dom.byId("clearGraphics"), "click", function () {

                if (map) {

                    map.graphics.clear();

                }

            });

          

 

 

            var featureLayer;

            map = new Map("map", {

                basemap: "topo",

                center: [72.2763, 26.3855],

                zoom: 7

            });

           

 

 

            map.on("load", initOperationalLayer);

            map.on("load", initToolbar);

      

            var BaseMap = new FeatureLayer("http://gistest1.rajasthan.gov.in/rajasthan/rest/services/GWD/GWDBASE/MapServer/0",

            {

                mode: FeatureLayer.MODE_ONDEMAND,

 

 

                outFields: ["*"]

            });

            map.addLayer(BaseMap);

            var BaseMap1 = new FeatureLayer("http://gistest1.rajasthan.gov.in/rajasthan/rest/services/GWD/GWDBASE/MapServer/1",

            {

                mode: FeatureLayer.MODE_ONDEMAND,

 

 

                outFields: ["*"]

            });

            map.addLayer(BaseMap1);

            var BaseMap2 = new FeatureLayer("http://gistest1.rajasthan.gov.in/rajasthan/rest/services/GWD/GWDBASE/MapServer/2",

            {

                mode: FeatureLayer.MODE_ONDEMAND,

 

 

                outFields: ["*"]

            });

            map.addLayer(BaseMap2);

            var BaseMap3 = new FeatureLayer("http://gistest1.rajasthan.gov.in/rajasthan/rest/services/GWD/GWDBASE/MapServer/3",

            {

                mode: FeatureLayer.MODE_ONDEMAND,

 

 

                outFields: ["*"]

            });

            map.addLayer(BaseMap3);

            var BaseMap4 = new FeatureLayer("http://gistest1.rajasthan.gov.in/rajasthan/rest/services/GWD/GWDBASE/MapServer/4",

            {

                mode: FeatureLayer.MODE_ONDEMAND,

 

 

                outFields: ["*"]

            });

            map.addLayer(BaseMap4);

            var BaseMap5 = new FeatureLayer("http://gistest1.rajasthan.gov.in/rajasthan/rest/services/GWD/GWDBASE/MapServer/5",

            {

                mode: FeatureLayer.MODE_ONDEMAND,

 

 

                outFields: ["*"]

            });

            map.addLayer(BaseMap5);

 

 

            //add the secure service - token is required

            var secureLayer = new FeatureLayer("http://gistest1.rajasthan.gov.in/rajasthan/rest/services/Common/ADMIN/MapServer/0",

              {

                  mode: FeatureLayer.MODE_ONDEMAND,

 

 

                  outFields: ["*"]

              });

 

 

            var secureLayer1 = new FeatureLayer("http://gistest1.rajasthan.gov.in/rajasthan/rest/services/Common/ADMIN/MapServer/1",

              {

                  mode: FeatureLayer.MODE_ONDEMAND,

 

 

                  outFields: ["*"]

              });

 

 

            var secureLayer2 = new FeatureLayer("http://gistest1.rajasthan.gov.in/rajasthan/rest/services/Common/ADMIN/MapServer/2",

              {

                  mode: FeatureLayer.MODE_ONDEMAND,

 

 

                  outFields: ["*"]

              });

 

 

 

 

            var secureLayer3 = new FeatureLayer("http://gistest1.rajasthan.gov.in/rajasthan/rest/services/Common/ADMIN/MapServer/3",

              {

                  mode: FeatureLayer.MODE_ONDEMAND,

 

 

                  outFields: ["*"]

              });

 

 

            var secureLayer4 = new FeatureLayer("http://gistest1.rajasthan.gov.in/rajasthan/rest/services/Common/ADMIN/MapServer/4",

              {

                  mode: FeatureLayer.MODE_ONDEMAND,

 

 

                  outFields: ["*"]

              });

 

 

 

 

            var secureLayer5 = new FeatureLayer("http://gistest1.rajasthan.gov.in/rajasthan/rest/services/Common/ADMIN/MapServer/5",

              {

                  mode: FeatureLayer.MODE_ONDEMAND,

 

 

                  outFields: ["*"]

              });

 

 

 

 

            var secureLayer6 = new FeatureLayer("http://gistest1.rajasthan.gov.in/rajasthan/rest/services/Common/ADMIN/MapServer/6",

              {

                  mode: FeatureLayer.MODE_ONDEMAND,

 

 

                  outFields: ["*"]

              });

 

 

            var secureLayer7 = new FeatureLayer("http://gistest1.rajasthan.gov.in/rajasthan/rest/services/Common/ADMIN/MapServer/7",

              {

                  mode: FeatureLayer.MODE_ONDEMAND,

 

 

                  outFields: ["*"]

              });

 

 

            var secureLayer8 = new FeatureLayer("http://gistest1.rajasthan.gov.in/rajasthan/rest/services/Common/ADMIN/MapServer/8",

              {

                  mode: FeatureLayer.MODE_ONDEMAND,

 

 

                  outFields: ["*"]

              });

 

 

            map.addLayers([secureLayer8, secureLayer7, secureLayer6, secureLayer5, secureLayer4, secureLayer3, secureLayer2, secureLayer1, secureLayer]);

 

 

            // adding check box

            map.on("layers-add-result", function (evt) {

  

                var layerInfo = array.map(evt.layers, function (layer,

                index) {

                    return {

                        layer: layer.layer,

                        title: layer.layer.name

                    };

                });

 

 

                array.forEach(layerInfo, function (layer) {

                    var layerName = layer.title;

                    if (layerName == undefined) {

                        layerName = secureLayer8;

                    }

                    var checkBox = new CheckBox({

                        name: "checkBox" + layer.layer.id,

                        value: layer.layer.id,

                        checked: layer.layer.visible,

                        onChange: function (evt) {

                            var clayer = map.getLayer(this.value);

                            clayer.setVisibility(!clayer.visible);

                            this.checked = clayer.visible;

                        }

                    });

                  

                    domConstruct.place(checkBox.domNode, "t",

                        "after");

                    var checkLabel = domConstruct.create('label', {

                        'for': checkBox.name,

                        innerHTML: layerName

                    }, checkBox.domNode, "after");

                    domConstruct.place("<br />", checkLabel,

                        "after");

                });

            });

 

 

            function initOperationalLayer() {

                //Layer that is in Lat, Long Spatial reference 102100

                var infoTemplate = new InfoTemplate();

                hydrant = new FeatureLayer("http://gistest1.rajasthan.gov.in/rajasthan/rest/services/Common/ADMIN/MapServer/3", {

                    mode: FeatureLayer.MODE_ONDEMAND,

                    outFields: ["*"],

                    infoTemplate: infoTemplate

                });

 

 

                //Layer that is NAD83 / UTM zone 15 N Spatial Reference 26915

                hospital = new FeatureLayer("http://gistest1.rajasthan.gov.in/rajasthan/rest/services/Common/ADMIN/MapServer/4", {

                    mode: FeatureLayer.MODE_ONDEMAND,

                    outFields: ["*"],

                    infoTemplate: infoTemplate

                });

                var outline = new SimpleLineSymbol()

                  .setColor(Color.fromHex('#fff'));

                var sym = new SimpleFillSymbol()

                  .setColor(new Color([212, 212, 210, 0.3]))

                  .setOutline(outline);

                var renderer = new SimpleRenderer(sym);

                map.addLayer(hydrant);

                map.addLayer(hospital);

            }

 

 

            function initToolbar(evtObj) {

              

                tb = new Draw(evtObj.map);

                tb.on("draw-end", doBuffer);

                //click handler for the draw tool buttons

                query(".tool").on("click", function (evt) {

                    if (tb) {

                        tb.activate(evt.target.id);

                    }

                });

            }

 

 

            function doBuffer(evtObj) {

                tb.deactivate();

                var geometry = evtObj.geometry,

                  symbol;

                switch (geometry.type) {

                    case "point":

                        symbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE, 10, new SimpleLineSymbol(SimpleMarkerSymbol.STYLE_SOLID, new Color([255, 0, 0]), 1), new Color([0, 255, 0, 0.25]));

                        break;

                    case "polyline":

                        symbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASH, new Color([255, 0, 0]), 1);

                        break;

                    case "polygon":

                        symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_NONE, new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASHDOT, new Color([255, 0, 0]), 2), new Color([255, 255, 0, 0.25]));

                        break;

                }

                var graphic = new Graphic(geometry, symbol);

                map.graphics.add(graphic);

                //setup the buffer parameters

                var params = new BufferParameters();

                params.distances = [dom.byId("distance").value];

                params.outSpatialReference = map.spatialReference;

                params.unit = GeometryService[dom.byId("unit").value];

                //normalize the geometry

                normalizeUtils.normalizeCentralMeridian([geometry]).then(function (normalizedGeometries) {

                    var normalizedGeometry = normalizedGeometries[0];

                    if (normalizedGeometry.type === "point") {

                        //if geometry is a polygon then simplify polygon.  This will make the user drawn polygon topologically correct.

                        esriConfig.defaults.geometryService.simplify([normalizedGeometry], function (geometries) {

                            params.geometries = geometries;

                            esriConfig.defaults.geometryService.buffer(params, showBuffer);

                        });

                    } else {

                        params.geometries = [normalizedGeometry];

                        esriConfig.defaults.geometryService.buffer(params, showResults);

                    }

                });

            }

 

 

            function showBuffer(bufferedGeometries) {

                var symbol = new SimpleFillSymbol(

                  SimpleFillSymbol.STYLE_SOLID,

                  new SimpleLineSymbol(

                    SimpleLineSymbol.STYLE_SOLID,

                    new Color([255, 0, 0, 0.65]), 2

                  ),

                  new Color([255, 0, 0, 0.35])

                );

                arrayUtils.forEach(bufferedGeometries, function (geometry) {

                    var graphic = new Graphic(geometry, symbol);

                    map.graphics.add(graphic);

                });

            }

 

 

            on(esriConfig.defaults.geometryService, "buffer-complete", function (Geom) {

                queryMapService(Geom)

            })

           

            function queryMapService(Geom) {

                var promises = [];

 

 

                var query = new Query();

                query.returnGeometry = false;

                query.outFields = ["*"];

                query.geometry = Geom.geometries[0];

 

 

 

 

                promises.push(hydrant.selectFeatures(query, FeatureLayer.SELECTION_NEW));

                promises.push(hospital.selectFeatures(query, FeatureLayer.SELECTION_NEW));

                var allPromises = new All(promises);

                allPromises.then(function (r) {

                    showResults(r);

                });

            }

 

 

            function showResults(results) {

                console.log(results);

 

 

                var items = arrayUtils.map(results, function (result) {

                    return result;

                });

 

 

 

 

                var allItems = [];

 

 

 

 

                arrayUtils.map(items[0], function (item) {

                    allItems.push(item.attributes);

                })

 

 

 

 

                arrayUtils.map(items[1], function (item) {

                    allItems.push(item.attributes);

                })

 

 

                var data = {

                    identifier: "OBJECTID", //This field needs to have unique values

                    label: "OBJECTID", //Name field for display. Not pertinent to a grid but may be used elsewhere.

                    items: allItems

                };

 

 

                //Create data store and bind to grid.

                store = new ItemFileReadStore({

                    data: data

                });

                var grid = registry.byId("grid");

                grid.setStore(store);

                grid.on("rowclick", onRowClickHandler);

            }

 

 

            function onRowClickHandler(evt) {

                var clickedObjectf = evt.grid.getItem(evt.rowIndex).OBJECTID;

                var selectedObjectf;

                var distance = 50;

 

 

                dojo.forEach(hydrant.graphics, function (graphicf) {

                    if ((graphicf.attributes) && graphicf.attributes.OBJECTID === clickedObjectf) {

                        selectedObjectf = graphicf;

                        return;

                    }

                });

                dojo.forEach(hospital.graphics, function (graphicf) {

                    if ((graphicf.attributes) && graphicf.attributes.OBJECTID === clickedObjectf) {

                        selectedObjectf = graphicf;

                        return;

                    }

                });

                if (selectedObjectf.geometry.declaredClass == 'esri.geometry.Point') {

                    var PointExtent = new esri.geometry.Extent({

                        "xmin": selectedObjectf.geometry.x - distance,

                        "ymin": selectedObjectf.geometry.y - distance,

                        "xmax": selectedObjectf.geometry.x + distance,

                        "ymax": selectedObjectf.geometry.y + distance,

                        "spatialReference": {

                            "wkid": 102100

                        }

                    });

                    map.setExtent(PointExtent);

 

 

                }

            }

 

 

            function showLocation(evt) {

                map.graphics.clear();

                var point = evt.result.feature.geometry;

                var symbol = new SimpleMarkerSymbol()

                  .setStyle("square")

                  .setColor(new Color([255, 0, 0, 0.5]));

                var graphic = new Graphic(point, symbol);

                map.graphics.add(graphic);

                map.infoWindow.setTitle("Search Result");

                map.infoWindow.setContent(evt.result.name);

                map.infoWindow.show(evt.result.feature.geometry);

            }

 

 

 

 

            function loadCredentials() {

                var idJson, idObject;

 

 

                if (supports_local_storage()) {

                    // read from local storage

                    idJson = window.localStorage.getItem(cred);

                }

                else {

                    // read from a cookie

                    idJson = cookie(cred);

                }

 

 

                if (idJson && idJson != "null" && idJson.length > 4) {

                    idObject = JSON.parse(idJson);

                    esriId.initialize(idObject);

                }

                else {

                    // console.log("didn't find anything to load :(");

                }

            }

 

 

            function storeCredentials() {

                // make sure there are some credentials to persist

                if (esriId.credentials.length === 0) {

                    return;

                }

 

 

                // serialize the ID manager state to a string

                var idString = JSON.stringify(esriId.toJson());

                // store it client side

                if (supports_local_storage()) {

                    // use local storage

                    window.localStorage.setItem(cred, idString);

                    // console.log("wrote to local storage");

                }

                else {

                    // use a cookie

                    cookie(cred, idString, { expires: 72000000000000000 });

                    // console.log("wrote a cookie :-/");

                }

            }

 

 

            function supports_local_storage() {

                try {

                    return "localStorage" in window && window["localStorage"] !== null;

                } catch (e) {

                    return false;

                }

            }

        });

    </script>

</head>

<body class="claro">

   

    <div id="main" data-dojo-type="dijit.layout.BorderContainer" data-dojo-props="design:'headline',gutters:false" style="width:100%; height:100%;">

      

        <div id="header" data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region:'top'">

            <center><font size="4"><strong>Ground Water</strong></font></center>

            <button data-dojo-type="dijit/form/Button" style="float:right" onclick="showDialog();"><b>Search Assets</b></button>

        </div>

         <div id="map" class="shadow roundedCorners" data-dojo-type="dijit.layout.ContentPane" data-dojo-props="region:'center'">

            <div style="position:absolute; right:20px; top:10px; z-Index:999;">

 

 

            </div>

            <div id="SearchAssets" >

                <span style="padding: 10px 0;">Click to toggle each layer on or off</span>

             

                   <div id="t" style="padding: 2px 2px;"></div>

       <br />

            

                <div class="details">Pick a tool and draw on the map. The drawn graphic will be buffered based on the specified parameters.</div>

                <div><b>Buffer Parameters</b></div>

                Distance:

                <input type="text" id="distance" size="5" value="25" />

                <select id="unit" style="width:100px;">

                    <option value="UNIT_STATUTE_MILE">Miles</option>

                    <option value="UNIT_FOOT">Feet</option>

                    <option value="UNIT_KILOMETER">Kilometers</option>

                    <option value="UNIT_METER">Meters</option>

                    <option value="UNIT_NAUTICAL_MILE">Nautical Miles</option>

                    <option value="UNIT_US_NAUTICAL_MILE">US Nautical Miles</option>

                    <option value="UNIT_DEGREE">Degrees</option>

                </select>

                <br /> <br /><br />

                <button type="button"  onclick="point"  class="tool" id="point">Click On The Map</button>

                <button type="button" id="clearGraphics">Clear Graphics</button>

                <br />

                <br /><hr />

                <table data-dojo-type="dojox/grid/DataGrid" data-dojo-id="grid" id="grid" data-dojo-props="rowsPerPage:'1', rowSelector:'30px'">

                    <thead>

                        <tr>

                            <th width=40 field="OBJECTID">ID</th>

                            <th width=180 field="DISTRICT_NAME_EN">NAME</th>

 

 

 

 

                        </tr>

                    </thead>

                </table>

                <hr />

 

 

                <br />

 

 

            </div>

          

          

        </div>

    </div>

    <script type="text/javascript">

        require(["dijit/Dialog", "dijit/DialogUnderlay", "dojo/dom", "dojo/domReady!"], function (Dialog, DialogUnderlay, dom) {

         

            myDialog = new Dialog({

                title: "Search Assets",

                content: dom.byId('SearchAssets'),

                style: "width: 300px"

            });

 

 

            showDialog = function () {

                myDialog.show().then(function () {

                    DialogUnderlay.hide()

                    DialogUnderlay._singleton.bgIframe = {

                        destroy: function () {

                        }

                    }

                });

            }

 

 

        });

    </script>

</body>

 

 

</html> 

Outcomes