Add layer via URL (JS API)

1691
12
Jump to solution
06-09-2017 03:37 PM
ChristopherSchreiber
Occasional Contributor II

Hello all!

I am attempting to add a layer via a URL that the user provides via a text box in the UI. 

I can capture the layer URL and work with it in JS, but when I attempt to use it to create a layer, I get the following error in the console "Uncaught TypeError: a.hasChildNodes is not a function"

Here is the JS code that attempts to use the entered URL to create a new Dynamic Map Service Layer:

NOTE: The URL I have been working with is: nowcoast/mapoverlays_political (MapServer) 

        var layerURLbox = registry.byId("LayerURLbox");
        on(dom.byId("layerSubmit"), "click", getValue);

        function getValue() {
            console.log(layerURLbox.get("value"));
            layerValue = layerURLbox.get("value")
            getLayerType(layerValue);
        }

        function getLayerType(layerURLValue) {

            if (layerURLValue.indexOf("MapServer")) {
                console.log("Map Service");
                var layer = new ArcGISDynamicMapServiceLayer(layerURLValue, {
                    id: "Test"
                })
                map.addLayer(layer);
            }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

The console error I mentioned occurs on line 14, where I attempt to create the new ArcGISDynamicMapServiceLayer.

It does not make it to map.addLayer.

If anyone has any pointers or has tried this before, please let me know!

Thank you!

Chris

0 Kudos
12 Replies
ChristopherSchreiber
Occasional Contributor II

Hello all,

I have gotten the code to work with the following layer types:

  1. Map Services
  2. Feature Services
  3. OGC WMS Services*
  4. CSV Layers*
  5. KML Layers*
  6. Image Service Layers

* = require a proxy to be set up. The Esri Resource Proxy can be used. 

Here is the code: (URL comes from a textbox)   

       function getLayerType(url) {
            var layerType;
            if (url.includes("/FeatureServer"))
                layerType = "FeatureServer";
            else if ((url.includes("wms") || (url.includes("WMS"))) || (url.includes("/MapServer") && url.includes("WMS")))
                layerType = "ogcWms";
            else if (url.includes(".csv"))
                layerType = "CSV";
            else if (url.includes(".kml"))
                layerType = "KML";
            else if (url.includes("/ImageServer"))
                layerType = "ImageServer";
            else if (url.includes("/MapServer") && layerType != "ogcWms")
                layerType = "MapServer";

            addLayer(url, layerType);
        }

        function addLayer(layerURLValue, layerType) {
            var date = getDate();
            switch (layerType) {
                case "FeatureServer":
                    console.log("Feature Service");
                    //Check to see if the URL ends with a number (for a specific sublayer), if it does not, load all sublayers.
                    var match = layerURLValue.match(/\d+$/);
                    if (match) {
                        var layersRequest = esriRequest({
                            url: layerURLValue,
                            content: { f: "json" },
                            handleAs: "json",
                            callbackParamName: "callback"
                        });
                        layersRequest.then(
                          function (response) {
                              console.log(response);
                              var popupTitle;
                              if (response.displayField)
                                  popupTitle = "{" + response.displayField + "}";
                              else
                                  popupTitle = response.name;

                              var layer = new FeatureLayer(layerURLValue, {
                                  mode: FeatureLayer.MODE_ONDEMAND,
                                  outFields: ["*"],
                                  infoTemplate: new PopupTemplate({ title: popupTitle, description: "{*}" })
                              })
                              var mapLyrNam;
                              if (response.name)
                                  mapLyrNam = response.name;
                              else
                                  mapLyrNam = date;
                              var layerObj = {
                                  id: mapLyrNam,
                                  layer: layer,
                              };
                              addLyrToMap(layerObj, layer); 
                    }, function (error) {
                        console.log("Error: Esri Request Failed. Feature Service Layer is unable to load. Error Message: ", error.message);
                        alert("Layer can not be added. See Console for details.");
                    });
                    //Load all sublayers
                    } else {
                        var layersRequest = esriRequest({
                            url: layerURLValue,
                            content: { f: "json" },
                            handleAs: "json",
                            callbackParamName: "callback"
                        });
                        layersRequest.then(
                          function (response) {
                              console.log(response);
                              response.layers.forEach(function (sublayer) {
                                      var layer = new FeatureLayer(layerURLValue + "/" + sublayer.id, {
                                          mode: FeatureLayer.MODE_ONDEMAND,
                                          outFields: ["*"],
                                          infoTemplate: new PopupTemplate({ title: sublayer.name, description: "{*}" })
                                      })
                                      var layerObj = {
                                          id: sublayer.name,
                                          layer: layer,
                                      };
                                      addLyrToMap(layerObj, layer);
                              });
                          }, function (error) {
                              console.log("Error: Esri Request Failed. Feature Service Layer is unable to load. Error Message: ", error.message);
                              alert("Layer can not be added. See Console for details.");
                          });
                    }
                    break;
                case "MapServer":
                    console.log("Map Service");
                    var match = layerURLValue.match(/\d+$/);
                    if (match) {
                        alert("Unfortunatly, loading specific Sublayers for a Map Service is not currently supported. Please remove the specific sublayer from the end of the URL, and try again.");
                        break;
                    }
                    var layer;
                    var layerPopup = {};
                    var layersRequest = esriRequest({
                        url: layerURLValue,
                        content: { f: "json" },
                        handleAs: "json",
                        callbackParamName: "callback"
                    });
                    layersRequest.then(
                      function (response) {
                          console.log("Success: ", response);
                              var sublayerCounter = -1;
                              response.layers.forEach(function (sublayer) {
                                  console.log(sublayer.name);
                                  sublayerCounter++
                                  layerPopup[sublayerCounter] = {
                                      infoTemplate: new InfoTemplate(sublayer.name, "${*}"),
                                      layerUrl: layerURLValue + "/" + sublayerCounter
                                  }
                              });
                              layer = new ArcGISDynamicMapServiceLayer(layerURLValue, {
                                  id: response.mapName,
                                  infoTemplates: layerPopup
                              });
                          var mapLyrNam;
                          if (response.documentInfo == undefined || response.documentInfo.Title == "" || response.documentInfo.Title == undefined)
                              mapLyrNam = response.mapName;
                          else
                              mapLyrNam = response.documentInfo.Title;
                          var layerObj = {
                              id: mapLyrNam,
                              layer: layer,
                          };
                          addLyrToMap(layerObj, layer);
                      }, function (error) {
                          console.log("Error: Esri Request Failed. Map Service Layer is unable to load. Error Message: ", error.message);
                          alert("Layer can not be added. See Console for details.");
                      });
                    break;
                case "ogcWms":
                    console.log("OGC Web Map Service");
                    var layer = new WMSLayer(layerURLValue, {
                        id: date
                    });
                    var layerObj = {
                        id: layer.id,
                        layer: layer
                    };
                    addLyrToMap(layerObj, layer);
                    break;
                case "CSV":
                    console.log("CSV Layer");
                    var csvName = layerURLValue.substring(layerURLValue.lastIndexOf('/') + 1);
                    var layer = new CSVLayer(layerURLValue, {
                        id: csvName,
                        infoTemplate: new PopupTemplate({ title: csvName, description: "{*}" })
                    });
                    var layerObj = {
                        id: csvName,
                        layer: layer
                    };
                    addLyrToMap(layerObj, layer);
                    break;
                case "ImageServer":
                    console.log("Image Service");
                    var layer;
                    var layersRequest = esriRequest({
                        url: layerURLValue,
                        content: { f: "json" },
                        handleAs: "json",
                        callbackParamName: "callback"
                    });
                    layersRequest.then(
                      function (response) {
                          layer = new ArcGISImageServiceLayer(layerURLValue);
                          var layerObj = {
                              id: response.name,
                              layer: layer,
                          };
                          addLyrToMap(layerObj, layer);
                      }, function (error) {
                          console.log("Error: Esri Request Failed. Image Service Layer is unable to load. Error Message: ", error.message);
                          alert("Layer can not be added. See Console for details.");
                      });               
                    break;
                case "KML":
                    console.log("KML");
                    var kmlName = layerURLValue.substring(layerURLValue.lastIndexOf('/') + 1);
                    var layer = new KMLLayer(layerURLValue, {
                        id: date
                    });
                    var layerObj = {
                        id: kmlName,
                        layer: layer
                    };
                    addLyrToMap(layerObj, layer);
                    break;
            }
        }

        function addLyrToMap(layerObj, layer) {
            mapInfoLyrs.push(layerObj);
            map.addLayer(layer);
            map.legendList.refresh();
        }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

For clarification:

The "mapInfoLyrs" array is used by the Esri "LayerList" to keep track of what layers are on the map. See this link for more details. 

The "legendList" object is the Esri "LayerList" widget. When a new layer is added to the map, it must be refreshed.

0 Kudos
KenBuja
MVP Honored Contributor

Nice implementation. One observation on the getLayerType function. In this condition

else if (url.includes("/MapServer") && layerType != "ogcWms")

you're checking layerType. However, that's always going to be undefined from the initial declaration of layerType, since if it's set in this condition

else if ((url.includes("wms") || (url.includes("WMS"))) || (url.includes("/MapServer") && url.includes("WMS")))

all other if statements will be skipped.

ChristopherSchreiber
Occasional Contributor II

Thanks Ken Buja‌! I must have left my thinking cap at home that day... 

0 Kudos