improved debug message
[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 gMapCanvas, gMapContext, gTrackCanvas, gTrackContext, 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 = 6; // pixels
15 var gCurLocColor = "#A00000";
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   gMapCanvas = document.getElementById("map");
79   gMapContext = gMapCanvas.getContext("2d");
80   gTrackCanvas = document.getElementById("track");
81   gTrackContext = gTrackCanvas.getContext("2d");
82   if (!gActiveMap)
83     gActiveMap = "osm_mapnik";
84
85   //gDebug = true;
86   if (gDebug) {
87     gGeolocation = geofake;
88     var hiddenList = document.getElementsByClassName("debugHide");
89     // last to first - list of elements with that class is changing!
90     for (var i = hiddenList.length - 1; i >= 0; i--) {
91       hiddenList[i].classList.remove("debugHide");
92     }
93   }
94
95   var loopCnt = 0;
96   var getPersistentPrefs = function() {
97     if (mainDB) {
98       gWaitCounter++;
99       gPrefs.get("position", function(aValue) {
100         if (aValue) {
101           gPos = aValue;
102           gWaitCounter--;
103         }
104       });
105       gWaitCounter++;
106       gPrefs.get("center_map", function(aValue) {
107         if (aValue === undefined)
108           document.getElementById("centerCheckbox").checked = true;
109         else
110           document.getElementById("centerCheckbox").checked = aValue;
111         setCentering(document.getElementById("centerCheckbox"));
112         gWaitCounter--;
113       });
114       gWaitCounter++;
115       gPrefs.get("tracking_enabled", function(aValue) {
116         if (aValue === undefined)
117           document.getElementById("trackCheckbox").checked = true;
118         else
119           document.getElementById("trackCheckbox").checked = aValue;
120         gWaitCounter--;
121       });
122       gWaitCounter++;
123       gTrackStore.getList(function(aTPoints) {
124         if (gDebug)
125           document.getElementById("debug").textContent = aTPoints.length + " points loaded.";
126         if (aTPoints.length) {
127           gTrack = aTPoints;
128         }
129         gWaitCounter--;
130       });
131     }
132     else
133       setTimeout(getPersistentPrefs, 100);
134     loopCnt++;
135     if (loopCnt > 50) {
136       document.getElementById("debug").textContent = "Loading prefs failed.";
137     }
138   };
139   getPersistentPrefs();
140
141   gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
142   gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
143   gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
144   gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
145
146   gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
147   gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
148   gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
149   gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
150   gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
151
152   // XXX deprecated? see https://groups.google.com/forum/?fromgroups#!topic/mozilla.dev.planning/kuhrORubaRY[1-25]
153   gTrackCanvas.addEventListener("DOMMouseScroll", mapEvHandler, false);
154   gTrackCanvas.addEventListener("mousewheel", mapEvHandler, false);
155
156   document.getElementById("copyright").innerHTML =
157       gMapStyles[gActiveMap].copyright;
158
159   gLoadingTile = new Image();
160   gLoadingTile.src = "style/loading.png";
161   gWaitCounter++;
162   gLoadingTile.onload = function() { gWaitCounter--; };
163 }
164
165 function resizeAndDraw() {
166   var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
167   var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
168
169   gMapCanvas.width = viewportWidth;
170   gMapCanvas.height = viewportHeight;
171   gTrackCanvas.width = viewportWidth;
172   gTrackCanvas.height = viewportHeight;
173   drawMap();
174   showUI();
175 }
176
177 function zoomIn() {
178   if (gPos.z < gMaxZoom) {
179     gPos.z++;
180     drawMap();
181   }
182 }
183
184 function zoomOut() {
185   if (gPos.z > 0) {
186     gPos.z--;
187     drawMap();
188   }
189 }
190
191 function gps2xy(aLatitude, aLongitude) {
192   var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
193   var convLat = aLatitude * Math.PI / 180;
194   var rawY = (1 - Math.log(Math.tan(convLat) +
195                            1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
196   var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
197   return {x: Math.round(rawX),
198           y: Math.round(rawY)};
199 }
200
201 function xy2gps(aX, aY) {
202   var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
203   var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
204   return {latitude: 180 / Math.PI *
205                     Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
206           longitude: aX / maxZoomFactor * 360 - 180};
207 }
208
209 function setMapStyle() {
210   var mapSel = document.getElementById("mapSelector");
211   if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
212     gActiveMap = mapSel.value;
213     gTiles = {};
214     document.getElementById("copyright").innerHTML =
215         gMapStyles[gActiveMap].copyright;
216     showUI();
217     drawMap();
218   }
219 }
220
221 // A sane mod function that works for negative numbers.
222 // Returns a % b.
223 function mod(a, b) {
224   return ((a % b) + b) % b;
225 }
226
227 function normaliseIndices(x, y, z) {
228   var zoomFactor = Math.pow(2, z);
229   return {x: mod(x, zoomFactor),
230           y: mod(y, zoomFactor),
231           z: z};
232 }
233
234 function tileURL(x, y, z) {
235   var norm = normaliseIndices(x, y, z);
236   return gMapStyles[gActiveMap].url
237          .replace("{x}", norm.x)
238          .replace("{y}", norm.y)
239          .replace("{z}", norm.z)
240          .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
241          .replace("[1-4]", 1 + Math.floor(Math.random() * 3));
242 }
243
244 // Returns true if the tile is outside the current view.
245 function isOutsideWindow(t) {
246   var pos = decodeIndex(t);
247
248   var zoomFactor = Math.pow(2, gMaxZoom - pos.z);
249   var wid = gMapCanvas.width * zoomFactor;
250   var ht = gMapCanvas.height * zoomFactor;
251
252   pos.x *= zoomFactor;
253   pos.y *= zoomFactor;
254
255   var sz = gTileSize * zoomFactor;
256   if (pos.x > gPos.x + wid / 2 || pos.y > gPos.y + ht / 2 ||
257       pos.x + sz < gPos.x - wid / 2 || pos.y - sz < gPos.y - ht / 2)
258     return true;
259   return false;
260 }
261
262 function encodeIndex(x, y, z) {
263   var norm = normaliseIndices(x, y, z);
264   return norm.x + "," + norm.y + "," + norm.z;
265 }
266
267 function decodeIndex(encodedIdx) {
268   var ind = encodedIdx.split(",", 3);
269   return {x: ind[0], y: ind[1], z: ind[2]};
270 }
271
272 function drawMap() {
273   // Go through all the currently loaded tiles. If we don't want any of them remove them.
274   // for (t in gTiles) {
275   //   if (isOutsideWindow(t))
276   //     delete gTiles[t];
277   // }
278   document.getElementById("zoomLevel").textContent = gPos.z;
279   gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
280   var wid = gMapCanvas.width * gZoomFactor; // Width in level 18 pixels.
281   var ht = gMapCanvas.height * gZoomFactor; // Height in level 18 pixels.
282   var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
283
284   var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
285   var yMin = gPos.y - ht / 2;
286   var xMax = gPos.x + wid / 2;
287   var yMax = gPos.y + ht / 2;
288
289   if (gMapPrefsLoaded && mainDB)
290     gPrefs.set("position", gPos);
291
292   // Go through all the tiles we want.
293   // If any of them aren't loaded or being loaded, do so.
294   for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
295     for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
296       // Round here is **CRUCIAL** otherwise the images are filtered
297       // and the performance sucks (more than expected).
298       var xoff = Math.round((x * size - xMin) / gZoomFactor);
299       var yoff = Math.round((y * size - yMin) / gZoomFactor);
300       var tileKey = encodeIndex(x, y, gPos.z);
301       if (gTiles[tileKey] && gTiles[tileKey].complete) {
302         gMapContext.drawImage(gTiles[tileKey], xoff, yoff);
303       }
304       else {
305         // Draw placeholder, and then initiate loading/drawing of real one.
306         gMapContext.drawImage(gLoadingTile, xoff, yoff);
307         if (!gTiles[tileKey]) {
308           gTiles[tileKey] = new Image();
309           // Use alt field to communicate info to .onload.
310           gTiles[tileKey].alt = gPos.z + ":" + xoff + ":" + yoff;
311           gTiles[tileKey].src = tileURL(x, y, gPos.z);
312           gTiles[tileKey].onload = function() {
313             var tdata = this.alt.split(":", 3);
314             // Draw the tile if we're still looking at the same zoom.
315             if (tdata[0] == gPos.z) {
316               gMapContext.drawImage(this, tdata[1], tdata[2]);
317             }
318             this.alt = "";
319           }
320         }
321         else {
322           // Update position to draw this image to when loaded.
323           gTiles[tileKey].alt = gPos.z + ":" + xoff + ":" + yoff;
324         }
325       }
326     }
327   }
328   gLastDrawnPoint = null;
329   gCurPosMapCache = undefined;
330   gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
331   if (gTrack.length) {
332     for (var i = 0; i < gTrack.length; i++) {
333       drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
334                      (i + 1 >= gTrack.length));
335     }
336   }
337 }
338
339 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
340   var trackpoint = gps2xy(aLatitude, aLongitude);
341   // lastPoint is for optimizing (not actually executing the draw until the last)
342   trackpoint.optimized = (lastPoint === false);
343   var mappos = {x: Math.round((trackpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
344                 y: Math.round((trackpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
345
346   if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
347     gTrackContext.strokeStyle = gTrackColor;
348     gTrackContext.fillStyle = gTrackContext.strokeStyle;
349     gTrackContext.lineWidth = gTrackWidth;
350     gTrackContext.lineCap = "round";
351     gTrackContext.lineJoin = "round";
352   }
353   if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
354     // This breaks optimiziation, so make sure to close path and reset optimization.
355     if (gLastDrawnPoint && gLastDrawnPoint.optimized)
356       gTrackContext.stroke();
357     gTrackContext.beginPath();
358     trackpoint.optimized = false;
359     gTrackContext.arc(mappos.x, mappos.y,
360                       gTrackContext.lineWidth, 0, Math.PI * 2, false);
361     gTrackContext.fill();
362   }
363   else {
364     if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
365       gTrackContext.beginPath();
366       gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
367                            Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2));
368     }
369     gTrackContext.lineTo(mappos.x, mappos.y);
370     if (!trackpoint.optimized)
371       gTrackContext.stroke();
372   }
373   gLastDrawnPoint = trackpoint;
374 }
375
376 function drawCurrentLocation(trackPoint) {
377   var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
378   var circleRadius = Math.round(gCurLocSize / 2);
379   var mappos = {x: Math.round((locpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
380                 y: Math.round((locpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
381
382   undrawCurrentLocation();
383
384   // Cache overdrawn area.
385   gCurPosMapCache =
386       {point: locpoint,
387        radius: circleRadius,
388        data: gTrackContext.getImageData(mappos.x - circleRadius,
389                                         mappos.y - circleRadius,
390                                         circleRadius * 2, circleRadius * 2)};
391
392   gTrackContext.strokeStyle = gCurLocColor;
393   gTrackContext.fillStyle = gTrackContext.strokeStyle;
394   gTrackContext.beginPath();
395   gTrackContext.arc(mappos.x, mappos.y,
396                     circleRadius, 0, Math.PI * 2, false);
397   gTrackContext.fill();
398 }
399
400 function undrawCurrentLocation() {
401   if (gCurPosMapCache) {
402     var oldpoint = gCurPosMapCache.point;
403     var oldmp = {x: Math.round((oldpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
404                  y: Math.round((oldpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
405     gTrackContext.putImageData(gCurPosMapCache.data,
406                                oldmp.x - gCurPosMapCache.radius,
407                                oldmp.y - gCurPosMapCache.radius);
408     gCurPosMapCache = undefined;
409   }
410 }
411
412 var mapEvHandler = {
413   handleEvent: function(aEvent) {
414     var touchEvent = aEvent.type.indexOf('touch') != -1;
415
416     // Bail out on unwanted map moves, but not zoom-changing events.
417     if (aEvent.type != "DOMMouseScroll" && aEvent.type != "mousewheel") {
418       // Bail out if this is neither a touch nor left-click.
419       if (!touchEvent && aEvent.button != 0)
420         return;
421
422       // Bail out if the started touch can't be found.
423       if (touchEvent && gDragging &&
424           !aEvent.changedTouches.identifiedTouch(gDragTouchID))
425         return;
426     }
427
428     var coordObj = touchEvent ?
429                    aEvent.changedTouches.identifiedTouch(gDragTouchID) :
430                    aEvent;
431
432     switch (aEvent.type) {
433       case "mousedown":
434       case "touchstart":
435         if (touchEvent) {
436           gDragTouchID = aEvent.changedTouches.item(0).identifier;
437           coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
438         }
439         var x = coordObj.clientX - gMapCanvas.offsetLeft;
440         var y = coordObj.clientY - gMapCanvas.offsetTop;
441
442         if (touchEvent || aEvent.button === 0) {
443           gDragging = true;
444         }
445         gLastMouseX = x;
446         gLastMouseY = y;
447         showUI();
448         break;
449       case "mousemove":
450       case "touchmove":
451         var x = coordObj.clientX - gMapCanvas.offsetLeft;
452         var y = coordObj.clientY - gMapCanvas.offsetTop;
453         if (gDragging === true) {
454           var dX = x - gLastMouseX;
455           var dY = y - gLastMouseY;
456           gPos.x -= dX * gZoomFactor;
457           gPos.y -= dY * gZoomFactor;
458           drawMap();
459           showUI();
460         }
461         gLastMouseX = x;
462         gLastMouseY = y;
463         break;
464       case "mouseup":
465       case "touchend":
466         gDragging = false;
467         showUI();
468         break;
469       case "mouseout":
470       case "touchcancel":
471       case "touchleave":
472         //gDragging = false;
473         break;
474       case "DOMMouseScroll":
475       case "mousewheel":
476         var delta = 0;
477         if (aEvent.wheelDelta) {
478           delta = aEvent.wheelDelta / 120;
479           if (window.opera)
480             delta = -delta;
481         }
482         else if (aEvent.detail) {
483           delta = -aEvent.detail / 3;
484         }
485
486         // Debug output: "coordinates" of the point the mouse was over.
487         /*
488         var ptCoord = {x: gPos.x + (x - gMapCanvas.width / 2) * gZoomFactor,
489                        y: gPos.y + (x - gMapCanvas.height / 2) * gZoomFactor};
490         var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
491         var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
492         document.getElementById("debug").textContent =
493             ptCoord.x + "/" + ptCoord.y + " - " +
494             gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
495             pt2Coord.x + "/" + pt2Coord.y;
496         */
497
498         var newZoomLevel = gPos.z + (delta > 0 ? 1 : -1);
499         if ((newZoomLevel >= 0) && (newZoomLevel <= gMaxZoom)) {
500           // Calculate new center of the map - same point stays under the mouse.
501           // This means that the pixel distance between the old center and point
502           // must equal the pixel distance of the new center and that point.
503           var x = coordObj.clientX - gMapCanvas.offsetLeft;
504           var y = coordObj.clientY - gMapCanvas.offsetTop;
505
506           // Zoom factor after this action.
507           var newZoomFactor = Math.pow(2, gMaxZoom - newZoomLevel);
508           gPos.x -= (x - gMapCanvas.width / 2) * (newZoomFactor - gZoomFactor);
509           gPos.y -= (y - gMapCanvas.height / 2) * (newZoomFactor - gZoomFactor);
510
511           if (delta > 0)
512             zoomIn();
513           else if (delta < 0)
514             zoomOut();
515         }
516         break;
517     }
518   }
519 };
520
521 var geofake = {
522   tracking: false,
523   lastPos: {x: undefined, y: undefined},
524   watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
525     this.tracking = true;
526     var watchCall = function() {
527       // calc new position in lat/lon degrees
528       // 90° on Earth surface are ~10,000 km at the equator,
529       // so try moving at most 10m at a time
530       if (geofake.lastPos.x)
531         geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
532       else
533         geofake.lastPos.x = 48.208174
534       if (geofake.lastPos.y)
535         geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
536       else
537         geofake.lastPos.y = 16.373819
538       aSuccessCallback({timestamp: Date.now(),
539                         coords: {latitude: geofake.lastPos.x,
540                                  longitude: geofake.lastPos.y,
541                                  accuracy: 20}});
542       if (geofake.tracking)
543         setTimeout(watchCall, 1000);
544     };
545     setTimeout(watchCall, 1000);
546     return "foo";
547   },
548   clearWatch: function(aID) {
549     this.tracking = false;
550   }
551 }
552
553 function setCentering(aCheckbox) {
554   if (gMapPrefsLoaded && mainDB)
555     gPrefs.set("center_map", aCheckbox.checked);
556   gCenterPosition = aCheckbox.checked;
557 }
558
559 function setTracking(aCheckbox) {
560   if (gMapPrefsLoaded && mainDB)
561     gPrefs.set("tracking_enabled", aCheckbox.checked);
562   if (aCheckbox.checked)
563     startTracking();
564   else
565     endTracking();
566 }
567
568 function startTracking() {
569   if (gGeolocation) {
570     gGeoWatchID = gGeolocation.watchPosition(
571       function(position) {
572         // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
573         var tPoint = {time: position.timestamp,
574                       coords: {latitude: position.coords.latitude,
575                                longitude: position.coords.longitude,
576                                altitude: position.coords.altitude,
577                                accuracy: position.coords.accuracy,
578                                altitudeAccuracy: position.coords.altitudeAccuracy,
579                                heading: position.coords.heading,
580                                speed: position.coords.speed},
581                       beginSegment: !gLastTrackPoint};
582         // Only add point to track is accuracy is good enough.
583         if (tPoint.coords.accuracy < gMinTrackAccuracy) {
584           gLastTrackPoint = tPoint;
585           gTrack.push(tPoint);
586           try { gTrackStore.push(tPoint); } catch(e) {}
587           var redrawn = false;
588           if (gCenterPosition) {
589             var posCoord = gps2xy(position.coords.latitude,
590                                   position.coords.longitude);
591             if (Math.abs(gPos.x - posCoord.x) > gMapCanvas.width * gZoomFactor / 4 ||
592                 Math.abs(gPos.y - posCoord.y) > gMapCanvas.height * gZoomFactor / 4) {
593               gPos.x = posCoord.x;
594               gPos.y = posCoord.y;
595               drawMap(); // This draws the current point as well.
596               redrawn = true;
597             }
598           }
599           if (!redrawn)
600             undrawCurrentLocation();
601             drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
602         }
603         drawCurrentLocation(tPoint);
604       },
605       function(error) {
606         // Ignore erros for the moment, but this is good for debugging.
607         // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
608         document.getElementById("debug").textContent = error.message;
609       },
610       {enableHighAccuracy: true}
611     );
612   }
613 }
614
615 function endTracking() {
616   if (gGeoWatchID) {
617     gGeolocation.clearWatch(gGeoWatchID);
618   }
619 }
620
621 function clearTrack() {
622   gTrack = [];
623   gTrackStore.clear();
624   drawMap();
625 }