how to pass data with marker in leaflet js

With the current version of leaflet (0.8-dev) you can just set your custom properties on the marker object itself, without having to create a custom marker class...

function map() {
    return L.map('leaflet-canvas',
    {
        maxZoom: 10,
        minZoom: 0,
        crs: L.CRS.Simple
    });
}

var map = map().setView([0, 0], 10).on('click', onMapClick);

function onMapClick(e) {
    var marker = L.circleMarker(e.latlng, {draggable:true});

    marker.myCustomID = Math.floor((Math.random() * 100) + 1);

    marker.on('click', onMarkerClick);

    map.addLayer(marker);

    // 'click' the new marker to show the ID when marker created
    marker.fireEvent('click');
}

function onMarkerClick(e) {
    alert(e.target.myCustomID);
}

It sounds like you would like to add new functionality (functions, properties, etc) to an existing class. It would make sense to use object-oriented principals for this. For this purpose, I'd recommend you extending the CircleMarker class to add those properties.

customCircleMarker = L.CircleMarker.extend({
   options: { 
      someCustomProperty: 'Custom data!',
      anotherCustomProperty: 'More data!'
   }
});

Now when you create your circle marker, create an instance of your extended object instead.

var myMarker = new customCircleMarker(myPoint, { 
    title: 'unselected',
    radius: 20,
    someCustomProperty: 'Adding custom data to this marker!',
    anotherCustomProperty: 'More custom data to this marker!'
});
myMarker.addTo(map);

Now you can get the properties like you would any other option from the marker. This is just a simple case of extending, and you can do more as needed, such as adding other properties or functions to the object.

JSFiddle example: JSFiddle


Here is a TypeScript friendly way:

DataMarker.ts

import * as L from 'leaflet';

export class DataMarker extends L.Marker {
  data: any;

  constructor(latLng: L.LatLngExpression, data: any, options?: L.MarkerOptions) {
    super(latLng, options);
    this.setData(data);
  }

  getData() {
    return this.data;
  }

  setData(data: any) {
    this.data = data;
  }
}

SomeOtherFile.ts

import { DataMarker } from './DataMarker';

const marker = new DataMarker([ lat, lng ], anyData, markerOptions);

--

Note 1: I decided not to merge the marker options with the data property

Note 2: Adjust the type of data if you need something more specific