Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using longclick/taphold with Google Maps in jQuery Mobile?

I'm using Google Maps with jQuery Mobile.

I can bind a click event to the map easily enough, but is there a way to bind a long click? I'd like to add a marker to the map following a long click.

I can use jQuery Mobile's 'taphold', designed especially for long clicks, but that doesn't give me a way to access map properties such as the latlng of the tap:

    $('#map-canvas').bind('taphold', function(e) {
      console.log('taphold');
      e.stopImmediatePropagation();
      return false;
    } );

Conversely, I can use the Google Maps click listener, but that picks up short clicks, which makes the map fiddly to use on a mobile:

google.maps.event.addListener($('#map-canvas'), 'click', function(event){  ...

I don't see a 'longclick' event listener for Google Maps API V3: http://code.google.com/apis/maps/documentation/javascript/reference.html#Map

Any ideas?

Thanks for your help.

like image 536
Richard Avatar asked Jun 07 '11 12:06

Richard


1 Answers

For anyone looking for a solution, I got this on the Google Maps forums, and it does the trick.

function LongClick(map, length) {
    this.length_ = length;
    var me = this;
    me.map_ = map;
    google.maps.event.addListener(map, 'mousedown', function(e) { me.onMouseDown_(e) });
    google.maps.event.addListener(map, 'mouseup', function(e) { me.onMouseUp_(e) });   
}   
LongClick.prototype.onMouseUp_ = function(e) {
    var now = +new Date;
    if (now - this.down_ > this.length_) {
        google.maps.event.trigger(this.map_, 'longpress', e);
    }   
}   
LongClick.prototype.onMouseDown_ = function() {
    this.down_ = +new Date;   
}
new LongClick(map, 300);
google.maps.event.addListener(map, 'longpress', function(event) {
    do stuff...
}
like image 69
Richard Avatar answered Oct 19 '22 10:10

Richard