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