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