b5fe9e2a088607063160a1be0d54cbd252c3b09d
[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://otile[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 var gLoadingTile;
60
61 var gMapPrefsLoaded = false;
62
63 var gDragging = false;
64 var gDragTouchID;
65
66 var gGeoWatchID;
67 var gTrack = [];
68 var gLastTrackPoint, gLastDrawnPoint;
69 var gCenterPosition = true;
70
71 var gCurPosMapCache;
72
73 function initMap() {
74   gGeolocation = navigator.geolocation;
75   gMapCanvas = document.getElementById("map");
76   gMapContext = gMapCanvas.getContext("2d");
77   gTrackCanvas = document.getElementById("track");
78   gTrackContext = gTrackCanvas.getContext("2d");
79   if (!gActiveMap)
80     gActiveMap = "osm_mapnik";
81
82   //gDebug = true;
83   if (gDebug) {
84     gGeolocation = geofake;
85     var hiddenList = document.getElementsByClassName("debugHide");
86     // last to first - list of elements with that class is changing!
87     for (var i = hiddenList.length - 1; i >= 0; i--) {
88       hiddenList[i].classList.remove("debugHide");
89     }
90   }
91
92   var loopCnt = 0;
93   var getPersistentPrefs = function() {
94     if (mainDB) {
95       gWaitCounter++;
96       gPrefs.get("position", function(aValue) {
97         if (aValue) {
98           gPos = aValue;
99           gWaitCounter--;
100         }
101       });
102       gWaitCounter++;
103       gPrefs.get("center_map", function(aValue) {
104         if (aValue === undefined)
105           document.getElementById("centerCheckbox").checked = true;
106         else
107           document.getElementById("centerCheckbox").checked = aValue;
108         setCentering(document.getElementById("centerCheckbox"));
109         gWaitCounter--;
110       });
111       gWaitCounter++;
112       gPrefs.get("tracking_enabled", function(aValue) {
113         if (aValue === undefined)
114           document.getElementById("trackCheckbox").checked = true;
115         else
116           document.getElementById("trackCheckbox").checked = aValue;
117         gWaitCounter--;
118       });
119       gWaitCounter++;
120       gTrackStore.getList(function(aTPoints) {
121         if (gDebug)
122           console.log(aTPoints.length + " points loaded.");
123         if (aTPoints.length) {
124           gTrack = aTPoints;
125         }
126         gWaitCounter--;
127       });
128     }
129     else
130       setTimeout(getPersistentPrefs, 100);
131     loopCnt++;
132     if (loopCnt > 50) {
133       console.log("Loading prefs failed.");
134     }
135   };
136   getPersistentPrefs();
137
138   gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
139   gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
140   gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
141   gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
142
143   gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
144   gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
145   gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
146   gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
147   gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
148
149   // XXX deprecated? see https://groups.google.com/forum/?fromgroups#!topic/mozilla.dev.planning/kuhrORubaRY[1-25]
150   gTrackCanvas.addEventListener("DOMMouseScroll", mapEvHandler, false);
151   gTrackCanvas.addEventListener("mousewheel", mapEvHandler, false);
152
153   document.getElementById("copyright").innerHTML =
154       gMapStyles[gActiveMap].copyright;
155
156   gLoadingTile = new Image();
157   gLoadingTile.src = "style/loading.png";
158   gWaitCounter++;
159   gLoadingTile.onload = function() { gWaitCounter--; };
160 }
161
162 function resizeAndDraw() {
163   var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
164   var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
165   if (gMapCanvas && gTrackCanvas) {
166     gMapCanvas.width = viewportWidth;
167     gMapCanvas.height = viewportHeight;
168     gTrackCanvas.width = viewportWidth;
169     gTrackCanvas.height = viewportHeight;
170     drawMap();
171     showUI();
172   }
173 }
174
175 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
176 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
177
178 function zoomIn() {
179   if (gPos.z < gMaxZoom) {
180     gPos.z++;
181     drawMap();
182   }
183 }
184
185 function zoomOut() {
186   if (gPos.z > 0) {
187     gPos.z--;
188     drawMap();
189   }
190 }
191
192 function gps2xy(aLatitude, aLongitude) {
193   var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
194   var convLat = aLatitude * Math.PI / 180;
195   var rawY = (1 - Math.log(Math.tan(convLat) +
196                            1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
197   var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
198   return {x: Math.round(rawX),
199           y: Math.round(rawY)};
200 }
201
202 function xy2gps(aX, aY) {
203   var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
204   var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
205   return {latitude: 180 / Math.PI *
206                     Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
207           longitude: aX / maxZoomFactor * 360 - 180};
208 }
209
210 function setMapStyle() {
211   var mapSel = document.getElementById("mapSelector");
212   if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
213     gActiveMap = mapSel.value;
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 normalizeCoords(aCoords) {
228   var zoomFactor = Math.pow(2, aCoords.z);
229   return {x: mod(aCoords.x, zoomFactor),
230           y: mod(aCoords.y, zoomFactor),
231           z: aCoords.z};
232 }
233
234 // Returns true if the tile is outside the current view.
235 function isOutsideWindow(t) {
236   var pos = decodeIndex(t);
237
238   var zoomFactor = Math.pow(2, gMaxZoom - pos.z);
239   var wid = gMapCanvas.width * zoomFactor;
240   var ht = gMapCanvas.height * zoomFactor;
241
242   pos.x *= zoomFactor;
243   pos.y *= zoomFactor;
244
245   var sz = gTileSize * zoomFactor;
246   if (pos.x > gPos.x + wid / 2 || pos.y > gPos.y + ht / 2 ||
247       pos.x + sz < gPos.x - wid / 2 || pos.y - sz < gPos.y - ht / 2)
248     return true;
249   return false;
250 }
251
252 function encodeIndex(x, y, z) {
253   var norm = normalizeCoords({x: x, y: y, z: z});
254   return norm.x + "," + norm.y + "," + norm.z;
255 }
256
257 function decodeIndex(encodedIdx) {
258   var ind = encodedIdx.split(",", 3);
259   return {x: ind[0], y: ind[1], z: ind[2]};
260 }
261
262 function drawMap(aPixels, aOverdraw) {
263   // aPixels is an object with left/right/top/bottom members telling how many
264   //   pixels on the borders should actually be drawn.
265   // aOverdraw is a bool that tells if we should draw placeholders or draw
266   //   straight over the existing content.
267   if (!aPixels)
268     aPixels = {left: gMapCanvas.width, right: gMapCanvas.width,
269                top: gMapCanvas.height, bottom: gMapCanvas.height};
270   if (!aOverdraw)
271     aOverdraw = false;
272
273   document.getElementById("zoomLevel").textContent = gPos.z;
274   gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
275   var wid = gMapCanvas.width * gZoomFactor; // Width in level 18 pixels.
276   var ht = gMapCanvas.height * gZoomFactor; // Height in level 18 pixels.
277   var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
278
279   var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
280   var yMin = gPos.y - ht / 2;
281   var xMax = gPos.x + wid / 2;
282   var yMax = gPos.y + ht / 2;
283
284   if (gMapPrefsLoaded && mainDB)
285     gPrefs.set("position", gPos);
286
287   var tiles = {left: Math.ceil((xMin + aPixels.left * gZoomFactor) / size) -
288                                (aPixels.left ? 0 : 1),
289                right: Math.floor((xMax - aPixels.right * gZoomFactor) / size) -
290                                  (aPixels.right ? 1 : 0),
291                top: Math.ceil((yMin + aPixels.top * gZoomFactor) / size) -
292                               (aPixels.top ? 0 : 1),
293                bottom: Math.floor((yMax - aPixels.bottom * gZoomFactor) / size) -
294                                   (aPixels.bottom ? 1 : 0)};
295
296   // Go through all the tiles in the map, find out if to draw them and do so.
297   for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
298     for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
299       // Only go to the drawing step if we need to draw this tile.
300       if (x < tiles.left || x > tiles.right ||
301           y < tiles.top || y > tiles.bottom) {
302         // Round here is **CRUCIAL** otherwise the images are filtered
303         // and the performance sucks (more than expected).
304         var xoff = Math.round((x * size - xMin) / gZoomFactor);
305         var yoff = Math.round((y * size - yMin) / gZoomFactor);
306         // Draw placeholder tile unless we overdraw.
307         if (!aOverdraw &&
308             (x < tiles.left -1  || x > tiles.right + 1 ||
309              y < tiles.top -1 || y > tiles.bottom + 1))
310           gMapContext.drawImage(gLoadingTile, xoff, yoff);
311
312         // Initiate loading/drawing of the actual tile.
313         gTileService.get(gActiveMap, {x: x, y: y, z: gPos.z},
314                          function(aImage, aStyle, aCoords) {
315           // Only draw if this applies for the current view.
316           if ((aStyle == gActiveMap) && (aCoords.z == gPos.z)) {
317             var ixMin = gPos.x - wid / 2;
318             var iyMin = gPos.y - ht / 2;
319             var ixoff = Math.round((aCoords.x * size - ixMin) / gZoomFactor);
320             var iyoff = Math.round((aCoords.y * size - iyMin) / gZoomFactor);
321             var URL = window.URL;
322             var imgURL = URL.createObjectURL(aImage);
323             var imgObj = new Image();
324             imgObj.src = imgURL;
325             imgObj.onload = function() {
326               gMapContext.drawImage(imgObj, ixoff, iyoff);
327               URL.revokeObjectURL(imgURL);
328             }
329           }
330         });
331       }
332     }
333   }
334   gLastDrawnPoint = null;
335   gCurPosMapCache = undefined;
336   gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
337   if (gTrack.length) {
338     for (var i = 0; i < gTrack.length; i++) {
339       drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
340                      (i + 1 >= gTrack.length));
341     }
342   }
343 }
344
345 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
346   var trackpoint = gps2xy(aLatitude, aLongitude);
347   // lastPoint is for optimizing (not actually executing the draw until the last)
348   trackpoint.optimized = (lastPoint === false);
349   var mappos = {x: Math.round((trackpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
350                 y: Math.round((trackpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
351
352   if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
353     gTrackContext.strokeStyle = gTrackColor;
354     gTrackContext.fillStyle = gTrackContext.strokeStyle;
355     gTrackContext.lineWidth = gTrackWidth;
356     gTrackContext.lineCap = "round";
357     gTrackContext.lineJoin = "round";
358   }
359   if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
360     // This breaks optimiziation, so make sure to close path and reset optimization.
361     if (gLastDrawnPoint && gLastDrawnPoint.optimized)
362       gTrackContext.stroke();
363     gTrackContext.beginPath();
364     trackpoint.optimized = false;
365     gTrackContext.arc(mappos.x, mappos.y,
366                       gTrackContext.lineWidth, 0, Math.PI * 2, false);
367     gTrackContext.fill();
368   }
369   else {
370     if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
371       gTrackContext.beginPath();
372       gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
373                            Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2));
374     }
375     gTrackContext.lineTo(mappos.x, mappos.y);
376     if (!trackpoint.optimized)
377       gTrackContext.stroke();
378   }
379   gLastDrawnPoint = trackpoint;
380 }
381
382 function drawCurrentLocation(trackPoint) {
383   var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
384   var circleRadius = Math.round(gCurLocSize / 2);
385   var mappos = {x: Math.round((locpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
386                 y: Math.round((locpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
387
388   undrawCurrentLocation();
389
390   // Cache overdrawn area.
391   gCurPosMapCache =
392       {point: locpoint,
393        radius: circleRadius,
394        data: gTrackContext.getImageData(mappos.x - circleRadius,
395                                         mappos.y - circleRadius,
396                                         circleRadius * 2, circleRadius * 2)};
397
398   gTrackContext.strokeStyle = gCurLocColor;
399   gTrackContext.fillStyle = gTrackContext.strokeStyle;
400   gTrackContext.beginPath();
401   gTrackContext.arc(mappos.x, mappos.y,
402                     circleRadius, 0, Math.PI * 2, false);
403   gTrackContext.fill();
404 }
405
406 function undrawCurrentLocation() {
407   if (gCurPosMapCache) {
408     var oldpoint = gCurPosMapCache.point;
409     var oldmp = {x: Math.round((oldpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
410                  y: Math.round((oldpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
411     gTrackContext.putImageData(gCurPosMapCache.data,
412                                oldmp.x - gCurPosMapCache.radius,
413                                oldmp.y - gCurPosMapCache.radius);
414     gCurPosMapCache = undefined;
415   }
416 }
417
418 var mapEvHandler = {
419   handleEvent: function(aEvent) {
420     var touchEvent = aEvent.type.indexOf('touch') != -1;
421
422     // Bail out on unwanted map moves, but not zoom-changing events.
423     if (aEvent.type != "DOMMouseScroll" && aEvent.type != "mousewheel") {
424       // Bail out if this is neither a touch nor left-click.
425       if (!touchEvent && aEvent.button != 0)
426         return;
427
428       // Bail out if the started touch can't be found.
429       if (touchEvent && gDragging &&
430           !aEvent.changedTouches.identifiedTouch(gDragTouchID))
431         return;
432     }
433
434     var coordObj = touchEvent ?
435                    aEvent.changedTouches.identifiedTouch(gDragTouchID) :
436                    aEvent;
437
438     switch (aEvent.type) {
439       case "mousedown":
440       case "touchstart":
441         if (touchEvent) {
442           gDragTouchID = aEvent.changedTouches.item(0).identifier;
443           coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
444         }
445         var x = coordObj.clientX - gMapCanvas.offsetLeft;
446         var y = coordObj.clientY - gMapCanvas.offsetTop;
447
448         if (touchEvent || aEvent.button === 0) {
449           gDragging = true;
450         }
451         gLastMouseX = x;
452         gLastMouseY = y;
453         showUI();
454         break;
455       case "mousemove":
456       case "touchmove":
457         var x = coordObj.clientX - gMapCanvas.offsetLeft;
458         var y = coordObj.clientY - gMapCanvas.offsetTop;
459         if (gDragging === true) {
460           var dX = x - gLastMouseX;
461           var dY = y - gLastMouseY;
462           gPos.x -= dX * gZoomFactor;
463           gPos.y -= dY * gZoomFactor;
464           var mapData = gMapContext.getImageData(0, 0, gMapCanvas.width, gMapCanvas.height);
465           gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
466           gMapContext.putImageData(mapData, dX, dY);
467           drawMap({left: (dX > 0) ? dX : 0,
468                    right: (dX < 0) ? -dX : 0,
469                    top: (dY > 0) ? dY : 0,
470                    bottom: (dY < 0) ? -dY : 0});
471           showUI();
472         }
473         gLastMouseX = x;
474         gLastMouseY = y;
475         break;
476       case "mouseup":
477       case "touchend":
478         gDragging = false;
479         showUI();
480         break;
481       case "mouseout":
482       case "touchcancel":
483       case "touchleave":
484         //gDragging = false;
485         break;
486       case "DOMMouseScroll":
487       case "mousewheel":
488         var delta = 0;
489         if (aEvent.wheelDelta) {
490           delta = aEvent.wheelDelta / 120;
491           if (window.opera)
492             delta = -delta;
493         }
494         else if (aEvent.detail) {
495           delta = -aEvent.detail / 3;
496         }
497
498         // Debug output: "coordinates" of the point the mouse was over.
499         /*
500         var ptCoord = {x: gPos.x + (x - gMapCanvas.width / 2) * gZoomFactor,
501                        y: gPos.y + (x - gMapCanvas.height / 2) * gZoomFactor};
502         var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
503         var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
504         console.log(ptCoord.x + "/" + ptCoord.y + " - " +
505                     gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
506                     pt2Coord.x + "/" + pt2Coord.y);
507         */
508
509         var newZoomLevel = gPos.z + (delta > 0 ? 1 : -1);
510         if ((newZoomLevel >= 0) && (newZoomLevel <= gMaxZoom)) {
511           // Calculate new center of the map - same point stays under the mouse.
512           // This means that the pixel distance between the old center and point
513           // must equal the pixel distance of the new center and that point.
514           var x = coordObj.clientX - gMapCanvas.offsetLeft;
515           var y = coordObj.clientY - gMapCanvas.offsetTop;
516
517           // Zoom factor after this action.
518           var newZoomFactor = Math.pow(2, gMaxZoom - newZoomLevel);
519           gPos.x -= (x - gMapCanvas.width / 2) * (newZoomFactor - gZoomFactor);
520           gPos.y -= (y - gMapCanvas.height / 2) * (newZoomFactor - gZoomFactor);
521
522           if (delta > 0)
523             zoomIn();
524           else if (delta < 0)
525             zoomOut();
526         }
527         break;
528     }
529   }
530 };
531
532 var geofake = {
533   tracking: false,
534   lastPos: {x: undefined, y: undefined},
535   watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
536     this.tracking = true;
537     var watchCall = function() {
538       // calc new position in lat/lon degrees
539       // 90° on Earth surface are ~10,000 km at the equator,
540       // so try moving at most 10m at a time
541       if (geofake.lastPos.x)
542         geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
543       else
544         geofake.lastPos.x = 48.208174
545       if (geofake.lastPos.y)
546         geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
547       else
548         geofake.lastPos.y = 16.373819
549       aSuccessCallback({timestamp: Date.now(),
550                         coords: {latitude: geofake.lastPos.x,
551                                  longitude: geofake.lastPos.y,
552                                  accuracy: 20}});
553       if (geofake.tracking)
554         setTimeout(watchCall, 1000);
555     };
556     setTimeout(watchCall, 1000);
557     return "foo";
558   },
559   clearWatch: function(aID) {
560     this.tracking = false;
561   }
562 }
563
564 function setCentering(aCheckbox) {
565   if (gMapPrefsLoaded && mainDB)
566     gPrefs.set("center_map", aCheckbox.checked);
567   gCenterPosition = aCheckbox.checked;
568 }
569
570 function setTracking(aCheckbox) {
571   if (gMapPrefsLoaded && mainDB)
572     gPrefs.set("tracking_enabled", aCheckbox.checked);
573   if (aCheckbox.checked)
574     startTracking();
575   else
576     endTracking();
577 }
578
579 function startTracking() {
580   if (gGeolocation) {
581     gActionLabel.textContent = "Establishing Position";
582     gAction.style.display = "block";
583     gGeoWatchID = gGeolocation.watchPosition(
584       function(position) {
585         if (gActionLabel.textContent) {
586           gActionLabel.textContent = "";
587           gAction.style.display = "none";
588         }
589         // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
590         var tPoint = {time: position.timestamp,
591                       coords: {latitude: position.coords.latitude,
592                                longitude: position.coords.longitude,
593                                altitude: position.coords.altitude,
594                                accuracy: position.coords.accuracy,
595                                altitudeAccuracy: position.coords.altitudeAccuracy,
596                                heading: position.coords.heading,
597                                speed: position.coords.speed},
598                       beginSegment: !gLastTrackPoint};
599         // Only add point to track is accuracy is good enough.
600         if (tPoint.coords.accuracy < gMinTrackAccuracy) {
601           gLastTrackPoint = tPoint;
602           gTrack.push(tPoint);
603           try { gTrackStore.push(tPoint); } catch(e) {}
604           var redrawn = false;
605           if (gCenterPosition) {
606             var posCoord = gps2xy(position.coords.latitude,
607                                   position.coords.longitude);
608             if (Math.abs(gPos.x - posCoord.x) > gMapCanvas.width * gZoomFactor / 4 ||
609                 Math.abs(gPos.y - posCoord.y) > gMapCanvas.height * gZoomFactor / 4) {
610               gPos.x = posCoord.x;
611               gPos.y = posCoord.y;
612               drawMap(); // This draws the current point as well.
613               redrawn = true;
614             }
615           }
616           if (!redrawn)
617             undrawCurrentLocation();
618             drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
619         }
620         drawCurrentLocation(tPoint);
621       },
622       function(error) {
623         // Ignore erros for the moment, but this is good for debugging.
624         // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
625         if (gDebug)
626           console.log(error.message);
627       },
628       {enableHighAccuracy: true}
629     );
630   }
631 }
632
633 function endTracking() {
634   if (gActionLabel.textContent) {
635     gActionLabel.textContent = "";
636     gAction.style.display = "none";
637   }
638   if (gGeoWatchID) {
639     gGeolocation.clearWatch(gGeoWatchID);
640   }
641 }
642
643 function clearTrack() {
644   gTrack = [];
645   gTrackStore.clear();
646   drawMap();
647 }
648
649 var gTileService = {
650   objStore: "tilecache",
651
652   get: function(aStyle, aCoords, aCallback) {
653     var norm = normalizeCoords(aCoords);
654     var dbkey = aStyle + "::" + norm.x + "," + norm.y + "," + norm.z;
655     this.getDBCache(dbkey, function(aResult, aEvent) {
656       if (aResult) {
657         // We did get a cached object.
658         // TODO: Look at the timestamp and trigger a reload when it's too old.
659         aCallback(aResult.image, aStyle, aCoords);
660       }
661       else {
662         // Retrieve image from the web and store it in the cache.
663         var XHR = new XMLHttpRequest();
664         XHR.open("GET",
665                  gMapStyles[aStyle].url
666                    .replace("{x}", norm.x)
667                    .replace("{y}", norm.y)
668                    .replace("{z}", norm.z)
669                    .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
670                    .replace("[1-4]", 1 + Math.floor(Math.random() * 3)),
671                  true);
672         XHR.responseType = "blob";
673         XHR.addEventListener("load", function () {
674           if (XHR.status === 200) {
675             var blob = XHR.response;
676             gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
677             aCallback(blob, aStyle, aCoords);
678           }
679         }, false);
680         XHR.send();
681       }
682     });
683   },
684
685   getDBCache: function(aKey, aCallback) {
686     if (!mainDB)
687       return;
688     var transaction = mainDB.transaction([this.objStore]);
689     var request = transaction.objectStore(this.objStore).get(aKey);
690     request.onsuccess = function(event) {
691       aCallback(request.result, event);
692     };
693     request.onerror = function(event) {
694       // Errors can be handled here.
695       aCallback(undefined, event);
696     };
697   },
698
699   setDBCache: function(aKey, aValue, aCallback) {
700     if (!mainDB)
701       return;
702     var success = false;
703     var transaction = mainDB.transaction([this.objStore], "readwrite");
704     var objStore = transaction.objectStore(this.objStore);
705     var request = objStore.put(aValue, aKey);
706     request.onsuccess = function(event) {
707       success = true;
708       if (aCallback)
709         aCallback(success, event);
710     };
711     request.onerror = function(event) {
712       // Errors can be handled here.
713       if (aCallback)
714         aCallback(success, event);
715     };
716   },
717
718   unsetDBCache: function(aKey, aCallback) {
719     if (!mainDB)
720       return;
721     var success = false;
722     var transaction = mainDB.transaction([this.objStore], "readwrite");
723     var request = transaction.objectStore(this.objStore).delete(aKey);
724     request.onsuccess = function(event) {
725       success = true;
726       if (aCallback)
727         aCallback(success, event);
728     };
729     request.onerror = function(event) {
730       // Errors can be handled here.
731       if (aCallback)
732         aCallback(success, event);
733     }
734   }
735 };