This sample demonstrates how to change the variable driving a visualization in a renderer while retaining all symbology and other renderer configurations previously made to the layer.
In this case, the layer represents temperature anomaly data from 1880 to 2018. The data is stored in fields F1880, F1881, …, F2018. The map author configured the renderer in Map Viewer to visualize the data based on the year 2018.
Once loaded, this sample updates the renderer to return data from an Arcade expression rather than a static field (e.g. F2018). The expression uses the $view.timeProperties variable and Year() function to find the year selected by the user with the Time Bar component. As the user slides the slider thumb, the Arcade expression will re-execute and thus update the layer’s renderer to return the data for the field corresponding to the Time Bar value.
const layer = view.map.layers.getItemAt(0); const renderer = layer.renderer.clone();
const sizeVisualVariable = renderer.visualVariables.find((visualVariable) => visualVariable.type === "size");
// Returns the value of the "F{year}" field based on the time bar slider's value. // This expression will re-execute every time the time bar slider's value changes const valueExpression = ` Expects($feature, "F*"); if(HasValue($view, ["timeProperties", "currentEnd"])){ var y = Year($view.timeProperties.currentEnd); var value = $feature["F" + y]; return value; } return null; `; // Update legend text to be more user friendly const valueExpressionTitle = "Are temperatures significantly warmer or colder than normal?";
// Replace the field with the valueExpression so the user can dynamically // explore the data as it changed from year to year renderer.field = null; renderer.valueExpression = valueExpression; renderer.valueExpressionTitle = valueExpressionTitle;
// Since this is an above-and-below size renderer, we need to update // the size visual variable to reflect the new valueExpression sizeVisualVariable.field = null; sizeVisualVariable.valueExpression = valueExpression; sizeVisualVariable.valueExpressionTitle = valueExpressionTitle; // Update legend text to be more user friendly sizeVisualVariable.stops[0].label = "Colder"; sizeVisualVariable.stops[2].label = "Normal"; sizeVisualVariable.stops[4].label = "Warmer";
renderer.visualVariables = [sizeVisualVariable]; layer.renderer = renderer;