Tuesday, April 17, 2012

How to create a hover intent function with Google Maps

Last week I wanted to fire a piece of code (div scrolling) when the user's mouse was hovering over a Google maps polygon. I got that working pretty easily with a simple Google Maps listener with the 'mouseover' event. Unfortunately, that created a different problem - if the user moved the mouse quickly over the map and crossed over many polygons, the div scrolling code I had within the listener was fired too much.

I ended up finding a jQuery plugin, hoverintent,  that only makes the call when the user's mouse is hovering over the element for a specific amount of time. This would have certainly done the trick on a DOM element but it wasn't going to work on my map when the polygon wasn't a DOM element, it was an overlay on the Google maps object. An even easier solution (no plugin required) emerged.

Javascript has a setTimeout() method that you can use to execute code in the future. So, in  my case, I set a variable, timer, to the setTimeout() method and the code I wanted called; I checked for timer when the user had the mouse over an element, if the timer existed, I set it to null and used the clearTimeout method and then reset timer to the a new SetTimeout. I added another Google Maps listener for the event 'mouseout' of the polygon and set timer to null while using the clearTimeout(). In this way, the div scrolling only happened when the timer reached a certain time, in other words, when the user's mouse was hovering over a polygon for  a certain amount of time.

google.maps.event.addListener(polygon, 'mouseover', function(event) {

            if (timer) {
              clearTimeout(timer);
              timer = null;
            }
//set timer so animation of scrollbar only happens when mouse is within polygon for longer than 500 milliseconds
        timer = setTimeout(function() {
            $('#side_content').animate({ top: -$('#div').top }, 300);
        }, 500);
});

google.maps.event.addListener(polygon, 'mouseout', function(event) {
          if (timer) {
            clearTimeout(timer);
            timer = null;
          }
});

3 comments:

  1. No, this is very incorrect. You should be doing this with PHP and not javascript as javascript is the same thing as java and but made by only fools. For assistance, use the following PHP function:

    $trapper_keeper = '';

    function() {
    $trapper_keeper = 'not_hover';
    if($trapper_keeper == "dawson's creek good tv show") {
    DO NOT HOVER;
    }
    }

    ReplyDelete
  2. GEvent.addListener(marker, "mouseover", function() {
    if (this.timer) {
    clearTimeout(this.timer);
    this.timer = null;
    }
    this.timer = setTimeout(function() {
    myover(pointid);
    }, 100);
    });
    GEvent.addListener(marker, "mouseout", function() {
    if (this.timer) {
    clearTimeout(this.timer);
    this.timer = null;
    }
    myout(pointid);
    });

    ReplyDelete