Wednesday, November 5, 2008

Bouncy Map Markers

I like the bouncy icons that gmaps has on the google maps site. If you want this in your own application though, it isn't the easiest thing to accomplish. I first tried the obvious loop, then the loop with a delay built in but that's just not going to work and the Gmaps API has some unnatural ability to filter out a series of small moves meant to animate the bounce of the marker if they are very close to each other.

What I finally tried and seems to have worked, was to use a call to move the marker wrapped in closure called by a setTimeout(). The following code is a template that you can use to implemented bouncy markers in your application.


var bounceInProgress = false;
var myMap; // this has been set prior to call

function bounceMarker(marker)
{
if (! bounceInProgress)
{
var point =
myMap.fromLatLngToContainerPixel(marker.getLatLng());

bounceInProgress = true;
myMap.disableDoubleClickZoom();
myMap.disableDragging();
bounceMarkerMove(marker, point, -10, -1);
}
}

function bounceMarkerMove(marker, point, i, direction)
{
if (i <= 10)
{
direction = (i == 0) ? 0 : direction = i/Math.abs(i);
point.y += direction;

marker.setLatLng(myMap.fromContainerPixelToLatLng(point));
markerNextMove = function () { bounceMarkerMove(marker,
point,
i + 1,
direction); };
setTimeout("markerNextMove()", 15);
}
else
{
myMap.enableDoubleClickZoom();
myMap.enableDragging();
bounceInProgress = false;
}
}

To see this template in action, check out this page, http://www.abaq.us/geo/pub/glog/john there you will see bouncy icons on the map. Select another map from the list that has a marker if the default map doesn't have one, and click it to see the marker bounce. Check out the code of the page to see it implemented in situ. I've also implemented it in the GWT as well.