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