javascriptleaflet

How to pass an argument to a Leaflet event listener?


I'm trying to write this function so that clicking on a new item created in a Google map should run a panTo() to the specified latlng. I do not know if addListener is unable to send a parameter to the callback function.

function createLinkToMarker(title, latlng, container) {
    var a = L.DomUtil.create('a', 'link-marker', container);
        a.href='#',
        a.innerHTML = title;

    function pan() {//??? why I passing argument(latlng) for each new A element?
        console.log(arguments);
        map.panTo(latlng);
    }
    L.DomEvent
        .addListener(a, 'click', L.DomEvent.stopPropagation)
        .addListener(a, 'click', L.DomEvent.preventDefault)
        .addListener(a, 'click', pan);
    return a;
}

Solution

  • You should probably just add the latlng value to the DOM element and retrieve it in the listener. If you're using HTML5 you can store items with the prefix "data" so you could store latitude in the element as "data-lat" and longitude as "data-lon", i.e.:

    a.setAttribute( "data-lat", latlng.lat );
    a.setAttribute( "data-lon", latlng.lng );
    

    Then in your listener:

    var lat = this.getAttribute( "data-lat" );
    var lon = this.getAttribute( "data-lon" );
    map.panTo( new L.LatLng( lat, lon ) );
    

    Hope this helps!