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