only put points into the track if they're accurate enough, but always paint the curre...
[lantea.git] / js / map.js
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3  * You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 var gCanvas, gContext, gGeolocation;
6 var gDebug = false;
7
8 var gTileSize = 256;
9 var gMaxZoom = 18; // The minimum is 0.
10
11 var gMinTrackAccuracy = 1000; // meters
12 var gTrackWidth = 2; // pixels
13 var gTrackColor = "#FF0000";
14 var gCurLocSize = 5; // pixels
15 var gCurLocColor = "#800000";
16
17 var gMapStyles = {
18   // OSM tile usage policy: http://wiki.openstreetmap.org/wiki/Tile_usage_policy
19   // Find some more OSM ones at http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers
20   osm_mapnik:
21     {name: "OpenStreetMap (Mapnik)",
22      url: "http://tile.openstreetmap.org/{z}/{x}/{y}.png",
23      copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
24   osm_cyclemap:
25     {name: "Cycle Map (OSM)",
26      url: "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
27      copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
28   osm_transmap:
29     {name: "Transport Map (OSM)",
30      url: "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png",
31      copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
32   mapquest_open:
33     {name: "MapQuest OSM",
34      url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png",
35      copyright: 'Map data &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> and contributors (<a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>), tiles Courtesy of <a href="http://www.mapquest.com/">MapQuest</a>.'},
36   mapquest_aerial:
37     {name: "MapQuest Open Aerial",
38      url: "http://oatile[1-4].mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg",
39      copyright: 'Tiles Courtesy of <a href="http://www.mapquest.com/">MapQuest</a>, portions Courtesy NASA/JPL-Caltech and U.S. Depart. of Agriculture, Farm Service Agency.'},
40   opengeoserver_arial:
41     {name: "OpenGeoServer Aerial",
42      url: "http://services.opengeoserver.org/tiles/1.0.0/globe.aerial_EPSG3857/{z}/{x}/{y}.png?origin=nw",
43      copyright: 'Tiles by <a href="http://www.opengeoserver.org/">OpenGeoServer.org</a>, <a href="https://creativecommons.org/licenses/by/3.0/at/">CC-BY 3.0 AT</a>.'},
44   google_map:
45     {name: "Google Maps",
46      url: " http://mt1.google.com/vt/x={x}&y={y}&z={z}",
47      copyright: 'Map data and imagery &copy; <a href="http://maps.google.com/">Google</a>'},
48 };
49 var gActiveMap = "osm_mapnik";
50
51 var gPos = {x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
52             y: 23670000.0, // The range is 0-67108864 (2^gMaxZoom * gTileSize)
53             z: 5}; // This could be fractional if supported being between zoom levels.
54
55 var gLastMouseX = 0;
56 var gLastMouseY = 0;
57 var gZoomFactor;
58
59 // Used as an associative array.
60 // The keys have to be strings, ours will be "xindex,yindex,zindex" e.g. "13,245,12".
61 var gTiles = {};
62 var gLoadingTile;
63
64 var gMapPrefsLoaded = false;
65
66 var gDragging = false;
67 var gDragTouchID;
68
69 var gGeoWatchID;
70 var gTrack = [];
71 var gLastTrackPoint, gLastDrawnPoint;
72 var gCenterPosition = true;
73
74 var gCurPosMapCache;
75
76 function initMap() {
77   gGeolocation = navigator.geolocation;
78   gCanvas = document.getElementById("map");
79   gContext = gCanvas.getContext("2d");
80   if (!gActiveMap)
81     gActiveMap = "osm_mapnik";
82
83   //gDebug = true;
84   if (gDebug) {
85     gGeolocation = geofake;
86     var hiddenList = document.getElementsByClassName("debugHide");
87     // last to first - list of elements with that class is changing!
88     for (var i = hiddenList.length - 1; i >= 0; i--) {
89       hiddenList[i].classList.remove("debugHide");
90     }
91   }
92
93   var loopCnt = 0;
94   var getPersistentPrefs = function() {
95     if (mainDB) {
96       gPrefs.get("position", function(aValue) {
97         if (aValue) {
98           gPos = aValue;
99           drawMap();
100         }
101       });
102       gPrefs.get("center_map", function(aValue) {
103         if (aValue === undefined)
104           document.getElementById("centerCheckbox").checked = true;
105         else
106           document.getElementById("centerCheckbox").checked = aValue;
107         setCentering(document.getElementById("centerCheckbox"));
108       });
109       gPrefs.get("tracking_enabled", function(aValue) {
110         if (aValue === undefined)
111           document.getElementById("trackCheckbox").checked = true;
112         else
113           document.getElementById("trackCheckbox").checked = aValue;
114         setTracking(document.getElementById("trackCheckbox"));
115       });
116       gMapPrefsLoaded = true;
117     }
118     else
119       setTimeout(getPersistentPrefs, 100);
120     loopCnt++;
121     if (loopCnt > 20) {
122       gMapPrefsLoaded = true;
123       return;
124     }
125   };
126   getPersistentPrefs();
127
128   gCanvas.addEventListener("mouseup", mapEvHandler, false);
129   gCanvas.addEventListener("mousemove", mapEvHandler, false);
130   gCanvas.addEventListener("mousedown", mapEvHandler, false);
131   gCanvas.addEventListener("mouseout", mapEvHandler, false);
132
133   gCanvas.addEventListener("touchstart", mapEvHandler, false);
134   gCanvas.addEventListener("touchmove", mapEvHandler, false);
135   gCanvas.addEventListener("touchend", mapEvHandler, false);
136   gCanvas.addEventListener("touchcancel", mapEvHandler, false);
137   gCanvas.addEventListener("touchleave", mapEvHandler, false);
138
139   // XXX deprecated? see https://groups.google.com/forum/?fromgroups#!topic/mozilla.dev.planning/kuhrORubaRY[1-25]
140   gCanvas.addEventListener("DOMMouseScroll", mapEvHandler, false);
141   gCanvas.addEventListener("mousewheel", mapEvHandler, false);
142
143   document.getElementById("copyright").innerHTML =
144       gMapStyles[gActiveMap].copyright;
145
146   gLoadingTile = new Image();
147   gLoadingTile.src = "style/loading.png";
148 }
149
150 function resizeAndDraw() {
151   var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
152   var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
153
154   var canvasWidth = viewportWidth - 2;
155   var canvasHeight = viewportHeight - 2;
156   gCanvas.style.position = "fixed";
157   gCanvas.width = canvasWidth;
158   gCanvas.height = canvasHeight;
159   drawMap();
160   showUI();
161 }
162
163 function zoomIn() {
164   if (gPos.z < gMaxZoom) {
165     gPos.z++;
166     drawMap();
167   }
168 }
169
170 function zoomOut() {
171   if (gPos.z > 0) {
172     gPos.z--;
173     drawMap();
174   }
175 }
176
177 function gps2xy(aLatitude, aLongitude) {
178   var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
179   var convLat = aLatitude * Math.PI / 180;
180   var rawY = (1 - Math.log(Math.tan(convLat) +
181                            1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
182   var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
183   return {x: Math.round(rawX),
184           y: Math.round(rawY)};
185 }
186
187 function xy2gps(aX, aY) {
188   var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
189   var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
190   return {latitude: 180 / Math.PI *
191                     Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
192           longitude: aX / maxZoomFactor * 360 - 180};
193 }
194
195 function setMapStyle() {
196   var mapSel = document.getElementById("mapSelector");
197   if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
198     gActiveMap = mapSel.value;
199     gTiles = {};
200     document.getElementById("copyright").innerHTML =
201         gMapStyles[gActiveMap].copyright;
202     showUI();
203     drawMap();
204   }
205 }
206
207 // A sane mod function that works for negative numbers.
208 // Returns a % b.
209 function mod(a, b) {
210   return ((a % b) + b) % b;
211 }
212
213 function normaliseIndices(x, y, z) {
214   var zoomFactor = Math.pow(2, z);
215   return {x: mod(x, zoomFactor),
216           y: mod(y, zoomFactor),
217           z: z};
218 }
219
220 function tileURL(x, y, z) {
221   var norm = normaliseIndices(x, y, z);
222   return gMapStyles[gActiveMap].url
223          .replace("{x}", norm.x)
224          .replace("{y}", norm.y)
225          .replace("{z}", norm.z)
226          .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
227          .replace("[1-4]", 1 + Math.floor(Math.random() * 3));
228 }
229
230 // Returns true if the tile is outside the current view.
231 function isOutsideWindow(t) {
232   var pos = decodeIndex(t);
233   var x = pos[0];
234   var y = pos[1];
235   var z = pos[2];
236
237   var zoomFactor = Math.pow(2, gMaxZoom - z);
238   var wid = gCanvas.width * zoomFactor;
239   var ht = gCanvas.height * zoomFactor;
240
241   x *= zoomFactor;
242   y *= zoomFactor;
243
244   var sz = gTileSize * zoomFactor;
245   if (x > gPos.x + wid / 2 || y > gPos.y + ht / 2 ||
246       x + sz < gPos.x - wid / 2 || y - sz < gPos.y - ht / 2)
247     return true;
248   return false;
249 }
250
251 function encodeIndex(x, y, z) {
252   var norm = normaliseIndices(x, y, z);
253   return norm.x + "," + norm.y + "," + norm.z;
254 }
255
256 function decodeIndex(encodedIdx) {
257   return encodedIdx.split(",", 3);
258 }
259
260 function drawMap() {
261   // Go through all the currently loaded tiles. If we don't want any of them remove them.
262   // for (t in gTiles) {
263   //   if (isOutsideWindow(t))
264   //     delete gTiles[t];
265   // }
266   document.getElementById("zoomLevel").textContent = gPos.z;
267   gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
268   var wid = gCanvas.width * gZoomFactor; // Width in level 18 pixels.
269   var ht = gCanvas.height * gZoomFactor; // Height in level 18 pixels.
270   var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
271
272   var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
273   var yMin = gPos.y - ht / 2;
274   var xMax = gPos.x + wid / 2;
275   var yMax = gPos.y + ht / 2;
276
277   if (gMapPrefsLoaded && mainDB)
278     gPrefs.set("position", gPos);
279
280   // Go through all the tiles we want.
281   // If any of them aren't loaded or being loaded, do so.
282   for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
283     for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
284       var xoff = (x * size - xMin) / gZoomFactor;
285       var yoff = (y * size - yMin) / gZoomFactor;
286       var tileKey = encodeIndex(x, y, gPos.z);
287       if (gTiles[tileKey] && gTiles[tileKey].complete) {
288         // Round here is **CRUCIAL** otherwise the images are filtered
289         // and the performance sucks (more than expected).
290         gContext.drawImage(gTiles[tileKey], Math.round(xoff), Math.round(yoff));
291       }
292       else {
293         if (!gTiles[tileKey]) {
294           gTiles[tileKey] = new Image();
295           gTiles[tileKey].src = tileURL(x, y, gPos.z);
296           gTiles[tileKey].onload = function() {
297             // TODO: Just render this tile where it should be.
298             // context.drawImage(gTiles[tileKey], Math.round(xoff), Math.round(yoff)); // Doesn't work for some reason.
299             drawMap();
300           }
301         }
302         gContext.drawImage(gLoadingTile, Math.round(xoff), Math.round(yoff));
303       }
304     }
305   }
306   if (gTrack.length) {
307     gLastDrawnPoint = null;
308     for (var i = 0; i < gTrack.length; i++) {
309       drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
310                      (i + 1 >= gTrack.length));
311     }
312   }
313 }
314
315 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
316   var trackpoint = gps2xy(aLatitude, aLongitude);
317   // lastPoint is for optimizing (not actually executing the draw until the last)
318   trackpoint.optimized = (lastPoint === false);
319   var mappos = {x: Math.round((trackpoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
320                 y: Math.round((trackpoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2)};
321
322   if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
323     gContext.strokeStyle = gTrackColor;
324     gContext.fillStyle = gContext.strokeStyle;
325     gContext.lineWidth = gTrackWidth;
326     gContext.lineCap = "round";
327     gContext.lineJoin = "round";
328   }
329   if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
330     // This breaks optimiziation, so make sure to close path and reset optimization.
331     if (gLastDrawnPoint && gLastDrawnPoint.optimized)
332       gContext.stroke();
333     gContext.beginPath();
334     trackpoint.optimized = false;
335     gContext.arc(mappos.x, mappos.y,
336                  gContext.lineWidth, 0, Math.PI * 2, false);
337     gContext.fill();
338   }
339   else {
340     if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
341       gContext.beginPath();
342       gContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
343                       Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2));
344     }
345     gContext.lineTo(mappos.x, mappos.y);
346     if (!trackpoint.optimized)
347       gContext.stroke();
348   }
349   gLastDrawnPoint = trackpoint;
350 }
351
352 function drawCurrentLocation(trackPoint) {
353   var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.ccords.longitude);
354   var circleSize = gCurLocSize;
355   var mappos = {x: Math.round((locpoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
356                 y: Math.round((locpoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2)};
357
358   // Initialize or draw cache.
359   if (!gCurPosMapCache) 
360     gCurPosMapCache = {point: locpoint,
361                        data: context.createImageData(circleSize, circleSize)};
362   else
363     gContext.putImageData(gCurPosMapCache, mappos.x - circleSize / 2,
364                                            mappos.y - circleSize / 2);
365
366   // Cache overdrawn area.
367   gCurPosMapCache = gContext.getImageData(mappos.x - circleSize / 2,
368                                           mappos.y - circleSize / 2,
369                                           circleSize, circleSize);
370
371   gContext.strokeStyle = gCurLocColor;
372   gContext.fillStyle = gContext.strokeStyle;
373   gContext.beginPath();
374   gContext.arc(mappos.x, mappos.y,
375                circleSize, 0, Math.PI * 2, false);
376   gContext.fill();
377 }
378
379 var mapEvHandler = {
380   handleEvent: function(aEvent) {
381     var touchEvent = aEvent.type.indexOf('touch') != -1;
382
383     // Bail out on unwanted map moves, but not zoom-changing events.
384     if (aEvent.type != "DOMMouseScroll" && aEvent.type != "mousewheel") {
385       // Bail out if this is neither a touch nor left-click.
386       if (!touchEvent && aEvent.button != 0)
387         return;
388
389       // Bail out if the started touch can't be found.
390       if (touchEvent && gDragging &&
391           !aEvent.changedTouches.identifiedTouch(gDragTouchID))
392         return;
393     }
394
395     var coordObj = touchEvent ?
396                    aEvent.changedTouches.identifiedTouch(gDragTouchID) :
397                    aEvent;
398
399     switch (aEvent.type) {
400       case "mousedown":
401       case "touchstart":
402         if (touchEvent) {
403           gDragTouchID = aEvent.changedTouches.item(0).identifier;
404           coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
405         }
406         var x = coordObj.clientX - gCanvas.offsetLeft;
407         var y = coordObj.clientY - gCanvas.offsetTop;
408
409         if (touchEvent || aEvent.button === 0) {
410           gDragging = true;
411         }
412         gLastMouseX = x;
413         gLastMouseY = y;
414         showUI();
415         break;
416       case "mousemove":
417       case "touchmove":
418         var x = coordObj.clientX - gCanvas.offsetLeft;
419         var y = coordObj.clientY - gCanvas.offsetTop;
420         if (gDragging === true) {
421           var dX = x - gLastMouseX;
422           var dY = y - gLastMouseY;
423           gPos.x -= dX * gZoomFactor;
424           gPos.y -= dY * gZoomFactor;
425           drawMap();
426           showUI();
427         }
428         gLastMouseX = x;
429         gLastMouseY = y;
430         break;
431       case "mouseup":
432       case "touchend":
433         gDragging = false;
434         showUI();
435         break;
436       case "mouseout":
437       case "touchcancel":
438       case "touchleave":
439         //gDragging = false;
440         break;
441       case "DOMMouseScroll":
442       case "mousewheel":
443         var delta = 0;
444         if (aEvent.wheelDelta) {
445           delta = aEvent.wheelDelta / 120;
446           if (window.opera)
447             delta = -delta;
448         }
449         else if (aEvent.detail) {
450           delta = -aEvent.detail / 3;
451         }
452
453         // Calculate new center of the map - same point stays under the mouse.
454         // This means that the pixel distance between the old center and point
455         // must equal the pixel distance of the new center and that point.
456         var x = coordObj.clientX - gCanvas.offsetLeft;
457         var y = coordObj.clientY - gCanvas.offsetTop;
458         // Debug output: "coordinates" of the point the mouse was over.
459         /*
460         var ptCoord = {x: gPos.x + (x - gCanvas.width / 2) * gZoomFactor,
461                        y: gPos.y + (x - gCanvas.height / 2) * gZoomFactor};
462         var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
463         var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
464         document.getElementById("debug").textContent =
465             ptCoord.x + "/" + ptCoord.y + " - " +
466             gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
467             pt2Coord.x + "/" + pt2Coord.y;
468         */
469         // Zoom factor after this action.
470         var newZoomFactor = Math.pow(2, gMaxZoom - gPos.z + (delta > 0 ? -1 : 1));
471         gPos.x -= (x - gCanvas.width / 2) * (newZoomFactor - gZoomFactor);
472         gPos.y -= (y - gCanvas.height / 2) * (newZoomFactor - gZoomFactor);
473
474         if (delta > 0)
475           zoomIn();
476         else if (delta < 0)
477           zoomOut();
478         break;
479     }
480   }
481 };
482
483 var geofake = {
484   tracking: false,
485   lastPos: {x: undefined, y: undefined},
486   watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
487     this.tracking = true;
488     var watchCall = function() {
489       // calc new position in lat/lon degrees
490       // 90° on Earth surface are ~10,000 km at the equator,
491       // so try moving at most 10m at a time
492       if (geofake.lastPos.x)
493         geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
494       else
495         geofake.lastPos.x = 48.208174
496       if (geofake.lastPos.y)
497         geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
498       else
499         geofake.lastPos.y = 16.373819
500       aSuccessCallback({timestamp: Date.now(),
501                         coords: {latitude: geofake.lastPos.x,
502                                  longitude: geofake.lastPos.y,
503                                  accuracy: 20}});
504       if (geofake.tracking)
505         setTimeout(watchCall, 1000);
506     };
507     setTimeout(watchCall, 1000);
508     return "foo";
509   },
510   clearWatch: function(aID) {
511     this.tracking = false;
512   }
513 }
514
515 function setCentering(aCheckbox) {
516   if (gMapPrefsLoaded && mainDB)
517     gPrefs.set("center_map", aCheckbox.checked);
518   gCenterPosition = aCheckbox.checked;
519 }
520
521 function setTracking(aCheckbox) {
522   if (gMapPrefsLoaded && mainDB)
523     gPrefs.set("tracking_enabled", aCheckbox.checked);
524   if (aCheckbox.checked)
525     startTracking();
526   else
527     endTracking();
528 }
529
530 function startTracking() {
531   var loopCnt = 0;
532   var getStoredTrack = function() {
533     if (mainDB)
534       gTrackStore.getList(function(aTPoints) {
535         if (gDebug)
536           document.getElementById("debug").textContent = aTPoints.length + " points loaded.";
537         if (aTPoints.length) {
538           gTrack = aTPoints;
539         }
540       });
541     else
542       setTimeout(getStoredTrack, 100);
543     loopCnt++;
544     if (loopCnt > 20)
545       return;
546   };
547   getStoredTrack();
548   if (gGeolocation) {
549     gGeoWatchID = gGeolocation.watchPosition(
550       function(position) {
551         // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
552         var tPoint = {time: position.timestamp,
553                       coords: {latitude: position.coords.latitude,
554                                longitude: position.coords.longitude,
555                                altitude: position.coords.altitude,
556                                accuracy: position.coords.accuracy,
557                                altitudeAccuracy: position.coords.altitudeAccuracy,
558                                heading: position.coords.heading,
559                                speed: position.coords.speed},
560                       beginSegment: !gLastTrackPoint};
561         // Only add point to track is accuracy is good enough.
562         if (tPoint.coords.accuracy < gMinTrackAccuracy) {
563           gLastTrackPoint = tPoint;
564           gTrack.push(tPoint);
565           try { gTrackStore.push(tPoint); } catch(e) {}
566           var redrawn = false;
567           if (gCenterPosition) {
568             var posCoord = gps2xy(position.coords.latitude,
569                                   position.coords.longitude);
570             if (Math.abs(gPos.x - posCoord.x) > gCanvas.width * gZoomFactor / 4 ||
571                 Math.abs(gPos.y - posCoord.y) > gCanvas.height * gZoomFactor / 4) {
572               gPos.x = posCoord.x;
573               gPos.y = posCoord.y;
574               drawMap(); // This draws the current point as well.
575               redrawn = true;
576             }
577           }
578           if (!redrawn)
579             drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
580         }
581         drawCurrentLocation(tPoint);
582       },
583       function(error) {
584         // Ignore erros for the moment, but this is good for debugging.
585         // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
586         document.getElementById("debug").textContent = error.message;
587       },
588       {enableHighAccuracy: true}
589     );
590   }
591 }
592
593 function endTracking() {
594   if (gGeoWatchID) {
595     gGeolocation.clearWatch(gGeoWatchID);
596   }
597 }
598
599 function clearTrack() {
600   gTrack = [];
601   gTrackStore.clear();
602   drawMap();
603 }