2
\$\begingroup\$

I have got 2 working codes, where one is a bit longer and another a bit shorter. Is it some way to bind all these layers as a one group?

The first one is:

 map.on('zoomend', function() {
if (map.getZoom() <6){
        map.removeLayer(job);
    }else{
    map.addLayer(job);
    }
    if (map.getZoom() <7){
        map.removeLayer(job2);
    }else{
    map.addLayer(job2);
    }
    if (map.getZoom() <8){
        map.removeLayer(job3);
    }else{
    map.addLayer(job3);
    }
  });

and another one

   map.on('zoomend', function() {
     if (map.getZoom() <8){
        map.removeLayer(job);
    }
    if (map.getZoom() <8){
        map.removeLayer(job2);
    }
    if (map.getZoom() <8){
        map.removeLayer(job3);
    }
     else {
        map.addLayer(job);
        map.addLayer(job2);
        map.addLayer(job3);
    }
   });

I would like to avoid this kind of repeats, as I am going to have multitude of layers in the future.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

In your case a better way is using a predefined mapping (as Map) holding the relations between zoom limits and respective jobs.
Then, just iterate through the mapping and perform add/remove operation:

const zoomJobsMap = new Map([
  [6, job],
  [7, job2],
  [8, job3],
  ...
]);

map.on('zoomend', function() {
    let zoom = map.getZoom();   # get zoom value at once
    for (var [zoomLimit, jobObj] of zoomJobsMap) {
        (zoom < zoomLimit)? map.removeLayer(jobObj) : map.addLayer(jobObj);

    }
}
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.