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