简体   繁体   中英

adding layers to my Leaflet map using a loop

So here is one of my layers:

               TurksAndCaicosLayer = L.geoJson(TurksAndCaicos, { 
                    style: {
                        weight:         0.5,
                        color:          'white',
                        fillOpacity:    1,
                        fillColor:      'brown',
                        }})         

I have 8 of these polygon layers for my Leaflet map. I am trying to construct a loop which will go through the array of my layers and add them to the map, but it doesn't seem to be working. Can anyone spot why?

            let layers = [AnguillaLayer, BermudaLayer, BritishVirginIslandsLayer, GibraltarLayer, GuernseyLayer, IsleOfManLayer, JerseyLayer, TurksAndCaicosLayer]

                for (let layer of layers) {

                map.addLayer(layer)}

try

layers.forEach(addLayer);

function addLayer(item, index) {
   map.addLayer(item);
}

An alternative approach would be to add your layers to a layerGroup and add the layerGroup to the map - saves writing an explicit loop.

let layers = [AnguillaLayer, BermudaLayer, BritishVirginIslandsLayer, GibraltarLayer, GuernseyLayer, IsleOfManLayer, JerseyLayer, TurksAndCaicosLayer];

let myLayerGroup = L.layerGroup(layers).addTo(map);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM