Raruto / leaflet-kmz

A KMZ file loader for Leaflet Maps
GNU General Public License v3.0
48 stars 27 forks source link

pass options from layer instantiation to load event #21

Closed CalRobert closed 2 years ago

CalRobert commented 2 years ago

I needed to include some metadata around the layer when adding the control, but this wasn't available on the "load" event.

This lets you load the layer with

kmz.load(url, options)

and then add the control with e.g.:

kmz.on('load', function(e) {
  control.addOverlay(e.layer, `<a href="${e.props.options.url}" target="_blank">${e.props.options.name}</a>`);
  e.layer.addTo(map);
});
Raruto commented 2 years ago

Hi CalRobert, you can just use different layers:

const files = [
  {
    url: 'https://raruto.github.io/leaflet-kmz/examples/regions.kmz',
    name: 'Regions of Italy'
  },
  {
    url: 'https://raruto.github.io/leaflet-kmz/examples/capitals.kmz',
    name: 'Capitals of Europe'
  },
  {
    url: 'https://raruto.github.io/leaflet-kmz/examples/globe.kmz',
    name: 'The Equator and Prime Meridian'
  },
  {
    url: 'https://raruto.github.io/leaflet-kmz/examples/etna.kmz',
    name: 'Etna volcanic eruption'
  },
];

files.forEach(file => {
  let kmz = L.kmzLayer();
  kmz.on('load', (e) => kmz.addTo(map) && control.addOverlay(kmz, file.name)); // NB using the event is not mandatory, it is purely an aesthetic choice
  kmz.load(file.url);
});

if you wish, you can also group them into a single layer:

let kmzGroup = L.featureGroup();

kmzGroup.addLayer(kmz1);
kmzGroup.addLayer(kmz2);
kmzGroup.addLayer(kmz3);

...

Have a nice day, Raruto