0

I am using javascript mapping libraries to make a web map.

I have buttons that will toggle different layers and basemaps on/off. When a button is pressed, a unique buttonId is passed to this function. From there, I would like to reference a json dictionary that pulls the layers and basemaps for the relevant buttonId and shows that information on the map.

In my sample code below, there is an issue with obj.name.buttonId.show, whereas obj.name.button1.show would return a valid value. How do I resolve this? In other words, how do I pass the variable buttonId in a method to retrieve its parameters? Code:

function(arg) { 

    var json = '{"name":{"button1": {"show": "streets", "basemap": "dark-gray"}, "button2": {"show": "railroads", "basemap": "terrain"}, "button3": {"show": "rivers", "basemap": "terrain"} }}';
    var obj = dojo.fromJson(json);
    buttonId = arg.target.id

        if (obj.name == buttonId){
            this.map.getLayer(obj.name.buttonId.show).show()
            this.map.setBasemap(obj.name.buttonId.basemap) 
        else
            pass
};

I am trying to avoid writing if/then statements for every button, hence why I am taking this approach.

  • Don't use JSON strings. Just create a simple object literal: `var obj = {nme: {button1:…, button2:…}};` – Bergi Jun 20 '17 at 01:15
  • @Bergi, would the "..." be functions? Is this the best way if each button will have a very similar function--ie showing a particular layer and basemap? I want to avoid writing the same code for each button scenario – user2094378 Jun 20 '17 at 02:24
  • You could use any kind of value, including functions, but those values you currently have seem totally fine. – Bergi Jun 20 '17 at 03:06

0 Answers0