简体   繁体   中英

Detecting a long press on openlayers map

I have a map that presently catches the double-click event and fires some code to set a waypoint on the map and it works great.

What I'd really like to do is detect a long press for tablet/mobile users as I think the double-click method (which is working fine on my ipad) is not as precise as it is with a mouse pointer. I assume that I'll have to somehow tie in to onmousedown/onmouseup and set a timer/threshold but I'm struggling to get something like this working.

Old question - but since I struggled with this a bit I figured i'd share the answer for people looking through google.

var multiTouchEvent = 0;
var timeoutId;
var waitFor = 1000;
$(document).delegate("#openLayersMapDiv", "pagecreate", function() {
     map.events.register('touchstart', map, function(e) {
         multiTouchEvent = e.touches.length;
         timeoutId = setTimeout(function() {
              if (multiTouchEvent > 1) {
                   clearTimeout(timeoutId);
              }
              else {
                   alert("longpress!!!");
              }
         }, waitFor);
     }, true);

     map.events.register('touchmove', map, function(e) {
         clearTimeout(timeoutId);
     });
     map.events.register('touchend', map, function(e) {
         clearTimeout(timeoutId);
     });
}

The alert above will fire after 1000 miliseconds. Change the waitFor value for how long you want the user to press the map.

Explanation: Essentially the touchstart event fires an event after waiting 1000miliseconds (through the setTimeOut function). However if the user lifts up their finger (thus firing the touchend event) the setTimeOut function is cleared. This also happens if the user moves their finger (thus firing the touchmove event) or the zoom level changes (being monitored by multiTouchEvent variable).

Hope this helps someone.

Tested on Android 4+

try this code:

$(document).ready(function () {
    var longpress = false;

    $("button").on('click', function () {
        (longpress) ? alert("Long Press") : alert("Short Press");
    });

    var startTime, endTime;
    $("button").on('mousedown', function () {
        startTime = new Date().getTime();
    });

    $("button").on('mouseup', function () {
        endTime = new Date().getTime();
        longpress = (endTime - startTime < 500) ? false : true;
    });
});

DEMO

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