Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect long press on Google maps markers?

I guess Google maps does not have a long press / taphold event handler. Is the below code a way to implement this?

like image 813
Anbarasan Thangapalam Avatar asked Nov 28 '22 07:11

Anbarasan Thangapalam


2 Answers

I have implemeted the long press feature using mouse up and mouse down event listener. Thanks!!

var longpress = false;
        
google.maps.event.addListener(marker,'click', function (event) {
    (longpress) ? console.log("Long Press") : console.log("Short Press");
});
        
google.maps.event.addListener(marker, 'mousedown', function(event){
    start = new Date().getTime();           
});
        
google.maps.event.addListener(marker, 'mouseup', function(event){
    end = new Date().getTime();
    longpress = (end - start < 500) ? false : true;         
});
like image 60
Anbarasan Thangapalam Avatar answered Nov 30 '22 20:11

Anbarasan Thangapalam


I know this is an old post, but I came across the same problem and I found what I think to be a better solution than the one that @Anbarasan Thangapalam suggested.

Solution:

var mousedUp = false;
google.maps.event.addListener(marker, 'mousedown', function(event){ 
    mousedUp = false;
    setTimeout(function(){
        if(mousedUp === false){
            //do something if the mouse was still down
            //after 500ms        
        }
    }, 500);
});
google.maps.event.addListener(marker, 'mouseup', function(event){ 
    mousedUp = true;
});

I think this approach might be better to understand, with less lines of code and less listener functions.

To avoid firing the timeout function on a drag event, just duplicate the mouseup function and change it with dragstart. Like so:

google.maps.event.addListener(marker, 'dragstart', function(event){ 
    mousedUp = true;
});
like image 24
rafaelmorais Avatar answered Nov 30 '22 21:11

rafaelmorais