Maps API Engineer Bo Majewski brings us a fun example of an animated clock using both GPolyline
and the new setImage
method of GMarker
that was just introduced in v2.75.
Why is this clock centered on Australia? That's where the engineer's from! We leave it up to adventurous developers to combine this with a service like EarthTools to let users move the map and see the clock time reflect the timezone of the new map center.
Update: Maps developer Esa created a similar clock example that changes the clock location and time for various locations using the EarthTools service. Great work, Esa!
If you want to know how it's done, check out the how-to below the map, and ping us if you come up with any fun variations.
Setting up the clock:
- We declare a global variable to keep track of the last hour/minute/second shown, as well as the polylines used for the hour/minute hands and the markers used for the clock ticks. We also declare global constants for our image strings, clock radius, and slice angle (the angle we need to move each minute, 2*Math.PI/60).
-
After loading the map in
setupMap
, we plot the markers for the ticks insetupTicks
. We first declare aGIcon
for each tick type (marker/second). Then we create 60 markers around the circumfrence of the clock, using the minute icon every 5 ticks and the seconds icon for the rest.
-
After setting up the initial markers, we call
setInterval
on theclockTick
function with 1000 milliseconds so that it's called once every second, and then we callsetTimeout
onclockTick
with 0 milliseconds to call it immediately. -
In
clockTick
, we extract the current time from the javascriptDate
function into hours, minutes, and seconds variables. If the hour is not the same as the previously displayed hour, we remove the hour hand'sGPolyline
from the map, re-create it pointing to the new hour, and add the newGPolyline
to the map. We do the same for the minutes hand. If the second is not the same as the previously displayed second, we callsetImage
on the previous marker with the appropriate image (MINUTE_OFF or SECOND_OFF) so that it's no longer highlighted, and we callsetImage
on the current marker with the appropriate image (MINUTE_ON or SECOND_ON) so that it is highlighted.
-
The
minToLatLng
function is used frequently throughout the code to figure out the point at which to place or marker or end a polyline. This function takes in two parameters. The first indicates the minute (0-59), and the second indicates an inner offset from the radius (used for creating hour/minute hands of different lengths). It then calculates the point using basic trig on the known center of the map and the slice angle.
Here's a direct link to the clock, if you want to check out the source code yourself.
API v2 Latest: 2.75
API v2 Default: 2.74