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\$
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\$

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.