• Is managing your map layers a bit of a hassle?
  • Would you like to be able to turn layers on and off with the click of a button?

I had a request from a user last week to be able to turn map layers on and off with the click of a button.  I knew this would require a bit of IronPython, so I turned to one of my Ruths.ai colleagues, Lucas Wood, who was able to supply a few simple lines of code to make this work.  You can download a example DXP here: Toggle Script  Here are the steps needed to apply this solution.

  1. In the map chart, right click on the Map > Properties
  2. Go to the Layers menu
  3. Select the desired layer
  4. Click the Settings button
  5. Go to the General menu and name the layer something that is distinctive but simple, such as ‘Swedish’
  6. Click Close to exit
  7. Add a text area to the page
  8. Right click and select ‘Edit Text Area’
  9. Click the Add Action Control button
  10. Name the control as desired, such as “Toggle Sweden Off/On”
  11. Click the Script button the left hand side of the dialog
  12. Click New
  13. Name the script, such as ‘toggle script’
  14. Copy and paste the code below
  15. Edit the script so that the name of the script is specified in the 5th line of code within quotation marks
  16. Add a Script parameter called “viz”.
  17. Set the ‘Type:’ drop down to ‘Visualization’
  18. Select the map from the ‘Select visualization’ drop down
  19. Click Ok to exit
  20. Run the script to make sure there are no errors
  21. Click OK twice to exit
  22. The button should now work to toggle the feature layer on and off

 

Code:

from Spotfire.Dxp.Application.Visuals import *

v = viz.As[VisualContent]()
for l in v.Layers:
if l.Title == “Swedish”:
if l.Enabled == True:
l.Enabled = False
else:
l.Enabled = True

I also want to note two more things before wrapping up.

  1. This script should work for any layer — feature, marker, WMS, etc — because the layer type is not specified, only the layer name.
  2. The same script will work to turn off multiple layers, just copy and paste, and specify each layer you want to turn on and off with one click of the button.

Happy scripting!!

Written by Julie Schellberg of Big Mountain Analytics, LLC
Residing in Whitefish, MT, an analytics partner with Ruths.ai. Specializing in Spotfire analytics, dabbling in Power BI and R.