Select to view content in your preferred language

Having Issue on Adding/Removing Service Layer by Checkbox

2807
3
Jump to solution
10-23-2015 02:29 PM
BruceGreen
Occasional Contributor

Can you please take a look at this code and let me know how I can add and remove some layers based on their index number in a Map Service? I tried this before but it is not working!

Layer 52 : <input type="checkbox" value=52 name="overlayLayers"><br  />
Layer 53 : <input type="checkbox" value=53 name="overlayLayers"><br  />

   var service ="http://renewablestoolbox.biol.sfu.ca/rorapp/rest/services//RORApp/MapServer";
   
    $('input:checkbox[name=overlayLayers]').on('change', function(){
    if($(this).is(':checked')){
        var index = $(this).val();
        map.addLayer(service+index);
    }
    else{
        var index = $(this).val();
        map.removeLayer(service+index);
        }
});
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
RobertScheitlin__GISP
MVP Emeritus

Behrouz,

   The main issue in your code is you are trying to add a string to the map and not an actual layer.  Try something like map.addLayer(new FeatureLayer(service+index));  and map.removeLayer is expecting an actual layer as well.

Look at the docs for map.getLayer:

Map | API Reference | ArcGIS API for JavaScript | getLayer

This would mean that you need to assign an Id to the layer when it is added.

View solution in original post

0 Kudos
3 Replies
RobertScheitlin__GISP
MVP Emeritus

Behrouz,

   The main issue in your code is you are trying to add a string to the map and not an actual layer.  Try something like map.addLayer(new FeatureLayer(service+index));  and map.removeLayer is expecting an actual layer as well.

Look at the docs for map.getLayer:

Map | API Reference | ArcGIS API for JavaScript | getLayer

This would mean that you need to assign an Id to the layer when it is added.

0 Kudos
BruceGreen
Occasional Contributor

Thanks Robert but I tried to do what you recommend but I am not sure why I am getting this error

err.png

I already register the  "esri.layers.FeatureLayer", and  function(Map, FeatureLayer,

but still getting this!

0 Kudos
RobertScheitlin__GISP
MVP Emeritus

Behrouz,

You say that you have registered "esri.layers.FeatureLayer". This leads me to believe that you are developing using the old legacy style and not AMD Legacy code. Legacy will not be supported any more when JS API 4.0 comes out and you should quit using Legacy style. It would help to see more of your code.

Just looking at the snippets you provided you also have an issue with the service url.

You have:

var service ="http://renewablestoolbox.biol.sfu.ca/rorapp/rest/services//RORApp/MapServer"; 

It should be:

var service ="http://renewablestoolbox.biol.sfu.ca/rorapp/rest/services/RORApp/MapServer/"; 

Notice double slash removed and a slash added to the end of the url since you are just adding the layer id to this string.

0 Kudos