aratcliffe / Leaflet.contextmenu

A context menu for Leaflet.
MIT License
368 stars 107 forks source link

Executing a callback function for a marker (not-geoJSON) / Addition of example in docs #109

Closed idenchev closed 6 years ago

idenchev commented 6 years ago

Hello,

First thank you for this nice feature :)

I am having troubles with executing a callback function on markers. The marker menu extends the map menu as shown in your example. Map callbacks work properly.

I saw some issues about this topic already included on Github, but none of them helped me to solve my problem. It would be great if you could include an example on your page.

I am defining the markers and menus as follows (map contextmenu and corresponding functions are not shown because they are the same as in example):

for(i in sites) {
var title = sites[i].ID,    
        loc = sites[i].loc,     
        object = sites[i].Type,
        marker = new L.circle(new L.latLng(loc), {radius: radsiteinit+50,color: 'gold', weight: 3, title: title, pane: "sitePane",
               contextmenu: true,contextmenuInheritItems:true,contextmenuItems: [{text: 'Show Charts',index:0}, {separator: true, index: 1}]} ).
               bindPopup(object+': '+ title ).on('click', onClick);

        layerSites.addLayer(marker);
    }

As per comments in Issues section I need to use "contextmenu.show" event, as follows:

mymap.on('contextmenu.show', function (event) {

         var latlngs = event.relatedTarget.getLatLng();

    });

This is producing an error "Uncaught TypeError: Cannot read property 'getLatLng' of undefined". Also event is fired before selecting an option from contextmenu. What I need is to do different operations based on user-selected option in contextmenu.

Another attemp was to define the marker with specified callback function named showCharts:

for(i in sites) {
var title = sites[i].ID,    
        loc = sites[i].loc,     
        object = sites[i].Type,
        marker = new L.circle(new L.latLng(loc), {radius: radsiteinit+50,color: 'gold', weight: 3, title: title, pane: "sitePane",
               contextmenu: true,contextmenuInheritItems:true,contextmenuItems: [{text: 'Show Charts',callback:showCharts,index:0}, {separator: true, index: 1}]} ).
               bindPopup(object+': '+ title ).on('click', onClick);

        layerSites.addLayer(marker);
    }

Function definition looks like following:

function showCharts(e) {

    var latlngs = e.relatedTarget.getLatLng();

    };

Again the same error message is produced: "Uncaught TypeError: Cannot read property 'getLatLng' of undefined".

Could you please help me with finding what I am doing wrong?

Thank you in advance!

idenchev commented 6 years ago

Issue was solved.

Please refer to following link for a working solution.