When we released the setImage method for GMarker a few weeks ago, we showed you how it could be used to overlay an animated clock on top of a map. Well, honestly, I've never been that good at reading the time from an analog clock, so I decided to take advantage of the new GMarker show/hide methods to create this digital clock:
Just to remind you that it's easy to mash up the Google Maps API with Google Gadgets, I made a smaller gadget version that you can add to your personalized homepage or website, and then customize the map's latitude/longitude and zoom. I chose to position my clock over Victoria Falls, Africa (in the hope it'll increase my chances of visiting there one day!), but you may have your own background preference.
How does the clock work? Each clock digit is made up of the seven segments typical of LED clocks, and each of these segments is actually a marker that I toggle with show/hide. If you really want to dive into the code (and perhaps customize it to display messages or countdowns), view source on the clock and read the code breakdown below.Storing the clock data:
markersassociative array is used to keep track of the markers. For example, "hour_10" refers to the array for all the markers representing the tens place of the hour. The arrays begin empty and are populated later.
numberLayoutsassociative array is used to indicate which segments should be on/off in order to represent a particular digit. In the array, true indicates a segment should be on and false indicates the opposite, and the array index for each segment is dictated by the diagram shown here. Because of the way it's setup, it'd be simple to extend this alarm clock to non-number output as well.
colonWidthvariables are used in positioning the marker segments with the correct spacing.
- First the map is initialized and 3 custom icons are declared (for the colon, horizontal segment, and vertical segment). Then
addSegmentMarkersis called 6 times (hours*2,minutes*2,seconds*2) and
addColonMarkeris called twice, each time with an appropriate offset so that digits aren't overlapping.
- In the
addSegmentMarkersfunction, a pixel location is calculated for each 7 segments based on a startPixel, and the global sizing variables. The API-provided
fromPixelToLatLngis used to calculate a
GLatLngbased on the resultant pixel location, and a marker is created at that point and added to the relevant array in markers. The segments are added so that their array indices correspond with the
addColonMarkerfunction is similar to
addSegmentMarkers, but only calculates one marker position.
toggleSegmentsfor each of the digits.
toggleSegmentsfunction iterates through the markers in the array for that digit place, and compares the return value of
isHidden()to the boolean in the
numberLayoutsarray. If it's hidden and needs to be shown, it calls
show()on the marker. If it's shown and needs to be hidden, it calls
hide()on the marker.