2

I"m trying to teach my self coding for some mapping work, and I cannot seem to wrap my head around this.

I have a JavaScript function that is called from a button: This code connects my button using DOJO:

on(dom.byId("metro"), "change", updateLayerVisibility);

The following code correctly turns my layer off (metro is defined elsewhere)

function updateLayerVisibility(){

metro.setVisibility(false);
  }

However if i try to use a variable I get an error that "test.setvisiblity is not a function"

function updateLayerVisibility(){
var test = "metro";
test.setVisibility(false);
}

So my question is what is the difference between these two? why isn't "metro" substituted for "test"? If its because the variable is a string, what should it be converted to.

Thanks (and sorry for the strange question)

3 Answers3

1

In your above example, test is just a string and strings don't have a method named setVisibility. However a metro object (apparently) does.

The methods available to strings can be seen here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Methods

bvaughn
  • 13,300
  • 45
  • 46
  • OK, how would I programmatically change "test" to "metro" and have it work? For example, I tried 'var text = test + ".setVisibility(False); text' which didn't work. – Aubin Maynard Mar 19 '15 at 19:56
1

metro is an identifier. In that context it is a variable. It will have a value, in this case, that value is an object with a property setVisibility that has (in turn) a value that is a function.

test is also an identifier and a variable. It has a value, which is the string "metro". The string has no connection to the variable metro and it doesn't have a setVisibility property.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

The key part of your question is where you say "metro is defined elsewhere". As already suggested by others, your metro object is not just a string with a value (as your test object is) but a reference to a particular type of object which has particular functions such as setVisibility.

I think I see what you want to do: programmatically turn individual layers on and off. If you know the layer ID then you can get a reference to a layer using:

var layer = map.getLayer(id);

(where map is your reference to the ArcGIS map object and id is the string name of the layer to return. So if you had a layer with the id "metro" you would get it with:

var layer = map.getLayer("metro");

Here you can substitute the string passed in to the getLayer method for any other string value that represents the id of a layer you want.

Once you've got your layer object you can then set it's visibility in the same way as you were with the metro layer reference:

layer.setVisibility(false);

Hope this helps!

Kate
  • 1,556
  • 1
  • 16
  • 33