Select to view content in your preferred language

Geometry Service Question

6114
27
Jump to solution
01-09-2017 05:22 PM
LloydBronn
Frequent Contributor

I've set up a blank map where I click on any point and a popup displays the lat/lon coordinates and a link to a geoprocessing service. Right now I'm using this example to get everything working. Eventually I'll make my own geoprocessing tool that returns custom charts based on the lat/lon coordinates from the click event. When I click the link in the popup, it just says "calculating" and never returns a population. Chrome creates a debug text file with a bunch of errors. I'm pretty sure this happens because I haven't specified a geometry service in my script. 

<!DOCTYPE html>
<html>  
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
    <title>Forecast Analysis</title>
    <link rel="stylesheet" href="http://js.arcgis.com/3.19/dijit/themes/claro/claro.css">
    <link rel="stylesheet" type="text/css" href="http://js.arcgis.com/3.19/esri/css/esri.css">
    <style>
      html, body, .container, #map {
            height: 700px;
            width: 100%;
            margin: 0;
            padding: 0;
            margin: 0;
            font-family: "arial";
        }          
       .esriScalebar {
        padding: 20px 20px;
      }
       
       #HomeButton {
      position: absolute;
      top: 95px;
      left: 20px;
      z-index: 50;
    }
       
          
          .esriPopup .titleButton.maximize {
        display: none;

      }
       .esriPopup .sizer {
          position: relative;
          width: 150px;
          z-index: 1;
          }     
                    
          .esriPopup .contentPane {
        text-align: left;
          
      }
          
       
       #search {
         display: block;
         position: absolute;
         z-index: 2;
         top: 20px;
         left: 75px;
      }
       
       .esriPopup .actionsPane .zoomTo{     
       display: none; 
       }  
     
 
    </style>
    <script src="http://js.arcgis.com/3.19/"></script>
    <script>
      var map;

      require([
         "esri/config",
        "esri/map",
          "esri/arcgis/utils",
        "esri/tasks/Geoprocessor",
        "esri/tasks/GeometryService",
        "esri/tasks/BufferParameters",
          "esri/graphic",
          "esri/geometry/webMercatorUtils",
          "esri/SpatialReference",
        "esri/tasks/FeatureSet",
        "esri/symbols/SimpleFillSymbol",
          "esri/dijit/Popup",
        "esri/dijit/PopupTemplate",
          "esri/InfoTemplate",
          "esri/layers/FeatureLayer",
          "esri/symbols/SimpleMarkerSymbol",
          "esri/symbols/SimpleLineSymbol",
          "esri/dijit/BasemapGallery",
          "esri/dijit/HomeButton",
          "esri/dijit/Search",
          "dojo/dom-construct",
        "esri/Color",
          "dojo/dom",
          "dojo/dom-attr",
          "dojo/query",
          "dojo/on",           
          "dojo/parser",
          "dijit/layout/BorderContainer",
        "dijit/layout/ContentPane",
          "dijit/TitlePane",
        "dojo/domReady!"
      ], function (
        esriConfig, Map,  arcgisUtils, Geoprocessor, GeometryService,
        BufferParameters, Graphic, webMercatorUtils,  SpatialReference,
        FeatureSet, SimpleFillSymbol, Popup, PopupTemplate, 
          InfoTemplate, FeatureLayer, SimpleMarkerSymbol,
          SimpleLineSymbol, BasemapGallery, HomeButton, Search, domConstruct, 
          Color, dom, domAttr, query, on, parser
      ) {
          parser.parse();

            map = new Map("map", {
            basemap: "gray",
               center: [10, 40],
               maxZoom: 18,
            minZoom: 3
          });
            
            var home = new HomeButton({
          map: map
         }, "HomeButton");
         home.startup();
           
           var search = new Search({
            map: map,
               showInfoWindowOnSelect: false,
               enableLabel: false,
               enableHighlight: false
         }, "search");
         search.startup();
            
           var popupOptions = {
            markerSymbol: new SimpleMarkerSymbol("circle", 32, null,
              new Color([0, 0, 0, 0.25])),
            marginLeft: "20",
            marginTop: "20"
          };
          
      
            
            var basemapGallery = new BasemapGallery({
             showArcGISBasemaps: true,
             map: map
           }, "basemapGallery");
           basemapGallery.startup();
            
            basemapGallery.on('load',function(){  
          basemapGallery.remove('basemap_2');  
          basemapGallery.remove('basemap_4');
          basemapGallery.remove('basemap_5'); 
          basemapGallery.remove('basemap_0'); 
          basemapGallery.remove('basemap_1');
          basemapGallery.remove('basemap_11');
     }); 
       
          basemapGallery.on("selection-change",function(){
           var tp = dijit.byId("TitlePane");
         if(tp != null){tp.toggle();}
         });
       
           basemapGallery.on("error", function(msg) {
            console.log("basemap gallery error:  ", msg);
          });
       
         basemapGallery.on("load", function(msg) {
        for (b=0;b<map.basemapLayerIds.length;b++){
          var lyr = map.getLayer(map.basemapLayerIds[b]);
          if(lyr._isRefLayer){
            refLayerId = lyr.id;
          }
        }
      });
       
       map.on("load", function() {
          //after map loads, connect to listen to mouse move & drag events
          map.on("mouse-move", showCoordinates);
          map.on("mouse-drag", showCoordinates);
        });

        function showCoordinates(evt) {
          //the map is in web mercator but display coordinates in geographic (lat, long)
          var mp = webMercatorUtils.webMercatorToGeographic(evt.mapPoint);
          //display mouse coordinates
          dom.byId("info").innerHTML = "Longitude: " + mp.x.toFixed(3) + "    " + "Latitude: " + mp.y.toFixed(3);
        };
               
          map.on("click", function(evt){
            var mp = webMercatorUtils.webMercatorToGeographic(evt.mapPoint);
            var x = mp.x.toFixed(3);
            var y = mp.y.toFixed(3);
          map.graphics.clear();
          var graphic = new Graphic(evt.mapPoint);

          map.graphics.add(graphic);
          map.infoWindow.setFeatures([graphic]);

          map.infoWindow.setContent("Longitude: " + x.toString() + " <br>Latitude: " + y.toString());
          map.infoWindow.show(evt.mapPoint)
        });

          var link = domConstruct.create("a",{
                "class": "action", 
                "id": "statsLink",
                "innerHTML": "Population", //text that appears in the popup for the link 
                "href": "javascript: void(0);"
              }, query(".actionList", map.infoWindow.domNode)[0]);
          on(link, "click", calculatePopulation);
            
            window.gp = new Geoprocessor("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Population_World/GPServ...");
            
            function calculatePopulation(evt){
            //display a message so user knows something is happening
            domAttr.set(dom.byId("statsLink"), "innerHTML", "Calculating...");

            //Get the feature associated with the displayed popup and use it as 
            //input to the geoprocessing task. The geoprocessing task will calculate 
            //population statistics for the area within the specified buffer distance. 
            var feature = window.map.infoWindow.getSelectedFeature();
            
            var param = new BufferParameters();
            param.geometries = [webMercatorUtils.webMercatorToGeographic(feature.geometry)];

            param.distances = [10]; //buffer distance
            param.unit = GeometryService.UNIT_KILOMETER;
            param.bufferSpatialReference = new SpatialReference({"wkid": 4326});
            param.outSpatialReference = new SpatialReference({"wkid": 102100});
            param.geodesic = true;

            config.defaults.geometryService.buffer(param, function(geometries){

              var graphic = new Graphic(geometries[0]);
              graphic.setSymbol(new SimpleFillSymbol().setColor(new Color([0,255,255,0.25])));

              window.map.graphics.add(graphic);
 
              //Use the buffered geometry as input to the GP task 
              var featureSet = new FeatureSet();
              featureSet.geometryType = "esriGeometryPolygon";
              featureSet.features = [graphic];
              var taskParams = {
                "inputPoly": featureSet
              };
              window.gp.execute(taskParams, gpResultAvailable, gpFailure);


            });
          }

          function gpResultAvailable(results, messages){
            domAttr.set(dom.byId("statsLink"),"innerHTML", "Population");
            //clear any existing features displayed in the popup 
            window.map.infoWindow.clearFeatures();

            //display the query results 
            var content = "";
            if(results.length > 0){
              content = "Population = " + results[0].value.features[0].attributes.SUM;
            }else{
              content = "No Results Found";
            }
            window.map.infoWindow.setContent(content);
          }
          function gpFailure(error){
            domAttr.set(dom.byId("statsLink"),"innerHTML", "Population");

            var details = domConstruct.create("div", {
              "innerHTML": "Population = " + error
            }, query(".break", window.map.infoWindow.domNode)[0],"after" );
            console.error("Error occurred: ", error);
          }

        
          
     
     });
    </script>
  </head>

  <body class="claro">
  
    <div data-dojo-type="dijit/layout/BorderContainer" data-dojo-props="design:'headline'"
         style="width: 100%; height: 100%; margin: 0;">
           
      <div id="map" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'center'">
       
       <div id="search"></div>
             
             <span id="info" style="font-family:arial;position:absolute;left:15px; bottom:30px; background-color:lightgray; opacity: 0.70; z-index:50;"></span>
             
             <div id="HomeButton"></div>
             
          <div style="position:absolute; left:15px; bottom:60px; z-Index:999;">
          
     <div data-dojo-type="dijit/TitlePane" id = "TitlePane" style="font-family:arial;background-color:lightgray"
             data-dojo-props="title:'Switch Basemap', closable:true, open:false">
                
            <div id="basemapGallery"></div>
               
               
             </div>
          </div>   
      </div>
    </div>
  </body>

</html>

If I follow the GP tool in popup example and I add a geometry service from my company ArcGIS server or this ESRI sample server, my popup disappears, as does my lat/lon tracker. The popup and lat/lon tracker incorporate webmercator utils to convert XY to lat/lon. I'm not sure how to proceed.  

config.defaults.geometryService = new GeometryService("https://utility.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");
config.defaults.io.proxyUrl = "/proxy/";
0 Kudos
27 Replies
RobertScheitlin__GISP
MVP Emeritus

Lloyd,

  Window is a global JavaScript variable that does not get declared (it just exists), so you need to add that code back.

The looks of it is that you are using a https url for accessing your app and thus the proxy and you should just be using an http url.

0 Kudos
LloydBronn
Frequent Contributor

OK. I'll add window back. All of my URLs in the JavaScript and the proxy config are HTTP. The errors all display them as HTTPS.

0 Kudos
RobertScheitlin__GISP
MVP Emeritus

Lloyd,

  So when you launch your app in the browsers address bar are you using a http or https url?

0 Kudos
LloydBronn
Frequent Contributor

I'm just opening it directly in the browser from the local html file.

0 Kudos
RobertScheitlin__GISP
MVP Emeritus

So are you saying that you have file:// in the url? If so you really need to break that habit as lots of html code and JS sample will not work in that fashion. You need to use http://localhost or better yet http://machinename and have your html files in a IIS virtual directory.

0 Kudos
LloydBronn
Frequent Contributor

OK. I'll migrate it to our server.

I keep getting errors like:

"http://<ourserver>/DotNet/proxy.ashx?https://sampleserver1.arcgisonlin…ices/Demographics/ESRI_Population_World/GPServer/PopulationSummary... Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."

I found threads that reference adding custom headers to the web.config file. I've tried adding this:

<customHeaders>  
    <remove name="Access-Control-Allow-Origin" />  
</customHeaders> 

I've also tried this. 

<customHeaders>  
    <add name="Access-Control-Allow-Credentials" value="true" />  
    <add name="Access-Control-Allow-Origin" value="http://sub.domain.com" />  
</customHeaders> 

Neither has worked. I'm adding them to the web config file in the wwwroot DotNet folder where I installed the proxy. Should I add them somewhere else? No matter what I do I get the same error. 

0 Kudos
RobertScheitlin__GISP
MVP Emeritus

Lloyd,

   No, you do not have to migrate it to your server you just use the IIS in your workstation for testing. If you set a virtual directory on your workstations IIS to a folder that has the html file you are developing (I actually have a folder called JS_Workspace on my C drive that is set as the destination of my virtual directory with an alias of "js") then you can use a url like http://machinename/js/yourhtmlfile.html in your addressbar and test you code using your local web server.

LloydBronn
Frequent Contributor

Once I removed all those custom header tags and moved the script to IIS, it worked! I'll develop my scripts there from now on. Thanks for all your help, Robert. 

0 Kudos