Geoprocessing Task in ArcGIS API for JavaScript: Creating Buffer around 'map.graphics'

3902
9
Jump to solution
04-22-2016 07:46 AM
JacobSnyder2
New Contributor III

Hello,

I am currently in the process of creating a web application, in which I would like for the user to be able to type in their address, and have this location appear on the map. I have already accomplished this task. Next, I have created a geoprocessing model in ArcMap which should create a buffer around this point, and will find restaurants which intersect this buffer, and display them on the map. The model has 2 parameters, one distance parameter (linear unit), and one input parameter(feature set), which I have set as 'map.graphics' in my script. When I try to run the operation in a browser, i get a generic error: 'init.js:182 Error: Unable to complete operation'. I was wondering if anyone could tell me what they think I am doing wrong. Any help at all would be appreciated. Thanks so much in advance. Here is myJavaScript code:

require([

  "dojo/parser",

  "esri/map",

  "esri/layers/ArcGISDynamicMapServiceLayer",

  "esri/InfoTemplate",

  "esri/dijit/Search",

  "esri/dijit/LayerList",

  "esri/dijit/Scalebar",

  "esri/symbols/SimpleMarkerSymbol",

  "esri/Color",

  "esri/graphic",

  "esri/tasks/Geoprocessor",

  "esri/tasks/LinearUnit",

  "esri/tasks/locator",

                "esri/tasks/FeatureSet",

  "dojo/on",

  "dojo/_base/array",

  "dojo/dom",

  "dijit/registry",

  "dijit/layout/BorderContainer",

  "dijit/layout/ContentPane",

  "dijit/layout/AccordionContainer",

  "dijit/layout/AccordionPane",

  "dijit/layout/TabContainer",

  "dijit/form/Button",

  "dijit/form/Select",

  "dijit/form/HorizontalSlider",

  "dijit/form/HorizontalRule",

  "dijit/form/HorizontalRuleLabels",

  "dojo/domReady!"

  ], function (parser, Map, ArcGISDynamicMapServiceLayer, InfoTemplate, Search, LayerList, Scalebar, SimpleMarkerSymbol, Color, Graphic, Geoprocessor, LinearUnit, Locator, FeatureSet, on, arrayUtils, dom, registry){

  parser.parse();

  var map = new Map("map", { //Create the basemap

  basemap: "streets",

  center: [-77.6559716660883, 38.1850243980318],

  zoom: 11

  });

  var dynamicMapServiceLayer = new ArcGISDynamicMapServiceLayer("http://gis.spotsylvania.va.us/arcgis/rest/services/SoccerTournamentWebApp/SoccerTournamentMap_Initia..."); //Request Congressional Districts dynamic map service layer from ArcGIS Server.

  map.addLayer(dynamicMapServiceLayer);

  layers = [ //Create layers for insertion into LayerList constructor

  {

  layer:dynamicMapServiceLayer,

  showSubLayers: true,

  showLegend: true,

  showOpacitySlider: true,

  visibility: true,

  id: "Click arrow to the right to expand the layer list and map legend"

  }

  ]

  var onMapLoad = function() {

  var layerList = new LayerList({

  map: map,

  layers: layers

  },"layerlist");

  layerList.startup();

  };

  onMapLoad();

  var scaleBar = new Scalebar({

  map: map,

  attachTo: "bottom-left",

  scalebarStyle: "ruler",

  scalebarUnit: "english"

  });

  var locator = new Locator("http://gis.spotsylvania.va.us/arcgis/rest/services/SoccerTournamentWebApp/AddressLocator/GeocodeServ...");

  var s = new Search({

  map: map,

  }, "search");

  s.startup();

  registry.byId("locate").on("click", locate);

  function locate() {

  if(dom.byId("Street").value == "") {

  alert("Make sure that you have filled in all of the text boxes to find your location. Restaurants near you cannot be found unless your current location is known.")

  }

  else if(dom.byId("City").value == "") {

  alert("Make sure that you have filled in all of the text boxes to find your location. Restaurants near you cannot be found unless your current location is known.")

  }

  else if(dom.byId("State").value == "") {

  alert("Make sure that you have filled in all of the text boxes to find your location. Restaurants near you cannot be found unless your current location is known.")

  }

  else if(dom.byId("ZIP").value == "") {

  alert("Make sure that you have filled in all of the text boxes to find your location. Restaurants near you cannot be found unless your current location is known.")

  }

  else {

  map.graphics.clear();

  var address = {"Single Line Input" : dom.byId("Street").value.toString() + "," + " " + dom.byId("City").value.toString() + "," + " " + dom.byId("State").value.toString() + "," + " " + dom.byId("ZIP").value.toString()};

  console.log(address)

  locator.outSpatialReference = map.spatialReference;

  var options = {

  address: address,

  outFields: ["*"]

  }

  }

  locator.addressToLocations(options, showResults);

  }

  function showResults(results) {

     var candidate;

                    var symbol = new SimpleMarkerSymbol();

                      var infoTemplate = new InfoTemplate(

                        "Your Current Location",

                        "Address: ${address}"

                      );

                      symbol.setStyle(SimpleMarkerSymbol.STYLE_SQUARE);

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

  var geom;

  arrayUtils.every(results, function(candidate) {

    console.log(candidate.score);

    if (candidate.score > 80){

  

    var attributes = {

    address: candidate.address,

    score: candidate.score

    };

    geom = candidate.location;

    var graphic = new Graphic(geom, symbol,attributes,infoTemplate);

    map.graphics.add(graphic);

    return false;

    }

    else

    {

    return true;

    }

  });

  if ( geom !== undefined ) {

  map.centerAndZoom(geom, 12);

                        }

                    };

                    registry.byId("findRestaurants").on("click", findRestaurants);

                   

                    function findRestaurants() {

                        var gp = new Geoprocessor("http://gis.spotsylvania.va.us/arcgis/rest/services/SoccerTournamentWebApp/FindRestaurantsNearMe/GPSe...");

                        gp.setOutputSpatialReference({wkid:102100});

                        var distance = dom.byId("distance").value;

                        var distUnit = new LinearUnit();

                        distUnit.distance = distance;

                        distUnit.units = "esriMiles";

                        var inputFeatures = new FeatureSet();

                        var features = [];

                        features.push(map.graphics);

                        console.log(features);

                        inputFeatures.features = features;

                       

                        var params = { "Distance": distUnit, "Feature_Set": features };

  console.log(gp);

                       

                        console.log(params);

                       

                        gp.execute(params, drawRestaurants);

                    };

               

                    function drawRestaurants(results) {

                    var symbol1 = new SimpleMarkerSymbol();

                      var infoTemplate1 = new InfoTemplate(

                        "${Name of Facility}",

                        "Address: ${address}"

                      );

                        symbol1.setStyle(SimpleMarkerSymbol.STYLE_SQUARE);

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

  var features = results[0].value.features;

                        for (var f=0; f<features.length; f++) {

                            var feature = features;

                            feature.setSymbol(symbol1);

                            map.graphics.add(feature);

                        }

                    };

  });

0 Kudos
1 Solution

Accepted Solutions
RobertScheitlin__GISP
MVP Emeritus

Jacob,

  OK here is the code updated to do this using JS API:

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
    <title> Explore Spotsylvania County </title>
    <link rel="stylesheet" href="http://js.arcgis.com/3.16/esri/css/esri.css">
    <link rel="stylesheet" href="http://js.arcgis.com/3.16/dijit/themes/nihilo/nihilo.css">
    <link rel="stylesheet" href="https://js.arcgis.com/3.16/esri/css/esri.css" />
    <style>
        html,
        body {
            border: 0;
            height: 100%;
            margin: 0;
            padding: 0;
            width: 100%;
            font-size: 14px;
            background-color: #FFF;
            font-family: "Helvetica";
        }

        h1 {
            font-size: 28px;
            font-family: "Helvetica Neue";
            font-weight: bold;
            color: white;
            position: relative;
        }

        #mainwindow {
            background: #ffffff;
        }

        #header {
            background: #3366ff;
        }

        #sidebar {
            width: 310px;
            height: "auto";
        }

        #search {
            display: block;
            position: absolute;
            z-index: 2;
            top: 20px;
            right: 40px;
        }

        .right {
            display: block;
            position: absolute;
            z-index: 2;
            top: 10px;
            right: 40px;
        }

        #layerlist {
            font-family: "Helvetica";
        }

        p {
            font-family: "Helvetica";
        }
    </style>
    <script src="https://js.arcgis.com/3.16/"></script>
    <script type="text/javascript">
        require([
            "dojo/parser",
            "esri/map",
            "esri/layers/ArcGISDynamicMapServiceLayer",
            "esri/InfoTemplate",
            "esri/dijit/Search",
            "esri/dijit/LayerList",
            "esri/dijit/Scalebar",
            "esri/symbols/SimpleMarkerSymbol",
            "esri/Color",
            "esri/graphic",
            "esri/tasks/GeometryService",
            "esri/tasks/locator",
            "dojo/on",
            "dojo/_base/array",
            "dojo/dom",
            "dijit/registry",
            "esri/tasks/BufferParameters",
            "esri/tasks/QueryTask",
            "esri/tasks/query",
            "esri/SpatialReference",
            "esri/graphicsUtils",
            "esri/symbols/SimpleFillSymbol",
            "esri/symbols/SimpleLineSymbol",
            "esri/layers/GraphicsLayer",
            "dijit/layout/BorderContainer",
            "dijit/layout/ContentPane",
            "dijit/layout/AccordionContainer",
            "dijit/layout/AccordionPane",
            "dijit/layout/TabContainer",
            "dijit/form/Button",
            "dijit/form/Select",
            "dijit/form/HorizontalSlider",
            "dijit/form/HorizontalRule",
            "dijit/form/HorizontalRuleLabels",
            "dojo/domReady!"
        ], function(parser, Map, ArcGISDynamicMapServiceLayer, InfoTemplate, Search, LayerList, Scalebar, SimpleMarkerSymbol, Color, Graphic,
          GeometryService, Locator, on, arrayUtils, dom, registry, BufferParameters, QueryTask, Query,
          SpatialReference, graphicsUtils, SimpleFillSymbol, SimpleLineSymbol, GraphicsLayer) {
            parser.parse();

            var map = new Map("map", { //Create the basemap
                basemap: "streets",
                center: [-77.6559716660883, 38.1850243980318],
                zoom: 11
            });
            var gsvc = new GeometryService("http://gis.spotsylvania.va.us/arcgis/rest/services/Utilities/Geometry/GeometryServer");
            var dynamicMapServiceLayer = new ArcGISDynamicMapServiceLayer("http://gis.spotsylvania.va.us/arcgis/rest/services/SoccerTournamentWebApp/SoccerTournamentMap_Initia..."); //Request Congressional Districts dynamic map service layer from ArcGIS Server.
            var bufferGraphicsLayer = new GraphicsLayer({id: "bufferGL"});
            var restGraphicsLayer = new GraphicsLayer({id: "restGL"});
            var locateGraphicsLayer = new GraphicsLayer({id: "locateGL"});
            map.addLayers([dynamicMapServiceLayer, bufferGraphicsLayer, restGraphicsLayer, locateGraphicsLayer]);

            layers = [ //Create layers for insertion into LayerList constructor
                {
                    layer: dynamicMapServiceLayer,
                    showSubLayers: true,
                    showLegend: true,
                    showOpacitySlider: true,
                    visibility: true,
                    id: "Click arrow to the right to expand the layer list and map legend"
                }
            ]

            var onMapLoad = function() {
                var layerList = new LayerList({
                    map: map,
                    layers: layers
                }, "layerlist");
                layerList.startup();
            };

            onMapLoad();

            var scaleBar = new Scalebar({
                map: map,
                attachTo: "bottom-left",
                scalebarStyle: "ruler",
                scalebarUnit: "english"
            });

            var locator = new Locator("http://gis.spotsylvania.va.us/arcgis/rest/services/SoccerTournamentWebApp/AddressLocator/GeocodeServ...");

            var s = new Search({
                map: map,
            }, "search");
            s.startup();

            registry.byId("locate").on("click", locate);

            function locate() {
                if (dom.byId("Street").value == "") {
                    alert("Make sure that you have filled in all of the text boxes to find your location. Restaurants near you cannot be found unless your current location is known.")
                } else if (dom.byId("City").value == "") {
                    alert("Make sure that you have filled in all of the text boxes to find your location. Restaurants near you cannot be found unless your current location is known.")
                } else if (dom.byId("State").value == "") {
                    alert("Make sure that you have filled in all of the text boxes to find your location. Restaurants near you cannot be found unless your current location is known.")
                } else if (dom.byId("ZIP").value == "") {
                    alert("Make sure that you have filled in all of the text boxes to find your location. Restaurants near you cannot be found unless your current location is known.")
                } else {
                    map.graphics.clear();
                    var address = {
                        "Single Line Input": dom.byId("Street").value.toString() + "," + " " + dom.byId("City").value.toString() + "," + " " + dom.byId("State").value.toString() + "," + " " + dom.byId("ZIP").value.toString()
                    };
                    console.log(address)

                    locator.outSpatialReference = map.spatialReference;
                    var options = {
                        address: address,
                        outFields: ["*"]
                    }
                }
                locator.addressToLocations(options, showResults);
            }

            function showResults(results) {
                locateGraphicsLayer.clear();
                var candidate;
                var symbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_SQUARE, 10, null, new Color([255, 0, 0, 0.75]));
                var infoTemplate = new InfoTemplate(
                    "Your Current Location",
                    "Address: ${address}"
                );

                var geom;

                arrayUtils.every(results, function(candidate) {
                    console.log(candidate.score);
                    if (candidate.score > 80) {
                        var attributes = {
                            address: candidate.address,
                            score: candidate.score
                        };
                        geom = candidate.location;
                        var graphic = new Graphic(geom, symbol, attributes, infoTemplate);
                        locateGraphicsLayer.add(graphic);
                        return false;
                    } else {
                        return true;
                    }
                });

                if (geom !== undefined) {
                    map.centerAndZoom(geom, 12);
                }
            };

            registry.byId("findRestaurants").on("click", findRestaurants);
            registry.byId("clearBuffer").on("click", function(){
              bufferGraphicsLayer.clear();
            });
            registry.byId("clearResults").on("click", function(){
              restGraphicsLayer.clear();
            });

            function findRestaurants() {
                var params = new BufferParameters();

                params.geometries = graphicsUtils.getGeometries(locateGraphicsLayer.graphics);

                params.distances = [ dom.byId("distance").value ];
                params.unit = GeometryService.UNIT_STATUTE_MILE;
                params.outSpatialReference = map.spatialReference;
                gsvc.buffer(params, function(geometries){
                  console.info(geometries);
                  var buffer = new Graphic(geometries[0], new SimpleFillSymbol(SimpleFillSymbol.STYLE_NULL, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([255,0,0,0.8]), 2), new Color([0,0,0])));
                  bufferGraphicsLayer.add(buffer);
                  var qTask = new QueryTask("http://gis.spotsylvania.va.us/arcgis/rest/services/SoccerTournamentWebApp/SoccerTournamentMap_Initia...");
                  var query = new Query();
                  query.geometry = geometries[0];
                  query.spatialRelationship = Query.SPATIAL_REL_INTERSECTS;
                  query.outFields = ["*"];
                  query.returnGeometry = true;
                  qTask.execute(query, drawRestaurants);
                });
            };

            function drawRestaurants(results) {
                console.info(results);
                var symbol1 = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_SQUARE, 12, null, new Color([0, 0, 255]));
                var infoTemplate1 = new InfoTemplate(
                  "${NAME}",
                  "Address: ${FULLADDR}"
                );

                //var features = results[0].value.features;
                var features = results.features;
                for (var f = 0; f < features.length; f++) {
                    var feature = features;
                    feature.setSymbol(symbol1);
                    feature.setInfoTemplate(infoTemplate1);
                    restGraphicsLayer.add(feature);
                }
            };

        });
    </script>
</head>

<body class="nihilo">
    <div id="mainwindow" data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design:'headline',gutter:false,liveSplitters: true" style="width: 100%; height: 100%; margin: 0;">
        <div id="header" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'top',splitter:true" style="height:70px; background-color:#001F4C;">
            <h1> Explore Spotsylvania County, Virginia: An Interactive Experience for County Visitors  </h1>
            <div>
                <img src="http://www.spotsylvaniamuseum.org/data/layout/images/museum/county_seal.png" class="right">
            </div>
        </div>
        <div id="map" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'center',splitter:true">
            <div id="search"></div>
        </div>
        <div id="sidebar" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region: 'left', splitter:true">
            <div data-dojo-type="dijit/layout/AccordionContainer" title="Control visibility of layers, see map legend, or find restaurants near you">
                <div data-dojo-type="dijit/layout/AccordionPane" title="Layer list, map legend, and map opacity slider">
                    <div id="layerlist"></div>
                </div>
                <div data-dojo-type="dijit/layout/AccordionPane" title="Find Restaurants Near You">
                    <p> How many miles are you willing to travel? Type a mileage number in the box below. </p>
                    <input id="distance"></input><button id="clearBuffer" data-dojo-type="dijit/form/Button">Clear</button>
                    <br>
                    <br>
                    <p> Where are you right now? Type your address information below. </p>
                    <p>Street</p>
                    <input id="Street"></input>
                    <p>City</p>
                    <input id="City"></input>
                    <p>State</p>
                    <input id="State" value="Va"></input>
                    <p>ZIP</p>
                    <input id="ZIP"></input>
                    <br>
                    <button id="locate" data-dojo-type="dijit/form/Button">Find your location</button>
                    <p> Ready to find restaurants? Click the button below </p>
                    <button id="findRestaurants" data-dojo-type="dijit/form/Button">Find restaurants near your location</button>
                    <button id="clearResults" data-dojo-type="dijit/form/Button">Clear</button>
                    <div id="newLegend"></div>
                </div>
            </div>
        </div>
    </div>
</body>

</html>

View solution in original post

9 Replies
RobertScheitlin__GISP
MVP Emeritus

Jacob,

  Just quickly looking over your code it looks like you are setting the params Feature_Set to the features var and not the inputFeatures (which is the FeatureSet)

Try:

var params = { "Distance": distUnit, "Feature_Set": inputFeatures};

0 Kudos
JacobSnyder2
New Contributor III

Robert,

Thanks so much for your response. This actually was one of the errors that was in my script. I added this change to the script, and subsequently got this error after trying to run it again: 'init.js:199 TypeError: b.toJson is not a function(…) "TypeError: b.toJson is not a function'. Could this have something to do with the drawRestaurants() function? Thanks so much for your help.

0 Kudos
RobertScheitlin__GISP
MVP Emeritus

Jacob,

  Anyway you could zip the whole project up and attach for me to look at? If you are going to attach a zip then you have to click "Use advanced editor" link in the upper right hand corner and then find the attach link in the lower right corner.

0 Kudos
JacobSnyder2
New Contributor III

Robert,

Absolutely. I have attached a ZIP file which contains the full HTML file, and a toolbox that contains the model that I have created. Again, I really appreciate your time and efforts.

-Jacob

0 Kudos
RobertScheitlin__GISP
MVP Emeritus

Jacob,

  OK, I have to ask before I go to far in figuring out what is wrong here. Is there a reason you are using a GP for this and not just querying the map service using the buffergeomery that you could get from the GeometryService or GeometryEngine? This would be tons easier using the JS API to do everything.

0 Kudos
JacobSnyder2
New Contributor III

Robert,

Yes, there is a reason. When the buffer is completed, I would like to find the intersections of restaurants,  and would like to add the results to the map as additional graphics. Unless the GeometryService or GeometryEngine that you referring to can do this, in which case I am completely willing to try that instead. Would this be possible to do with GeometryService or GeometryEngine? I would like to accomplish essentially what is shown in the geoprocessing model that I sent to you. Thanks so much again.

-Jacob

0 Kudos
JacobSnyder2
New Contributor III

Also, to clarify, 'Restaurants' is a layer within the map service in the application, and this is what I am trying to perform the intersect on. Thank you.

-Jacob

0 Kudos
RobertScheitlin__GISP
MVP Emeritus

Jacob,

  OK here is the code updated to do this using JS API:

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
    <title> Explore Spotsylvania County </title>
    <link rel="stylesheet" href="http://js.arcgis.com/3.16/esri/css/esri.css">
    <link rel="stylesheet" href="http://js.arcgis.com/3.16/dijit/themes/nihilo/nihilo.css">
    <link rel="stylesheet" href="https://js.arcgis.com/3.16/esri/css/esri.css" />
    <style>
        html,
        body {
            border: 0;
            height: 100%;
            margin: 0;
            padding: 0;
            width: 100%;
            font-size: 14px;
            background-color: #FFF;
            font-family: "Helvetica";
        }

        h1 {
            font-size: 28px;
            font-family: "Helvetica Neue";
            font-weight: bold;
            color: white;
            position: relative;
        }

        #mainwindow {
            background: #ffffff;
        }

        #header {
            background: #3366ff;
        }

        #sidebar {
            width: 310px;
            height: "auto";
        }

        #search {
            display: block;
            position: absolute;
            z-index: 2;
            top: 20px;
            right: 40px;
        }

        .right {
            display: block;
            position: absolute;
            z-index: 2;
            top: 10px;
            right: 40px;
        }

        #layerlist {
            font-family: "Helvetica";
        }

        p {
            font-family: "Helvetica";
        }
    </style>
    <script src="https://js.arcgis.com/3.16/"></script>
    <script type="text/javascript">
        require([
            "dojo/parser",
            "esri/map",
            "esri/layers/ArcGISDynamicMapServiceLayer",
            "esri/InfoTemplate",
            "esri/dijit/Search",
            "esri/dijit/LayerList",
            "esri/dijit/Scalebar",
            "esri/symbols/SimpleMarkerSymbol",
            "esri/Color",
            "esri/graphic",
            "esri/tasks/GeometryService",
            "esri/tasks/locator",
            "dojo/on",
            "dojo/_base/array",
            "dojo/dom",
            "dijit/registry",
            "esri/tasks/BufferParameters",
            "esri/tasks/QueryTask",
            "esri/tasks/query",
            "esri/SpatialReference",
            "esri/graphicsUtils",
            "esri/symbols/SimpleFillSymbol",
            "esri/symbols/SimpleLineSymbol",
            "esri/layers/GraphicsLayer",
            "dijit/layout/BorderContainer",
            "dijit/layout/ContentPane",
            "dijit/layout/AccordionContainer",
            "dijit/layout/AccordionPane",
            "dijit/layout/TabContainer",
            "dijit/form/Button",
            "dijit/form/Select",
            "dijit/form/HorizontalSlider",
            "dijit/form/HorizontalRule",
            "dijit/form/HorizontalRuleLabels",
            "dojo/domReady!"
        ], function(parser, Map, ArcGISDynamicMapServiceLayer, InfoTemplate, Search, LayerList, Scalebar, SimpleMarkerSymbol, Color, Graphic,
          GeometryService, Locator, on, arrayUtils, dom, registry, BufferParameters, QueryTask, Query,
          SpatialReference, graphicsUtils, SimpleFillSymbol, SimpleLineSymbol, GraphicsLayer) {
            parser.parse();

            var map = new Map("map", { //Create the basemap
                basemap: "streets",
                center: [-77.6559716660883, 38.1850243980318],
                zoom: 11
            });
            var gsvc = new GeometryService("http://gis.spotsylvania.va.us/arcgis/rest/services/Utilities/Geometry/GeometryServer");
            var dynamicMapServiceLayer = new ArcGISDynamicMapServiceLayer("http://gis.spotsylvania.va.us/arcgis/rest/services/SoccerTournamentWebApp/SoccerTournamentMap_Initia..."); //Request Congressional Districts dynamic map service layer from ArcGIS Server.
            var bufferGraphicsLayer = new GraphicsLayer({id: "bufferGL"});
            var restGraphicsLayer = new GraphicsLayer({id: "restGL"});
            var locateGraphicsLayer = new GraphicsLayer({id: "locateGL"});
            map.addLayers([dynamicMapServiceLayer, bufferGraphicsLayer, restGraphicsLayer, locateGraphicsLayer]);

            layers = [ //Create layers for insertion into LayerList constructor
                {
                    layer: dynamicMapServiceLayer,
                    showSubLayers: true,
                    showLegend: true,
                    showOpacitySlider: true,
                    visibility: true,
                    id: "Click arrow to the right to expand the layer list and map legend"
                }
            ]

            var onMapLoad = function() {
                var layerList = new LayerList({
                    map: map,
                    layers: layers
                }, "layerlist");
                layerList.startup();
            };

            onMapLoad();

            var scaleBar = new Scalebar({
                map: map,
                attachTo: "bottom-left",
                scalebarStyle: "ruler",
                scalebarUnit: "english"
            });

            var locator = new Locator("http://gis.spotsylvania.va.us/arcgis/rest/services/SoccerTournamentWebApp/AddressLocator/GeocodeServ...");

            var s = new Search({
                map: map,
            }, "search");
            s.startup();

            registry.byId("locate").on("click", locate);

            function locate() {
                if (dom.byId("Street").value == "") {
                    alert("Make sure that you have filled in all of the text boxes to find your location. Restaurants near you cannot be found unless your current location is known.")
                } else if (dom.byId("City").value == "") {
                    alert("Make sure that you have filled in all of the text boxes to find your location. Restaurants near you cannot be found unless your current location is known.")
                } else if (dom.byId("State").value == "") {
                    alert("Make sure that you have filled in all of the text boxes to find your location. Restaurants near you cannot be found unless your current location is known.")
                } else if (dom.byId("ZIP").value == "") {
                    alert("Make sure that you have filled in all of the text boxes to find your location. Restaurants near you cannot be found unless your current location is known.")
                } else {
                    map.graphics.clear();
                    var address = {
                        "Single Line Input": dom.byId("Street").value.toString() + "," + " " + dom.byId("City").value.toString() + "," + " " + dom.byId("State").value.toString() + "," + " " + dom.byId("ZIP").value.toString()
                    };
                    console.log(address)

                    locator.outSpatialReference = map.spatialReference;
                    var options = {
                        address: address,
                        outFields: ["*"]
                    }
                }
                locator.addressToLocations(options, showResults);
            }

            function showResults(results) {
                locateGraphicsLayer.clear();
                var candidate;
                var symbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_SQUARE, 10, null, new Color([255, 0, 0, 0.75]));
                var infoTemplate = new InfoTemplate(
                    "Your Current Location",
                    "Address: ${address}"
                );

                var geom;

                arrayUtils.every(results, function(candidate) {
                    console.log(candidate.score);
                    if (candidate.score > 80) {
                        var attributes = {
                            address: candidate.address,
                            score: candidate.score
                        };
                        geom = candidate.location;
                        var graphic = new Graphic(geom, symbol, attributes, infoTemplate);
                        locateGraphicsLayer.add(graphic);
                        return false;
                    } else {
                        return true;
                    }
                });

                if (geom !== undefined) {
                    map.centerAndZoom(geom, 12);
                }
            };

            registry.byId("findRestaurants").on("click", findRestaurants);
            registry.byId("clearBuffer").on("click", function(){
              bufferGraphicsLayer.clear();
            });
            registry.byId("clearResults").on("click", function(){
              restGraphicsLayer.clear();
            });

            function findRestaurants() {
                var params = new BufferParameters();

                params.geometries = graphicsUtils.getGeometries(locateGraphicsLayer.graphics);

                params.distances = [ dom.byId("distance").value ];
                params.unit = GeometryService.UNIT_STATUTE_MILE;
                params.outSpatialReference = map.spatialReference;
                gsvc.buffer(params, function(geometries){
                  console.info(geometries);
                  var buffer = new Graphic(geometries[0], new SimpleFillSymbol(SimpleFillSymbol.STYLE_NULL, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([255,0,0,0.8]), 2), new Color([0,0,0])));
                  bufferGraphicsLayer.add(buffer);
                  var qTask = new QueryTask("http://gis.spotsylvania.va.us/arcgis/rest/services/SoccerTournamentWebApp/SoccerTournamentMap_Initia...");
                  var query = new Query();
                  query.geometry = geometries[0];
                  query.spatialRelationship = Query.SPATIAL_REL_INTERSECTS;
                  query.outFields = ["*"];
                  query.returnGeometry = true;
                  qTask.execute(query, drawRestaurants);
                });
            };

            function drawRestaurants(results) {
                console.info(results);
                var symbol1 = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_SQUARE, 12, null, new Color([0, 0, 255]));
                var infoTemplate1 = new InfoTemplate(
                  "${NAME}",
                  "Address: ${FULLADDR}"
                );

                //var features = results[0].value.features;
                var features = results.features;
                for (var f = 0; f < features.length; f++) {
                    var feature = features;
                    feature.setSymbol(symbol1);
                    feature.setInfoTemplate(infoTemplate1);
                    restGraphicsLayer.add(feature);
                }
            };

        });
    </script>
</head>

<body class="nihilo">
    <div id="mainwindow" data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design:'headline',gutter:false,liveSplitters: true" style="width: 100%; height: 100%; margin: 0;">
        <div id="header" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'top',splitter:true" style="height:70px; background-color:#001F4C;">
            <h1> Explore Spotsylvania County, Virginia: An Interactive Experience for County Visitors  </h1>
            <div>
                <img src="http://www.spotsylvaniamuseum.org/data/layout/images/museum/county_seal.png" class="right">
            </div>
        </div>
        <div id="map" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'center',splitter:true">
            <div id="search"></div>
        </div>
        <div id="sidebar" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region: 'left', splitter:true">
            <div data-dojo-type="dijit/layout/AccordionContainer" title="Control visibility of layers, see map legend, or find restaurants near you">
                <div data-dojo-type="dijit/layout/AccordionPane" title="Layer list, map legend, and map opacity slider">
                    <div id="layerlist"></div>
                </div>
                <div data-dojo-type="dijit/layout/AccordionPane" title="Find Restaurants Near You">
                    <p> How many miles are you willing to travel? Type a mileage number in the box below. </p>
                    <input id="distance"></input><button id="clearBuffer" data-dojo-type="dijit/form/Button">Clear</button>
                    <br>
                    <br>
                    <p> Where are you right now? Type your address information below. </p>
                    <p>Street</p>
                    <input id="Street"></input>
                    <p>City</p>
                    <input id="City"></input>
                    <p>State</p>
                    <input id="State" value="Va"></input>
                    <p>ZIP</p>
                    <input id="ZIP"></input>
                    <br>
                    <button id="locate" data-dojo-type="dijit/form/Button">Find your location</button>
                    <p> Ready to find restaurants? Click the button below </p>
                    <button id="findRestaurants" data-dojo-type="dijit/form/Button">Find restaurants near your location</button>
                    <button id="clearResults" data-dojo-type="dijit/form/Button">Clear</button>
                    <div id="newLegend"></div>
                </div>
            </div>
        </div>
    </div>
</body>

</html>
JacobSnyder2
New Contributor III

Robert,

This was exactly what I needed. Thanks so much for your time and help.

-Jacob

0 Kudos