46

With the Google Maps JS API v3, I want to drop a marker where the user clicks on the map, while keeping the default behavior when the user double clicks (and not adding any marker on the map).

I thought about defining a timeout on click event. If a double click event is triggered within the next few milliseconds, the timeout is cancelled. If not, the marker is placed on the map when the timeout expires. But it doesn't really look like the best solution ever.

Is there a more elegant way to handle this?

Thanks.

6 Answers 6

63

I just found an hackish solution which works but introduce a small waiting time (200ms, this is the minimum to make it work, but I don't know if it is client dependent)

var update_timeout = null;

google.maps.event.addListener(map, 'click', function(event){
    update_timeout = setTimeout(function(){
        do_something_here();
    }, 200);        
});

google.maps.event.addListener(map, 'dblclick', function(event) {       
    clearTimeout(update_timeout);
});

Hope this helps!

2
  • I tried this, but does not work for me. the first click in the doubleclick clears the timeout, but the second click still acts as a click, and do_something_here() is executed. Oct 29, 2015 at 0:02
  • Yet, setting a global variable doubleClicked = true in dblclick function and checking for it inside update_timeout solved the issue. ;) Oct 29, 2015 at 0:12
28

The easiest way to solve it.

var location;
var map = ...

google.maps.event.addListener(map, 'click', function(event) {
    mapZoom = map.getZoom();
    startLocation = event.latLng;
    setTimeout(placeMarker, 600);
});

function placeMarker() {
    if(mapZoom == map.getZoom()){
        new google.maps.Marker({position: location, map: map});
    }
}

shogunpanda's solution is better (see below)

1
  • This solution doesn't work if your placeMarker() function may be called sometimes besides on click events (unless you always call mapZoom = map.getZoom() before you call placeMarker()); I found @ShogunPanda's solution more flexible in this circumstance. Jun 17, 2015 at 0:13
7

You can take advantage of, dblclick fires if it is a double click, and single click fires in such occations only once.

runIfNotDblClick = function(fun){
    if(singleClick){
        whateverurfunctionis();
    }
};

clearSingleClick = function(fun){
    singleClick = false;
};

singleClick = false;

google.maps.event.addListener(map, 'click', function(event) {// duh! :-( google map zoom on double click!
    singleClick = true;
    setTimeout("runIfNotDblClick()", 500);
});

google.maps.event.addListener(map, 'dblclick', function(event) {// duh! :-( google map zoom on double click!
     clearSingleClick();
});

See http://www.ilikeplaces.com

1
  • Works great! If you like me had to send the event to runIfNotDblClick function you can do: setTimeout(runIfNotDblClick.bind(null, event), 500) and for example read latLng in event using Array.prototype.slice.call(arguments)[0].latLng
    – riper
    Jan 7, 2018 at 22:41
4

If you're using underscore.js or* lodash here's a quick and elegant way to solve this problem

// callback is wrapped into a debounce function that is called after
// 400 ms are passed, it provides a cancel function that can be used
// to stop it before it's actually executed
var clickHandler = _.debounce(function(evt) {
  // code called on single click only, delayed by 400ms
  // adjust delay as needed.
  console.debug('Map clicked with', evt);
}, 400);
// configure event listeners for map
google.maps.event.addListener(map, 'click', clickHandler);
google.maps.event.addListener(map, 'dblclick', clickHandler.cancel);

* Debounce.cancel is implemented only in lodash (with this commit), underscore.js does not implement it

0
0

A cleaner way to implement the setTimeout() approach is to trigger custom events for single clicks.

The following function takes any Google Maps interface object (e.g. map, marker, polygon etc.) and sets up two custom events:

singleclick: called 400ms after a click if no other clicks have occured

firstclick: called whenever a click event occurs, unless a click has already occured in the last 400ms (this is handy for showing some kind of immediate click feedback to the user)

function addSingleClickEvents(target) {
  var delay = 400;
  var clickTimer;
  var lastClickTime = 0;

  google.maps.event.addListener(target, 'click', handleClick);
  google.maps.event.addListener(target, 'dblclick', handleDoubleClick);

  function handleClick(e) {
    var clickTime = +new Date();

    var timeSinceLastClick = clickTime - lastClickTime;

    if(timeSinceLastClick > delay) {
      google.maps.event.trigger(target, 'firstclick', e);

      clickTimer = setTimeout(function() {
        google.maps.event.trigger(target, 'singleclick', e);
      }, delay);
    } else {
      clearTimeout(clickTimer);
    }

    lastClickTime = clickTime;
  }

  function handleDoubleClick(e) {
    clearTimeout(clickTimer);
    lastClickTime = +new Date();
  }
}

You can use it like so:

var map = ....
addSingleClickEvents(map);
google.maps.event.addListener(map, 'singleclick', function(event) {
    console.log("Single click detected at: " + event.latLng);
}
-4

I'm not sure, but if you add event handlers to both 'click' & 'dblclick' events, where you say to put marker on a click, and don't take any action on double click, then you can skip the adding of timeouts (the maps API can differ what is click and what is double click)

google.maps.event.addListener(map, 'click', function (event) {
        placeMarker(event.latLng);
    });
google.maps.event.addListener(map, 'dblclick', function(event) { 
//DO NOTHING, BECAUSE IT IS DOUBLE CLICK
});

The placeMarker(latLng) is custom added function which adds marker on the given location:

var marker = new google.maps.Marker({
        position: location,
        draggable: true,
        map: map
    });
map.setCenter(location);
1
  • 3
    Thanks for your answer. But the API triggers both a click and a dblclick event when the user double clicks :/
    – Pierre
    Mar 17, 2011 at 10:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.