[GIS] Leaflet: Find the “this” in GeoJSON.pointToLayer function

javascriptleaflet

In leaflet, I have a class that extends L.GeoJSON:

L.MyLayer = L.GeoJSON.extend
({
    initialize: function ()
    {
        this.markers = [];
...

I redefined the pointToLayer method to create markers for points:

pointToLayer : function(feature, latlng)
{
   var marker = L.marker(lat...
   ...
   return marker;
},

I need to store all the markers locally, so I created the markers array.
My problem is that if I call this. inside pointToLayer function I obtain the Window object instead obtaining the current instance of MyLayer.

How can I get a reference to current MyLayer instance inside pointToLayer function?

Best Answer

You could just pass the pointToLayer function as an option on layer instantiation.

var layer = L.myLayer(geojson, {
    pointToLayer: function (ftr, latLng) {
        return L.marker([latlng.lat, latlng.lng]);
    }
});

And then get markers off the layer instance.

var markers = layer.getLayers();