5

In the leaflet.js documentation an example with layers of markers is documented. I would like to create a layer of polygons in GeoJSON format. Is this possible?

I've defined a variable for each GeoJSON polygon, called route1, route2 etc. My .js file looks like this:

var map = L.map('map', {
    center: [55.676098, 12.568337],
});

L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

//============
//Create layer
//============

var Southroutes = new L.layerGroup([route1, route2, route3, route4, route5]);

L.geoJSON(Southroutes).addTo(map);

2 Answers 2

3

If you have a look at the documentation, you will see that a GeoJSON layer in Leaflet extends FeatureGroup (which in turn extends LayerGroup). In other words, it is already a LayerGroup. In practice this works by all features in a GeoJson object being grouped and you don't need to separately bundle them in a new L.layerGroup (the L.geoJSON is sufficient if they are all in the same GeoJson dataset). See the examples here. In these examples you will see how multiple GeoJson features can be in one 'layer' (because it is a LayerGroup).

You could also use your attribute to render the routes differently as per the emaples linked earlier.

3

This is the solution I came up with:

var route1Layer = L.geoJSON(route1);
var route2Layer = L.geoJSON(route2);
var route3Layer = L.geoJSON(route3);
var route4Layer = L.geoJSON(route4);
var route5Layer = L.geoJSON(route5);

group = new L.FeatureGroup();
group.addLayer(route1Layer);
group.addLayer(route2Layer);
group.addLayer(route3Layer);
group.addLayer(route4Layer);
group.addLayer(route5Layer);
map.addLayer(group);

What I ultimately wanted was to assign features to the group. For example color all the routes red:

group.setStyle(
    function(feature){
        return {color: 'red'};
    }
);

And it did the job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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