10e7d465d18c50ddc50320bc1912e0bebec34c67
[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 gGLMapCanvas, gTrackCanvas, gTrackContext, gGeolocation;
6 var gDebug = false;
7
8 var gMinTrackAccuracy = 1000; // meters
9 var gTrackWidth = 2; // pixels
10 var gTrackColor = "#FF0000";
11 var gCurLocSize = 6; // pixels
12 var gCurLocColor = "#A00000";
13
14 var gMapStyles = {
15   // OSM tile usage policy: http://wiki.openstreetmap.org/wiki/Tile_usage_policy
16   // Find some more OSM ones at http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers
17   // and http://wiki.openstreetmap.org/wiki/Tiles or http://wiki.openstreetmap.org/wiki/TMS
18   osm_mapnik:
19     {name: "OpenStreetMap (Mapnik)",
20      url: "https://[a-c].tile.openstreetmap.org/{z}/{x}/{y}.png",
21      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>'},
22   osm_cyclemap:
23     {name: "Cycle Map (OSM)",
24      url: "https://[a-c].tile.thunderforest.com/cycle/{z}/{x}/{y}.png", // "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
25      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>'},
26   osm_transmap:
27     {name: "Transport Map (OSM)",
28      url: "https://[a-c].tile.thunderforest.com/transport/{z}/{x}/{y}.png", // "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png",
29      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>'},
30   osm_germany:
31     {name: "OSM German Style",
32      url: "http://[a-d].tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png", // https is not supported at all
33      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>'},
34 //  oepnvkarte: // XXX: toolserver.org does not support CORS at this time :(
35 //    {name: "ÖPNV-Karte (OSM)",
36 //     url: "http://toolserver.org/~cmarqu/hill/{z}/{x}/{y}.png",
37 //     copyright: 'Map data &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://memomaps.de">MeMoMaps</a> under <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>.'},
38   mapquest_open:
39     {name: "MapQuest OSM",
40      url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png", // https has wrong cert, akamai instead of mqcdn
41      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>.'},
42   mapquest_aerial:
43     {name: "MapQuest Open Aerial",
44      url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg",
45      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.'},
46   osm_hot:
47     {name: "OSM HOT style",
48      url: "http://[a-c].tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", // https has CAcert which doesn't work in browsers
49      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>'},
50 //  hikebike: // XXX: toolserver.org does not support CORS at this time :(
51 //    {name: "Hike and Bike (OSM)",
52 //     url: "http://toolserver.org/tiles/hikebike/{z}/{x}/{y}.png",
53 //     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>'},
54   stamen_toner:
55     {name: "Stamen Toner (B+W)", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
56      url: "http://[a-c].tile.stamen.com/toner/{z}/{x}/{y}.jpg",
57      copyright: 'Map data &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>.'},
58   stamen_terrain:
59     {name: "Stamen Terrain (USA only)", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
60      url: "http://[a-c].tile.stamen.com/terrain/{z}/{x}/{y}.jpg",
61      copyright: 'Map data &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>.'},
62   stamen_watercolor:
63     {name: "Stamen Watercolor (artistic)", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
64      url: "http://[a-c].tile.stamen.com/watercolor/{z}/{x}/{y}.jpg",
65      copyright: 'Map data &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>.'},
66 };
67
68 var gLastMouseX = 0;
69 var gLastMouseY = 0;
70
71 var gLoadingTile;
72
73 var gMapPrefsLoaded = false;
74
75 var gDragging = false;
76 var gDragTouchID, gPinchStartWidth;
77
78 var gGeoWatchID;
79 var gTrack = [];
80 var gLastTrackPoint, gLastDrawnPoint;
81 var gCenterPosition = true;
82
83 var gCurPosMapCache;
84
85 function initMap() {
86   gGeolocation = navigator.geolocation;
87   // Set up canvas context.
88   gGLMapCanvas = document.getElementById("map");
89   try {
90     // Try to grab the standard context. If it fails, fallback to experimental.
91     // We also try to tell it we do not need a depth buffer.
92     gMap.gl = gGLMapCanvas.getContext("webgl", {depth: false}) ||
93               gGLMapCanvas.getContext("experimental-webgl", {depth: false});
94   }
95   catch(e) {}
96   if (!gMap.gl) {
97     // If we don't have a GL context, give up now
98     showGLWarningDialog();
99     gMap.gl = null;
100   }
101   else {
102     // GL context can be lost at any time, handle that.
103     // See http://www.khronos.org/webgl/wiki/HandlingContextLost
104     gGLMapCanvas.addEventListener("webglcontextlost",
105                                   gMap.handleContextLost, false);
106     gGLMapCanvas.addEventListener("webglcontextrestored",
107                                   gMap.handleContextRestored, false);
108   }
109   gTrackCanvas = document.getElementById("track");
110   gTrackContext = gTrackCanvas.getContext("2d");
111   if (!gMap.activeMap)
112     gMap.activeMap = "osm_mapnik";
113
114   //gDebug = true;
115   if (gDebug) {
116     gGeolocation = geofake;
117     var hiddenList = document.getElementsByClassName("debugHide");
118     // last to first - list of elements with that class is changing!
119     for (var i = hiddenList.length - 1; i >= 0; i--) {
120       hiddenList[i].classList.remove("debugHide");
121     }
122   }
123
124   gAction.addEventListener("prefload-done", gMap.initGL, false);
125
126   console.log("map vars set, loading prefs...");
127   loadPrefs();
128 }
129
130 function loadPrefs(aEvent) {
131   if (aEvent && aEvent.type == "prefs-step") {
132     console.log("wait: " + gWaitCounter);
133     if (gWaitCounter == 0) {
134       gAction.removeEventListener(aEvent.type, loadPrefs, false);
135       gMapPrefsLoaded = true;
136       console.log("prefs loaded.");
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("body").addEventListener("keydown", mapEvHandler, false);
152
153       document.addEventListener("visibilitychange", visibilityEvHandler, false);
154
155       console.log("Events added.");
156       document.getElementById("copyright").innerHTML =
157           gMapStyles[gMap.activeMap].copyright;
158
159       console.log("Init loading tile...");
160       gLoadingTile = new Image();
161       gLoadingTile.onload = function() {
162         console.log("Loading tile loaded.");
163         var throwEv = new CustomEvent("prefload-done");
164         gAction.dispatchEvent(throwEv);
165       };
166       console.log("Set loading tile...");
167       gLoadingTile.src = "style/loading.png";
168     }
169   }
170   else {
171     if (aEvent)
172       gAction.removeEventListener(aEvent.type, loadPrefs, false);
173     gAction.addEventListener("prefs-step", loadPrefs, false);
174     gWaitCounter++;
175     gPrefs.get("active_map_style", function(aValue) {
176       if (aValue && gMapStyles[aValue]) {
177         gMap.activeMap = aValue;
178       }
179       gWaitCounter--;
180       var throwEv = new CustomEvent("prefs-step");
181       gAction.dispatchEvent(throwEv);
182     });
183     gWaitCounter++;
184     gPrefs.get("position", function(aValue) {
185       if (aValue && aValue.x && aValue.y && aValue.z) {
186         gMap.pos = aValue;
187       }
188       gWaitCounter--;
189       var throwEv = new CustomEvent("prefs-step");
190       gAction.dispatchEvent(throwEv);
191     });
192     gWaitCounter++;
193     gPrefs.get("center_map", function(aValue) {
194       if (aValue === undefined) {
195         document.getElementById("centerCheckbox").checked = true;
196       }
197       else {
198         document.getElementById("centerCheckbox").checked = aValue;
199       }
200       setCentering(document.getElementById("centerCheckbox"));
201       gWaitCounter--;
202       var throwEv = new CustomEvent("prefs-step");
203       gAction.dispatchEvent(throwEv);
204     });
205     gWaitCounter++;
206     gPrefs.get("tracking_enabled", function(aValue) {
207       if (aValue === undefined) {
208         document.getElementById("trackCheckbox").checked = true;
209       }
210       else {
211         document.getElementById("trackCheckbox").checked = aValue;
212       }
213       gWaitCounter--;
214       var throwEv = new CustomEvent("prefs-step");
215       gAction.dispatchEvent(throwEv);
216     });
217     gWaitCounter++;
218     var trackLoadStarted = false;
219     var redrawBase = 100;
220     gTrackStore.getListStepped(function(aTPoint) {
221       if (aTPoint) {
222         // Add in front and return new length.
223         var tracklen = gTrack.unshift(aTPoint);
224         // Redraw track periodically, larger distance the longer it gets
225         // (but clamped to the first value over a certain limit).
226         // Initial paint will do initial track drawing.
227         if (tracklen % redrawBase == 0) {
228           drawTrack();
229           if (redrawBase < 1000) {
230             redrawBase = tracklen;
231           }
232         }
233       }
234       else {
235         // Last point received.
236         drawTrack();
237       }
238       if (!trackLoadStarted) {
239         // We have the most recent point, if present, rest will load async.
240         trackLoadStarted = true;
241         gWaitCounter--;
242         var throwEv = new CustomEvent("prefs-step");
243         gAction.dispatchEvent(throwEv);
244       }
245     });
246   }
247 }
248
249 var gMap = {
250   gl: null,
251   glShaderProgram: null,
252   glVertexPositionAttr: null,
253   glTextureCoordAttr: null,
254   glResolutionAttr: null,
255   glMapTexture: null,
256   glTextures: {},
257   glTxCleanIntervalID: null,
258   glTexturesPerZoomLevel: 0,
259
260   activeMap: "osm_mapnik",
261   tileSize: 256,
262   maxZoom: 18, // The minimum is 0.
263   zoomFactor: null,
264   pos: {
265     x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
266     y: 23670000.0, // The range is 0-67108864 (2^gMap.maxZoom * gMap.tileSize)
267     z: 5           // This could be fractional if supported being between zoom levels.
268   },
269   baseDim: { // Map width, height and tile size in level 18 pixels.
270     wid: null,
271     ht: null,
272     tsize: null,
273   },
274
275   get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; },
276   get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; },
277
278   getVertShaderSource: function() {
279     return 'attribute vec2 aVertexPosition;\n' +
280     'attribute vec2 aTextureCoord;\n\n' +
281     'uniform vec2 uResolution;\n\n' +
282     'varying highp vec2 vTextureCoord;\n\n' +
283     'void main(void) {\n' +
284     // convert the rectangle from pixels to -1.0 to +1.0 (clipspace) 0.0 to 1.0
285     '  vec2 clipSpace = aVertexPosition * 2.0 / uResolution - 1.0;\n' +
286     '  gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' +
287     '  vTextureCoord = aTextureCoord;\n' +
288     '}'; },
289   getFragShaderSource: function() {
290     return 'varying highp vec2 vTextureCoord;\n\n' +
291     'uniform sampler2D uImage;\n\n' +
292     'void main(void) {\n' +
293     '  gl_FragColor = texture2D(uImage, vTextureCoord);\n' +
294     '}'; },
295
296   initGL: function() {
297     // When called from the event listener, the "this" reference doesn't work, so use the object name.
298     console.log("Initializing WebGL...");
299     if (gMap.gl) {
300       gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
301       gMap.gl.clearColor(0.0, 0.0, 0.0, 0.5);                          // Set clear color to black, fully opaque.
302       gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT|gMap.gl.DEPTH_BUFFER_BIT);  // Clear the color.
303
304       // Create and initialize the shaders.
305       console.log("Create and compile shaders...");
306       var vertShader = gMap.gl.createShader(gMap.gl.VERTEX_SHADER);
307       var fragShader = gMap.gl.createShader(gMap.gl.FRAGMENT_SHADER);
308       gMap.gl.shaderSource(vertShader, gMap.getVertShaderSource());
309       // Compile the shader program.
310       gMap.gl.compileShader(vertShader);
311       // See if it compiled successfully.
312       if (!gMap.gl.getShaderParameter(vertShader, gMap.gl.COMPILE_STATUS)) {
313         console.log("An error occurred compiling the vertex shader: " + gMap.gl.getShaderInfoLog(vertShader));
314         return null;
315       }
316       gMap.gl.shaderSource(fragShader, gMap.getFragShaderSource());
317       // Compile the shader program.
318       gMap.gl.compileShader(fragShader);
319       // See if it compiled successfully.
320       if (!gMap.gl.getShaderParameter(fragShader, gMap.gl.COMPILE_STATUS)) {
321         console.log("An error occurred compiling the fragment shader: " + gMap.gl.getShaderInfoLog(fragShader));
322         return null;
323       }
324
325       console.log("Create and link shader program...");
326       gMap.glShaderProgram = gMap.gl.createProgram();
327       gMap.gl.attachShader(gMap.glShaderProgram, vertShader);
328       gMap.gl.attachShader(gMap.glShaderProgram, fragShader);
329       gMap.gl.linkProgram(gMap.glShaderProgram);
330       // If creating the shader program failed, alert
331       if (!gMap.gl.getProgramParameter(gMap.glShaderProgram, gMap.gl.LINK_STATUS)) {
332         alert("Unable to initialize the shader program.");
333       }
334       gMap.gl.useProgram(gMap.glShaderProgram);
335       // Get locations of the attributes.
336       gMap.glVertexPositionAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aVertexPosition");
337       gMap.glTextureCoordAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aTextureCoord");
338       gMap.glResolutionAttr = gMap.gl.getUniformLocation(gMap.glShaderProgram, "uResolution");
339
340       console.log("Set up vertex buffer...");
341       var tileVerticesBuffer = gMap.gl.createBuffer();
342       gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, tileVerticesBuffer);
343       // The vertices are the coordinates of the corner points of the square.
344       var vertices = [
345         0.0,  0.0,
346         1.0,  0.0,
347         0.0,  1.0,
348         0.0,  1.0,
349         1.0,  0.0,
350         1.0,  1.0,
351       ];
352       gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(vertices), gMap.gl.STATIC_DRAW);
353       gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr);
354       gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0);
355
356       gMap.loadImageToTexture(gLoadingTile, getTileKey("loading", {x: 0, y: 0, z: 0}));
357
358       gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
359
360       // Create a buffer for the position of the rectangle corners.
361       console.log("Set up coord buffer...");
362       var mapVerticesTextureCoordBuffer = gMap.gl.createBuffer();
363       gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer);
364       gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr);
365       gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0);
366
367       // Call texture cleaning every 30 seconds, for now (is 60 better?).
368       gMap.glTxCleanIntervalID = window.setInterval(gMap.cleanTextures, 30 * 1000);
369     }
370
371     if (!gAppInitDone) {
372       // We may be called when context was lost and destroyed,
373       // only send event when we are in app startup
374       // (gAppInitDone is set to true right after we return this event).
375       var throwEv = new CustomEvent("mapinit-done");
376       gAction.dispatchEvent(throwEv);
377     }
378   },
379
380   draw: function() {
381     gMap.assembleGL();
382     drawTrack();
383   },
384
385   assembleGL: function() {
386     if (!gMap.gl) { return; }
387
388     document.getElementById("zoomLevel").textContent = gMap.pos.z;
389     gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
390     gMap.baseDim.wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor;
391     gMap.baseDim.ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor;
392     gMap.baseDim.tsize = gMap.tileSize * gMap.zoomFactor;
393
394     var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
395     var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
396     var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
397     var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
398
399     if (gMapPrefsLoaded && mainDB)
400       gPrefs.set("position", gMap.pos);
401
402     // Go through all the tiles in the map, find out if to draw them and do so.
403     for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
404       for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
405         // Only go to loading step if we haven't loaded the texture.
406         var coords = {x: x, y: y, z: gMap.pos.z};
407         var tileKey = getTileKey(gMap.activeMap, normalizeCoords(coords));
408         if (!gMap.glTextures[tileKey]) {
409           // Initiate loading/drawing of the actual tile.
410           gTileService.get(gMap.activeMap, coords,
411                            function(aImage, aStyle, aCoords, aTileKey) {
412             // Only actually load if this still applies for the current view.
413             if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) {
414               var URL = window.URL;
415               var imgURL = URL.createObjectURL(aImage);
416               var imgObj = new Image();
417               imgObj.onload = function() {
418                 gMap.loadImageToTexture(imgObj, aTileKey);
419                 if (document.hidden != true) { // Only draw if we're actually visible.
420                   window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
421                 }
422                 URL.revokeObjectURL(imgURL);
423               }
424               imgObj.src = imgURL;
425             }
426           });
427         }
428       }
429     }
430     if (document.hidden != true) { // Only draw if we're actually visible.
431       window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
432     }
433   },
434
435   drawGL: function() {
436     var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
437     var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
438     var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
439     var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
440
441     // Go through all the tiles in the map, find out if to draw them and do so.
442     for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
443       for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
444         // Rounding the pixel offsets ensures we position the tiles precisely.
445         var xoff = Math.round((x * gMap.baseDim.tsize - xMin) / gMap.zoomFactor);
446         var yoff = Math.round((y * gMap.baseDim.tsize - yMin) / gMap.zoomFactor);
447         // Draw the tile, first find out the actual texture to use.
448         var norm = normalizeCoords({x: x, y: y, z: gMap.pos.z});
449         var tileKey = getTileKey(gMap.activeMap, norm);
450         if (!gMap.glTextures[tileKey]) {
451           tileKey = getTileKey("loading", {x: 0, y: 0, z: 0});
452         }
453         gMap.drawTileGL(xoff, yoff, tileKey);
454       }
455     }
456   },
457
458   resizeAndDraw: function() {
459     var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
460     var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
461     if (gGLMapCanvas && gTrackCanvas) {
462       gGLMapCanvas.width = viewportWidth;
463       gGLMapCanvas.height = viewportHeight;
464       gTrackCanvas.width = viewportWidth;
465       gTrackCanvas.height = viewportHeight;
466       if (gMap.gl) {
467         // Size viewport to canvas size.
468         gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
469         // Clear the color.
470         gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT);
471         // Make sure the vertex shader get the right resolution.
472         gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
473         // Prepare recalculation of textures to keep for one zoom level.
474         gMap.glTexturesPerZoomLevel = 0;
475       }
476       gMap.draw();
477       showUI();
478     }
479   },
480
481   drawTileGL: function(aLeft, aRight, aTileKey) {
482     gMap.gl.activeTexture(gMap.gl.TEXTURE0);
483     gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
484     // Set uImage to refer to TEXTURE0
485     gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0);
486     var x_start = aLeft;
487     var i_width = gMap.tileSize;
488     var y_start = aRight;
489     var i_height = gMap.tileSize;
490     var textureCoordinates = [
491       x_start, y_start,
492       x_start + i_width, y_start,
493       x_start, y_start + i_height,
494       x_start, y_start + i_height,
495       x_start + i_width, y_start,
496       x_start + i_width, y_start + i_height,
497     ];
498     gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW);
499
500     // There are 6 indices in textureCoordinates.
501     gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
502   },
503
504   loadImageToTexture: function(aImage, aTileKey) {
505     // Create and bind texture.
506     gMap.glTextures[aTileKey] = gMap.gl.createTexture();
507     gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
508     // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two).
509     gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST);
510     gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST);
511     // Upload the image into the texture.
512     gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage);
513   },
514
515   cleanTextures: function() {
516     // Get rid of unneeded textures to save memory.
517     // TODO: Be less aggressive, maybe keep neighboring zoom levels (but x/y coords there are zoom-specific).
518     if (!gMap.glTexturesPerZoomLevel) {
519       // Calculate how many textures we need to keep for one zoom level.
520       // ceil(width/size) gives us the minimum, keep one on either side as well.
521       gMap.glTexturesPerZoomLevel =
522         Math.ceil(gMap.gl.drawingBufferWidth / gMap.tileSize + 2) *
523         Math.ceil(gMap.gl.drawingBufferHeight / gMap.tileSize + 2);
524       console.log("Keeping " + gMap.glTexturesPerZoomLevel + " textures per level");
525     }
526     if (Object.keys(gMap.glTextures).length > gMap.glTexturesPerZoomLevel) {
527       console.log("Cleaning textures... (have " + Object.keys(gMap.glTextures).length + " atm)");
528
529       // Find coordinate ranges for tiles to keep.
530       var tMin = normalizeCoords({x: Math.floor((gMap.pos.x - gMap.baseDim.wid / 2) / gMap.baseDim.tsize) - 1,
531                                   y: Math.floor((gMap.pos.y - gMap.baseDim.ht / 2) / gMap.baseDim.tsize) - 1,
532                                   z: gMap.pos.z});
533       var tMax = normalizeCoords({x: Math.ceil((gMap.pos.x + gMap.baseDim.wid / 2) / gMap.baseDim.tsize) + 1,
534                                   y: Math.ceil((gMap.pos.y + gMap.baseDim.ht / 2) / gMap.baseDim.tsize) + 1,
535                                   z: gMap.pos.z});
536       console.log("In range: " + tMin.x + "," + tMin.y + "," + tMin.z + " - " + tMax.x + "," + tMax.y + "," + tMax.z);
537       for (var tileKey in gMap.glTextures) {
538         var keyMatches = tileKey.match(/([^:]+)::(\d+),(\d+),(\d+)/);
539         if (keyMatches && keyMatches[1] != "loading") {
540           var txData = {
541             style: keyMatches[1],
542             x: keyMatches[2],
543             y: keyMatches[3],
544             z: keyMatches[4],
545           }
546           var delTx = false;
547           if (txData.style != gMap.activeMap) { delTx = true; console.log("Different map style: " + txData.style); }
548           if (!delTx && (txData.z < tMin.z || txData.z > tMax.z)) { delTx = true; console.log("Out-of-range zoom: " + txData.z); }
549           if (tMin.x < tMax.x) {
550             if (!delTx && (txData.x < tMin.x || txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
551           }
552           else {
553             // We are crossing over the 0 coordinate!
554             if (!delTx && (txData.x < tMin.x && txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
555           }
556           if (tMin.y < tMax.y) {
557             if (!delTx && (txData.y < tMin.y || txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
558           }
559           else {
560             // We are crossing over the 0 coordinate!
561             if (!delTx && (txData.y < tMin.y && txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
562           }
563           if (delTx) {
564             // Delete texture from GL and from the array we are holding.
565             gMap.gl.deleteTexture(gMap.glTextures[tileKey]);
566             delete gMap.glTextures[tileKey];
567           }
568         }
569       }
570       console.log("Cleaning complete, " + Object.keys(gMap.glTextures).length + " textures left)");
571     }
572   },
573
574   handleContextLost: function(event) {
575     event.preventDefault();
576     // GL context is gone, let's reset everything that depends on it.
577     clearInterval(gMap.glTxCleanIntervalID);
578     gMap.glTextures = {};
579   },
580
581   handleContextRestored: function(event) {
582     // When GL context is back, init GL again and draw.
583     gMap.initGL();
584     gMap.draw();
585   },
586 }
587
588 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
589 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
590
591 function zoomIn() {
592   if (gMap.pos.z < gMap.maxZoom) {
593     gMap.pos.z++;
594     gMap.draw();
595   }
596 }
597
598 function zoomOut() {
599   if (gMap.pos.z > 0) {
600     gMap.pos.z--;
601     gMap.draw();
602   }
603 }
604
605 function zoomTo(aTargetLevel) {
606   aTargetLevel = parseInt(aTargetLevel);
607   if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) {
608     gMap.pos.z = aTargetLevel;
609     gMap.draw();
610   }
611 }
612
613 function gps2xy(aLatitude, aLongitude) {
614   var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
615   var convLat = aLatitude * Math.PI / 180;
616   var rawY = (1 - Math.log(Math.tan(convLat) +
617                            1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
618   var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
619   return {x: Math.round(rawX),
620           y: Math.round(rawY)};
621 }
622
623 function xy2gps(aX, aY) {
624   var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
625   var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
626   return {latitude: 180 / Math.PI *
627                     Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
628           longitude: aX / maxZoomFactor * 360 - 180};
629 }
630
631 function setMapStyle() {
632   var mapSel = document.getElementById("mapSelector");
633   if (!gWaitCounter && mapSel.selectedIndex >= 0 && gMap.activeMap != mapSel.value) {
634     gMap.activeMap = mapSel.value;
635     gPrefs.set("active_map_style", gMap.activeMap);
636     document.getElementById("copyright").innerHTML =
637         gMapStyles[gMap.activeMap].copyright;
638     showUI();
639     gMap.draw();
640   }
641 }
642
643 // A sane mod function that works for negative numbers.
644 // Returns a % b.
645 function mod(a, b) {
646   return ((a % b) + b) % b;
647 }
648
649 function normalizeCoords(aCoords) {
650   var zoomFactor = Math.pow(2, aCoords.z);
651   return {x: mod(aCoords.x, zoomFactor),
652           y: mod(aCoords.y, zoomFactor),
653           z: aCoords.z};
654 }
655
656 function getTileKey(aStyle, aNormalizedCoords) {
657   return aStyle + "::" +
658          aNormalizedCoords.x + "," +
659          aNormalizedCoords.y + "," +
660          aNormalizedCoords.z;
661 }
662
663 // Returns true if the tile is outside the current view.
664 function isOutsideWindow(t) {
665   var pos = decodeIndex(t);
666
667   var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z);
668   var wid = gMap.width * zoomFactor;
669   var ht = gMap.height * zoomFactor;
670
671   pos.x *= zoomFactor;
672   pos.y *= zoomFactor;
673
674   var sz = gMap.tileSize * zoomFactor;
675   if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 ||
676       pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2)
677     return true;
678   return false;
679 }
680
681 function encodeIndex(x, y, z) {
682   var norm = normalizeCoords({x: x, y: y, z: z});
683   return norm.x + "," + norm.y + "," + norm.z;
684 }
685
686 function decodeIndex(encodedIdx) {
687   var ind = encodedIdx.split(",", 3);
688   return {x: ind[0], y: ind[1], z: ind[2]};
689 }
690
691 function drawTrack() {
692   if (gTrackContext && (document.hidden != true)) { // Only draw if we're actually visible.
693     gLastDrawnPoint = null;
694     gCurPosMapCache = undefined;
695     gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
696     if (gTrack.length) {
697       for (var i = 0; i < gTrack.length; i++) {
698         drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
699                       (i + 1 >= gTrack.length || gTrack[i+1].beginSegment));
700       }
701     }
702   }
703 }
704
705 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
706   var trackpoint = gps2xy(aLatitude, aLongitude);
707   // lastPoint is for optimizing (not actually executing the draw until the last)
708   trackpoint.optimized = (lastPoint === false);
709   var mappos = {x: Math.round((trackpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
710                 y: Math.round((trackpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
711
712   if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
713     gTrackContext.strokeStyle = gTrackColor;
714     gTrackContext.fillStyle = gTrackContext.strokeStyle;
715     gTrackContext.lineWidth = gTrackWidth;
716     gTrackContext.lineCap = "round";
717     gTrackContext.lineJoin = "round";
718   }
719   // This breaks optimiziation, so make sure to reset optimization.
720   if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
721     trackpoint.optimized = false;
722     // Close path if one was open.
723     if (gLastDrawnPoint && gLastDrawnPoint.optimized) {
724       gTrackContext.stroke();
725     }
726   }
727   if (!gLastDrawnPoint || (gLastDrawnPoint == trackpoint) || !gLastDrawnPoint.optimized) {
728     // Start drawing a segment.
729     gTrackContext.beginPath();
730     gTrackContext.arc(mappos.x, mappos.y,
731                       gTrackContext.lineWidth, 0, Math.PI * 2, false);
732     gTrackContext.fill();
733   }
734   else {
735     // Continue drawing segment, close if needed.
736     gTrackContext.lineTo(mappos.x, mappos.y);
737     if (!trackpoint.optimized)
738       gTrackContext.stroke();
739   }
740   gLastDrawnPoint = trackpoint;
741 }
742
743 function drawCurrentLocation(trackPoint) {
744   var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
745   var circleRadius = Math.round(gCurLocSize / 2);
746   var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
747                 y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
748
749   undrawCurrentLocation();
750
751   // Cache overdrawn area.
752   gCurPosMapCache =
753       {point: locpoint,
754        radius: circleRadius,
755        data: gTrackContext.getImageData(mappos.x - circleRadius,
756                                         mappos.y - circleRadius,
757                                         circleRadius * 2, circleRadius * 2)};
758
759   gTrackContext.strokeStyle = gCurLocColor;
760   gTrackContext.fillStyle = gTrackContext.strokeStyle;
761   gTrackContext.beginPath();
762   gTrackContext.arc(mappos.x, mappos.y,
763                     circleRadius, 0, Math.PI * 2, false);
764   gTrackContext.fill();
765 }
766
767 function undrawCurrentLocation() {
768   if (gCurPosMapCache) {
769     var oldpoint = gCurPosMapCache.point;
770     var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
771                  y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
772     gTrackContext.putImageData(gCurPosMapCache.data,
773                                oldmp.x - gCurPosMapCache.radius,
774                                oldmp.y - gCurPosMapCache.radius);
775     gCurPosMapCache = undefined;
776   }
777 }
778
779 function calcTrackDuration() {
780   // Get the duration of the track in s.
781   var tDuration = 0;
782   if (gTrack.length > 1) {
783     for (var i = 1; i < gTrack.length; i++) {
784       if (!gTrack[i].beginSegment) {
785         tDuration += (gTrack[i].time - gTrack[i-1].time);
786       }
787     }
788   }
789   return Math.round(tDuration / 1000); // The timestamps are in ms but we return seconds.
790 }
791
792 function calcTrackLength() {
793   // Get the length of the track in km.
794   var tLength = 0;
795   if (gTrack.length > 1) {
796     for (var i = 1; i < gTrack.length; i++) {
797       if (!gTrack[i].beginSegment) {
798         tLength += getPointDistance(gTrack[i-1].coords, gTrack[i].coords);
799       }
800     }
801   }
802   return tLength;
803 }
804
805 function getPointDistance(aGPSPoint1, aGPSPoint2) {
806   // Get the distance in km between the two given GPS points.
807   // See http://stackoverflow.com/questions/365826/calculate-distance-between-2-gps-coordinates
808   // Earth is almost exactly a sphere and we calculate small distances on the surface, so we can do spherical great-circle math.
809   // Also see http://en.wikipedia.org/wiki/Great-circle_distance
810   var R = 6371; // km
811   var dLat = deg2rad(aGPSPoint2.latitude - aGPSPoint1.latitude);
812   var dLon = deg2rad(aGPSPoint2.longitude - aGPSPoint1.longitude);
813   var lat1 = deg2rad(aGPSPoint1.latitude);
814   var lat2 = deg2rad(aGPSPoint2.latitude);
815
816   var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
817           Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
818   var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
819   return R * c;
820 }
821
822 function deg2rad(aDegreeValue) {
823   // Convert an angle in degrees to radiants.
824   return aDegreeValue * (Math.PI / 180);
825 }
826
827 var mapEvHandler = {
828   handleEvent: function(aEvent) {
829     var touchEvent = aEvent.type.indexOf('touch') != -1;
830
831     if (touchEvent) {
832       aEvent.stopPropagation();
833     }
834
835     // Bail out if the event is happening on an input.
836     if (aEvent.target.tagName.toLowerCase() == "input")
837       return;
838
839     // Bail out on unwanted map moves, but not zoom or keyboard events.
840     if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
841       // Bail out if this is neither a touch nor left-click.
842       if (!touchEvent && aEvent.button != 0)
843         return;
844
845       // Bail out if the started touch can't be found.
846       if (touchEvent && gDragging &&
847           !aEvent.changedTouches.identifiedTouch(gDragTouchID))
848         return;
849     }
850
851     var coordObj = touchEvent ?
852                    aEvent.changedTouches.identifiedTouch(gDragTouchID) :
853                    aEvent;
854
855     switch (aEvent.type) {
856       case "mousedown":
857       case "touchstart":
858         if (touchEvent) {
859           if (aEvent.targetTouches.length == 2) {
860             gPinchStartWidth = Math.sqrt(
861                 Math.pow(aEvent.targetTouches.item(1).clientX -
862                          aEvent.targetTouches.item(0).clientX, 2) +
863                 Math.pow(aEvent.targetTouches.item(1).clientY -
864                          aEvent.targetTouches.item(0).clientY, 2)
865             );
866           }
867           gDragTouchID = aEvent.changedTouches.item(0).identifier;
868           coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
869         }
870         var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
871         var y = coordObj.clientY - gGLMapCanvas.offsetTop;
872
873         if (touchEvent || aEvent.button === 0) {
874           gDragging = true;
875         }
876         gLastMouseX = x;
877         gLastMouseY = y;
878         showUI();
879         break;
880       case "mousemove":
881       case "touchmove":
882         if (touchEvent && aEvent.targetTouches.length == 2) {
883           curPinchStartWidth = Math.sqrt(
884               Math.pow(aEvent.targetTouches.item(1).clientX -
885                        aEvent.targetTouches.item(0).clientX, 2) +
886               Math.pow(aEvent.targetTouches.item(1).clientY -
887                        aEvent.targetTouches.item(0).clientY, 2)
888           );
889           if (!gPinchStartWidth)
890             gPinchStartWidth = curPinchStartWidth;
891
892           if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
893               gPinchStartWidth / curPinchStartWidth < 0.6) {
894             var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
895             if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
896               // Calculate new center of the map - preserve middle of pinch.
897               // This means that pixel distance between old center and middle
898               // must equal pixel distance of new center and middle.
899               var x = (aEvent.targetTouches.item(1).clientX +
900                        aEvent.targetTouches.item(0).clientX) / 2 -
901                       gGLMapCanvas.offsetLeft;
902               var y = (aEvent.targetTouches.item(1).clientY +
903                        aEvent.targetTouches.item(0).clientY) / 2 -
904                       gGLMapCanvas.offsetTop;
905
906               // Zoom factor after this action.
907               var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
908               gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
909               gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
910
911               if (gPinchStartWidth < curPinchStartWidth)
912                 zoomIn();
913               else
914                 zoomOut();
915
916               // Reset pinch start width and start another pinch gesture.
917               gPinchStartWidth = null;
918             }
919           }
920           // If we are in a pinch, do not drag.
921           break;
922         }
923         var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
924         var y = coordObj.clientY - gGLMapCanvas.offsetTop;
925         if (gDragging === true) {
926           var dX = x - gLastMouseX;
927           var dY = y - gLastMouseY;
928           gMap.pos.x -= dX * gMap.zoomFactor;
929           gMap.pos.y -= dY * gMap.zoomFactor;
930           gMap.draw();
931           showUI();
932         }
933         gLastMouseX = x;
934         gLastMouseY = y;
935         break;
936       case "mouseup":
937       case "touchend":
938         gPinchStartWidth = null;
939         gDragging = false;
940         showUI();
941         break;
942       case "mouseout":
943       case "touchcancel":
944       case "touchleave":
945         //gDragging = false;
946         break;
947       case "wheel":
948         // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
949         // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
950
951         // Only accept (non-null) deltaY values
952         if (!aEvent.deltaY)
953           break;
954
955         // Debug output: "coordinates" of the point the mouse was over.
956         /*
957         var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor,
958                        y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor};
959         var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
960         var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
961         console.log(ptCoord.x + "/" + ptCoord.y + " - " +
962                     gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
963                     pt2Coord.x + "/" + pt2Coord.y);
964         */
965
966         var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1);
967         if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
968           // Calculate new center of the map - same point stays under the mouse.
969           // This means that the pixel distance between the old center and point
970           // must equal the pixel distance of the new center and that point.
971           var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
972           var y = coordObj.clientY - gGLMapCanvas.offsetTop;
973
974           // Zoom factor after this action.
975           var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
976           gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
977           gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
978
979           if (aEvent.deltaY < 0)
980             zoomIn();
981           else
982             zoomOut();
983         }
984         break;
985       case "keydown":
986         // Allow keyboard control to move and zoom the map.
987         // Should use aEvent.key instead of aEvent.which but needs bug 680830.
988         // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
989         var dX = 0;
990         var dY = 0;
991         switch (aEvent.which) {
992           case 39: // right
993             dX = -gMap.tileSize / 2;
994           break;
995           case 37: // left
996             dX = gMap.tileSize / 2;
997           break;
998           case 38: // up
999             dY = gMap.tileSize / 2;
1000           break;
1001           case 40: // down
1002             dY = -gMap.tileSize / 2;
1003           break;
1004           case 87: // w
1005           case 107: // + (numpad)
1006           case 171: // + (normal key)
1007             zoomIn();
1008           break;
1009           case 83: // s
1010           case 109: // - (numpad)
1011           case 173: // - (normal key)
1012             zoomOut();
1013           break;
1014           case 48: // 0
1015           case 49: // 1
1016           case 50: // 2
1017           case 51: // 3
1018           case 52: // 4
1019           case 53: // 5
1020           case 54: // 6
1021           case 55: // 7
1022           case 56: // 8
1023             zoomTo(aEvent.which - 38);
1024           break;
1025           case 57: // 9
1026             zoomTo(9);
1027           break;
1028           case 96: // 0 (numpad)
1029           case 97: // 1 (numpad)
1030           case 98: // 2 (numpad)
1031           case 99: // 3 (numpad)
1032           case 100: // 4 (numpad)
1033           case 101: // 5 (numpad)
1034           case 102: // 6 (numpad)
1035           case 103: // 7 (numpad)
1036           case 104: // 8 (numpad)
1037             zoomTo(aEvent.which - 86);
1038           break;
1039           case 105: // 9 (numpad)
1040             zoomTo(9);
1041           break;
1042           default: // not supported
1043             console.log("key not supported: " + aEvent.which);
1044           break;
1045         }
1046
1047         // Move if needed.
1048         if (dX || dY) {
1049           gMap.pos.x -= dX * gMap.zoomFactor;
1050           gMap.pos.y -= dY * gMap.zoomFactor;
1051           gMap.draw();
1052         }
1053         break;
1054     }
1055   }
1056 };
1057
1058 function visibilityEvHandler() {
1059   // Immediately draw if we just got visible.
1060   if (document.hidden != true) {
1061     gMap.draw();
1062   }
1063   // No need to handle the event where we become invisible as we care only draw
1064   // when we are visible anyhow.
1065 }
1066
1067 var geofake = {
1068   tracking: false,
1069   lastPos: {x: undefined, y: undefined},
1070   watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
1071     this.tracking = true;
1072     var watchCall = function() {
1073       // calc new position in lat/lon degrees
1074       // 90° on Earth surface are ~10,000 km at the equator,
1075       // so try moving at most 10m at a time
1076       if (geofake.lastPos.x)
1077         geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
1078       else
1079         geofake.lastPos.x = 48.208174
1080       if (geofake.lastPos.y)
1081         geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
1082       else
1083         geofake.lastPos.y = 16.373819
1084       aSuccessCallback({timestamp: Date.now(),
1085                         coords: {latitude: geofake.lastPos.x,
1086                                  longitude: geofake.lastPos.y,
1087                                  accuracy: 20}});
1088       if (geofake.tracking)
1089         setTimeout(watchCall, 1000);
1090     };
1091     setTimeout(watchCall, 1000);
1092     return "foo";
1093   },
1094   clearWatch: function(aID) {
1095     this.tracking = false;
1096   }
1097 }
1098
1099 function setCentering(aCheckbox) {
1100   if (gMapPrefsLoaded && mainDB)
1101     gPrefs.set("center_map", aCheckbox.checked);
1102   gCenterPosition = aCheckbox.checked;
1103 }
1104
1105 function setTracking(aCheckbox) {
1106   if (gMapPrefsLoaded && mainDB)
1107     gPrefs.set("tracking_enabled", aCheckbox.checked);
1108   if (aCheckbox.checked)
1109     startTracking();
1110   else
1111     endTracking();
1112 }
1113
1114 function startTracking() {
1115   if (gGeolocation) {
1116     gActionLabel.textContent = "Establishing Position";
1117     gAction.style.display = "block";
1118     gGeoWatchID = gGeolocation.watchPosition(
1119       function(position) {
1120         if (gActionLabel.textContent) {
1121           gActionLabel.textContent = "";
1122           gAction.style.display = "none";
1123         }
1124         // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
1125         var tPoint = {time: position.timestamp,
1126                       coords: {latitude: position.coords.latitude,
1127                                longitude: position.coords.longitude,
1128                                altitude: position.coords.altitude,
1129                                accuracy: position.coords.accuracy,
1130                                altitudeAccuracy: position.coords.altitudeAccuracy,
1131                                heading: position.coords.heading,
1132                                speed: position.coords.speed},
1133                       beginSegment: !gLastTrackPoint};
1134         // Only add point to track is accuracy is good enough.
1135         if (tPoint.coords.accuracy < gMinTrackAccuracy) {
1136           gLastTrackPoint = tPoint;
1137           gTrack.push(tPoint);
1138           try { gTrackStore.push(tPoint); } catch(e) {}
1139           var redrawn = false;
1140           if (gCenterPosition) {
1141             var posCoord = gps2xy(position.coords.latitude,
1142                                   position.coords.longitude);
1143             if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 ||
1144                 Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) {
1145               gMap.pos.x = posCoord.x;
1146               gMap.pos.y = posCoord.y;
1147               gMap.draw(); // This draws the current point as well.
1148               redrawn = true;
1149             }
1150           }
1151           if (!redrawn)
1152             undrawCurrentLocation();
1153             drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
1154         }
1155         drawCurrentLocation(tPoint);
1156       },
1157       function(error) {
1158         // Ignore erros for the moment, but this is good for debugging.
1159         // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
1160         if (gDebug)
1161           console.log(error.message);
1162       },
1163       {enableHighAccuracy: true}
1164     );
1165   }
1166 }
1167
1168 function endTracking() {
1169   if (gActionLabel.textContent) {
1170     gActionLabel.textContent = "";
1171     gAction.style.display = "none";
1172   }
1173   if (gGeoWatchID) {
1174     gGeolocation.clearWatch(gGeoWatchID);
1175   }
1176 }
1177
1178 function clearTrack() {
1179   gTrack = [];
1180   gTrackStore.clear();
1181   drawTrack();
1182 }
1183
1184 var gTileService = {
1185   objStore: "tilecache",
1186
1187   ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
1188
1189   get: function(aStyle, aCoords, aCallback) {
1190     var norm = normalizeCoords(aCoords);
1191     var dbkey = getTileKey(aStyle, norm);
1192     this.getDBCache(dbkey, function(aResult, aEvent) {
1193       if (aResult) {
1194         // We did get a cached object.
1195         aCallback(aResult.image, aStyle, aCoords, dbkey);
1196         // Look at the timestamp and return if it's not too old.
1197         if (aResult.timestamp + gTileService.ageLimit > Date.now())
1198           return;
1199         // Reload cached tile otherwise.
1200         var oldDate = new Date(aResult.timestamp);
1201         console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
1202       }
1203       // Retrieve image from the web and store it in the cache.
1204       var XHR = new XMLHttpRequest();
1205       XHR.open("GET",
1206                 gMapStyles[aStyle].url
1207                   .replace("{x}", norm.x)
1208                   .replace("{y}", norm.y)
1209                   .replace("{z}", norm.z)
1210                   .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 3)))
1211                   .replace("[a-d]", String.fromCharCode(97 + Math.floor(Math.random() * 4)))
1212                   .replace("[1-4]", 1 + Math.floor(Math.random() * 4)),
1213                 true);
1214       XHR.responseType = "blob";
1215       XHR.addEventListener("load", function () {
1216         if (XHR.status === 200) {
1217           var blob = XHR.response;
1218           aCallback(blob, aStyle, aCoords, dbkey);
1219           gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
1220         }
1221       }, false);
1222       XHR.send();
1223     });
1224   },
1225
1226   getDBCache: function(aKey, aCallback) {
1227     if (!mainDB)
1228       return;
1229     var transaction = mainDB.transaction([this.objStore]);
1230     var request = transaction.objectStore(this.objStore).get(aKey);
1231     request.onsuccess = function(event) {
1232       aCallback(request.result, event);
1233     };
1234     request.onerror = function(event) {
1235       // Errors can be handled here.
1236       aCallback(undefined, event);
1237     };
1238   },
1239
1240   setDBCache: function(aKey, aValue, aCallback) {
1241     if (!mainDB)
1242       return;
1243     var success = false;
1244     var transaction = mainDB.transaction([this.objStore], "readwrite");
1245     var objStore = transaction.objectStore(this.objStore);
1246     var request = objStore.put(aValue, aKey);
1247     request.onsuccess = function(event) {
1248       success = true;
1249       if (aCallback)
1250         aCallback(success, event);
1251     };
1252     request.onerror = function(event) {
1253       // Errors can be handled here.
1254       if (aCallback)
1255         aCallback(success, event);
1256     };
1257   },
1258
1259   unsetDBCache: function(aKey, aCallback) {
1260     if (!mainDB)
1261       return;
1262     var success = false;
1263     var transaction = mainDB.transaction([this.objStore], "readwrite");
1264     var request = transaction.objectStore(this.objStore).delete(aKey);
1265     request.onsuccess = function(event) {
1266       success = true;
1267       if (aCallback)
1268         aCallback(success, event);
1269     };
1270     request.onerror = function(event) {
1271       // Errors can be handled here.
1272       if (aCallback)
1273         aCallback(success, event);
1274     }
1275   },
1276
1277   clearDB: function(aCallback) {
1278     if (!mainDB)
1279       return;
1280     var success = false;
1281     var transaction = mainDB.transaction([this.objStore], "readwrite");
1282     var request = transaction.objectStore(this.objStore).clear();
1283     request.onsuccess = function(event) {
1284       success = true;
1285       if (aCallback)
1286         aCallback(success, event);
1287     };
1288     request.onerror = function(event) {
1289       // Errors can be handled here.
1290       if (aCallback)
1291         aCallback(success, event);
1292     }
1293   }
1294 };