简体   繁体   中英

Click event fires twice for item inside a loop

So the thing is that I have leafletjs map, using some data that I get from fetch I add new markers to the map. There is a loop going through the data and it creates and puts a new marker for both "destination from" and "destination to".

The problem is that after the click on one of the markers the event fires twice. I have tried for example using a variable holding last click time and comparing it with a new one, but it does not fix the problem. When I change the loop so it adds only 1 marker the event still fires twice. Can you see what might be the cause?

The other additional problem (if someone can see why is that happening) is that after clicking one of the markers (from/to) (event fires twice) and click any other one (that doesn't belong to the previously clicked pair) I get undefined error on package.addressFrom

function prepare(data)
{
    for(var i=0; i < data.length; ++i)
    {
        var markeFrom = L.marker([data[i].latFrom, data[i].lngFrom], {myCustomClass: data[i].id}).addTo(myMapAll).on('click', markerClicked);
        var markerTo = L.marker([data[i].latTo, data[i].lngTo], {myCustomClass: data[i].id}).addTo(myMapAll).on('click', markerClicked);
        
        packageInfo["id"] = data[i].id;
        packageInfo["addressFrom"] = data[i].destinationFrom;
        packageInfo["addressTo"] = data[i].destinationTo;
        packageInfo["recipient"] = data[i].recipient;
        packageMapInfoArr.push(packageInfo);
    }
}

function markerClicked() 
{
    var clickedMarkerId = this.options.myCustomClass;
    var package = packageMapInfoArr.find(x => x.id === clickedMarkerId);
    
    alert('From:' + package.addressFrom + '\n' +
            'To:' + package.addressTo + '\n' +
            'Recipient:' + package.recipient);
}

在此处输入图像描述

Those screenshots seem to be from the Safari web browser, so chances are that you're hitting known Leaflet issue #7255 . Using any other web browser should clarify if this is the case.

There is no clean solution to this bug at the time of this writing, but the current workaround is to disable the tap handler (by means of the tap option when initializing the L.Map instance)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM