leaflet: don't fire click event function on doubleclick

后端 未结 3 1735
庸人自扰
庸人自扰 2021-01-03 08:51

I have a question concerning clicks on a map in leaflet. If I click on the map I want to set a marker there, but if doubleclick on the map I just want to zoom in without set

相关标签:
3条回答
  • 2021-01-03 09:16

    This is still an issue on recent (leaflet 1.4) versions.

    Alternative approach I used that:

    • legit usage of setTimeout and clearTimeout
    • without adding random props to the map object
    • no jQuery:
    map.on('click', function(event) {
      if (_dblClickTimer !== null) {
        return;
      }
      _dblClickTimer = setTimeout(() => {
    
        // real 'click' event handler here
    
        _dblClickTimer = null;
      }, 200);
    })
    .on("dblclick", function() {
      clearTimeout(_dblClickTimer);
      _dblClickTimer = null;
    
      // real 'dblclick' handler here (if any). Do not add anything to just have the default zoom behavior
    });
    

    Note that the 200 ms delay must be tested. On my environment using a value like 100 was not enough as the doubleclick event is triggered with a delay.

    0 讨论(0)
  • 2021-01-03 09:18

    Had the same problem of 2 x unwanted click events firing when listening for dblclick.

    Note: I wanted single and double clicks on the same element to perform different actions.

    I adapted this approach to my leaflet map, which is not bullet proof but eliminates 99% of the conflicts:

    var timer = 0;
    var delay = 200;
    var prevent = false;
    
    $("#target")
      .on("click", function() {
        timer = setTimeout(function() {
          if (!prevent) {
            doClickAction();
          }
          prevent = false;
        }, delay);
      })
      .on("dblclick", function() {
        clearTimeout(timer);
        prevent = true;
        doDoubleClickAction();
      });
    

    Credit: CSS-Tricks

    Code Pen Example

    0 讨论(0)
  • 2021-01-03 09:33

    So, I found a way to do that, I am still not sure, if there is a better way to do it.

    var map = L.map(attrs.id, {
            center: [scope.lat, scope.lng],
            zoom: 14
        });
    map.clicked = 0;                                                                      
    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 18
        }).addTo(map);
    var marker = L.marker([scope.lat, scope.lng],{draggable: true});
    map.on('click', function(event){
        map.clicked = map.clicked + 1;
        setTimeout(function(){
            if(map.clicked == 1){
                marker.setLatLng(event.latlng);
                marker.addTo(map);                
                map.clicked = 0;
            }
         }, 300);
    });
    map.on('dblclick', function(event){
        map.clicked = 0;
        map.zoomIn();
    });
    
    0 讨论(0)
提交回复
热议问题