7

I am new with leaflet and I need help to change the color of a polygon on a choropleth map dynamically.

In my website I have an slider, and depending on the position of the handle, the colors of the polygons of the map vary. So I need to make these changes automatically.

I have found two options to do so, but they are too slow.

  • The first solution is to remove all the map and to create another one with the updated information. As the map is formed of several poligons it takes too much time so it is not a good solution.

  • The second one is to introduce a new layer to the map with the information of the updated polygons above the old ones. Although at first it works well after several changes the map goes slower.

I have other two posible solutions but I don't know how to implement them:

  • The first one is to use "onEachFeature" function. However as in my case the changes of the map are not related with the mouse events I don't know how to activate it.

  • The second one is to make the changes on the poligons of the map manually, but I don't know if it would be posible.

I would be grateful if someone could give me a solution to my problem.

PD: I try to explain my problem as well as possible, however if there is something that you do not understand I could explain it with more details.

2

If you are making the choropleth map using geoJSON layers..say for example

geoJsonLayer = L.geoJson(data, {style: style}).addTo(map);
function style(region) {
  return {
     fillColor: somefunctionforcolor(region.properties.somevariable),
  };
}

Now on changing the postion of the slider you can call a function like the following and apply whatever updated style you want:

function changeColors(){
   geoJsonlayer.setStyle(updatedStyle)
}
0

Did you look at this? It might be of help. Generally you need to keep reference to features you add to map, so you can change them when needed. You can store them as a L.LayerGroup for example. Than you just iterate over features and set their style to whatever you want.

Also, a functional jsfiddle example would be really useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.