I add a listener to a button

    .addListener(selectList, 'click', L.DomEvent.stopPropagation)
    .addListener(selectList, 'click', L.DomEvent.preventDefault)
    .addListener(selectList, 'click', this._onMarkerChange);

And then I want to move map by panto function.

_onMarkerChange: function (){
    this._handlingClick = true;
    for (var opt in this) {
            var lat = this[opt].getAttribute( "data-lat" );
            var lon = this[opt].getAttribute( "data-lon" );
            this.L.Map.panTo( new L.LatLng( lat, lon ) );
     this._handlingClick = false;

It has an error --Uncaught ReferenceError: map is not defined How should I do? pass map object into this event?


If you do not specify the 4th argument in L.DomEvent.addListener (the "context"), then this inside your callback will refer to the DOM element that triggered the event, i.e. what is referred by selectList in your code.

Then for (var opt in this) will loop through all selectList DOM properties, and this.L.Map.panTo will expect that L is referenced as a property of selectList. I do not think you can use it as-is either.

Now if you pass your map as 4th argument, this will refer to it. You can still access your DOM element by taking an argument event with your callback and looking for event.currentTarget.

this._onMarkerChange = function (event) {
    var dataset = event.currentTarget.dataset;
    var lat = parseFloat(dataset.lat);
    var lon = parseFloat(dataset.lon);
    this.panTo( new L.LatLng( lat, lon ) );

    .addListener(selectList, 'click', L.DomEvent.stopPropagation)
    .addListener(selectList, 'click', L.DomEvent.preventDefault)
    .addListener(selectList, 'click', this._onMarkerChange, map);
    // map as 4th argument will be the context (this) in the callback.

Demo: http://jsfiddle.net/ve2huzxw/49/

I am unsure about what object you want to refer to by using this within your callback (_onMarkerChange). As said above, this will refer to the DOM element (selectList) if you do not specify the 4th argument in L.DomEvent.addListener, or to whatever object you pass as 4th argument.

| improve this answer | |
  • 1
    Muhammed Naqi, thank you very much. It works. I am new in leaflet.js. – Hu Kenneth Nov 25 '15 at 9:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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