1

It's something that I have very rarely done - adding properties to a Leaflet marker.

I was reading this page which says that we should

customMarker = L.Marker.extend({
   options: {
      name: '',
      type: ''
   }
});

var marker = new customMarker([28.63278, 77.21972],{
   clickable: true,
   name: 'Connaught Place',
   type: 'Neighbourhood'
}).addTo(map);

I see from some old code that I have simply

let marker = L.marker(markerLatLng, {
       name: 'Connaught Place',
       type: 'Neighbourhood'  

Since this works, it seems like Leaflet is intelligent enough to treat any non-Leaflet properties as extending the L.Marker class.

Is there a "correct" way (with a technical reason for it being correct)?

1 Answer 1

1

No, you really do not need to extend the Leaflet Layer just for the sake of being able to add your own data.

The blog post you link to dates from 2013, so it may have been a different story at that time.

With today's Leaflet version (1.7.1 at time of writing), if you do:

const myMarker = L.marker(latLng, {
  myData: someData
});

...then you can retrieve someData with:

myMarker.options.myData; // someData

That being said, there may be some use case when you would like to extend such options as shown in the blog post: in case you want some default value, as described in https://leafletjs.com/reference-1.7.1.html#class-options

[...] makes managing configuration of objects and default values convenient

Otherwise, you also have other ways to attach your data to Leaflet layers, see Leaflet: Including metadata with CircleMarkers

1
  • "The blog post you link to dates from 2013, so it may have been a different story at that time" - that's what I suspected, but thanks for clarifying.
    – Mawg
    Commented Feb 16, 2021 at 21:01

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