antonio gabriel
antonio gabriel

Reputation: 41

Add dynamic overlays from array

I am trying to add new layers to the map using the leaflet. First I create the layers by a form then I put the elements related to their relationship. The problem is that to add a new layer to the overlayers object is using static code, and I wanted to use all the layers that I am creating and are downloaded from the database. Does anyone have an idea?

var tipo1 = L.layerGroup();
var tipo2 = L.layerGroup();

var overlayers = {
  "Tipo 1": tipo1,
  "Tipo 2": tipo2
};  

This example works. This is how it should be used. But in my case, instead of using tipo1 and tipo2 ... I would have one or more types coming from a database, and wanted to add to overlayers.

Upvotes: 2

Views: 250

Answers (2)

user7247147
user7247147

Reputation: 1107

You can create your own featureGroup class - something like:

    L.Overlayers = L.FeatureGroup.extend({
      initialize: function(options) {
        L.setOptions(this, options);
        L.FeatureGroup.prototype.initialize.call(this, options);
      },

      onAdd: function(map) {
        L.FeatureGroup.prototype.onAdd.call(this, map);

        this._map = map;

        this.on("layeradd", this._doThingsHere, this);
        this.on("layerremove", this._stopDoingThingsHere, this);
      },

      onRemove: function() {
        this.off("layeradd", this._doThingsHere, this);
        this.off("layerremove", this._stopDoingThingsHere, this);
      },
   });

If you instantiate an empty instance of it on the map:

var group = new L.Overlayers().addTo(map);

Then when your data layer loads, you can dynamically add it to the group:

group.addLayer(tipo1);

This will trigger layeradd and give you access to the layer via e.layer

From there you have full access to the layer and map.

You can do things like subgroup them into LayerGroups and organize them, etc.

Upvotes: 1

peeebeee
peeebeee

Reputation: 2618

You don't post much code, but assuming you're using a Layers control, you can add layers dynamically - eg

var myLayersControl = L.control.layers(null, null).addTo(map);
var myNewLayer = L.layerGroup();
myLayersControl.addOverlay(myNewLayer, "Description");

Upvotes: 1

Related Questions