TransWikia.com

Dynamically changing fillColor variables in leaflet

Geographic Information Systems Asked by Andrewchi on June 24, 2021

When I want to style a polygon using a property the traditional way is to assign a function that returns a style object. Within that object you assign the fillColor property to a getColor function

fillColor: getColor (feature.properties.population)

Is this the only way?
What if I want to style layers by dynamically changing the fill variable in a case where a drop down has 100 feature properties?

One Answer

One way of dynamically styling vector layer would be to have some global variable and then use it within style function to select desired style. Upon global variable change, .setStyle vector layer method has to be used to update style.

This could look then something like this:

var selectedPropertyNo = 0;

function style(feature) {
  var fillColor;
  if (selectedPropertyNo == 1)
    fillColor = getDensityColor(feature.properties.density);
  else {
    fillColor = getIncomeColor(feature.properties.income);
  }
  return {
    weight: 2,
    opacity: 1,
    color: 'white',
    dashArray: '3',
    fillOpacity: 0.7,
    fillColor: fillColor
  };
}

function changeLayerStyle(propertyNo) {
  selectedPropertyNo = propertyNo;
  vectorLayer.setStyle(style);
}

Answered by TomazicM on June 24, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP