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