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/. */
5 var gGLMapCanvas, gTrackCanvas, gTrackContext, gGeolocation;
8 var gMinTrackAccuracy = 1000; // meters
9 var gTrackWidth = 2; // pixels
10 var gTrackColor = "#FF0000";
11 var gCurLocSize = 6; // pixels
12 var gCurLocColor = "#A00000";
15 // OSM tile usage policy: http://wiki.openstreetmap.org/wiki/Tile_usage_policy
16 // Find some more OSM ones at http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers
17 // and http://wiki.openstreetmap.org/wiki/Tiles or http://wiki.openstreetmap.org/wiki/TMS
19 {name: "OpenStreetMap (Mapnik)",
20 url: "https://[a-c].tile.openstreetmap.org/{z}/{x}/{y}.png",
21 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
23 {name: "Cycle Map (OSM)",
24 url: "https://[a-c].tile.thunderforest.com/cycle/{z}/{x}/{y}.png", // "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
25 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
27 {name: "Transport Map (OSM)",
28 url: "https://[a-c].tile.thunderforest.com/transport/{z}/{x}/{y}.png", // "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png",
29 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
31 {name: "OSM German Style",
32 url: "http://[a-d].tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png", // https is not supported at all
33 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
34 // oepnvkarte: // XXX: toolserver.org does not support CORS at this time :(
35 // {name: "ÖPNV-Karte (OSM)",
36 // url: "http://toolserver.org/~cmarqu/hill/{z}/{x}/{y}.png",
37 // copyright: 'Map data © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://memomaps.de">MeMoMaps</a> under <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>.'},
39 {name: "MapQuest OSM",
40 url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png", // https has wrong cert, akamai instead of mqcdn
41 copyright: 'Map data © <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>.'},
43 {name: "MapQuest Open Aerial",
44 url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg",
45 copyright: 'Tiles Courtesy of <a href="http://www.mapquest.com/">MapQuest</a>, portions Courtesy NASA/JPL-Caltech and U.S. Depart. of Agriculture, Farm Service Agency.'},
47 {name: "OSM HOT style",
48 url: "http://[a-c].tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", // https has CAcert which doesn't work in browsers
49 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
50 // hikebike: // XXX: toolserver.org does not support CORS at this time :(
51 // {name: "Hike and Bike (OSM)",
52 // url: "http://toolserver.org/tiles/hikebike/{z}/{x}/{y}.png",
53 // copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
55 {name: "Stamen Toner (B+W)", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
56 url: "http://[a-c].tile.stamen.com/toner/{z}/{x}/{y}.jpg",
57 copyright: 'Map data © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>.'},
59 {name: "Stamen Terrain (USA only)", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
60 url: "http://[a-c].tile.stamen.com/terrain/{z}/{x}/{y}.jpg",
61 copyright: 'Map data © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>.'},
63 {name: "Stamen Watercolor (artistic)", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
64 url: "http://[a-c].tile.stamen.com/watercolor/{z}/{x}/{y}.jpg",
65 copyright: 'Map data © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>.'},
73 var gMapPrefsLoaded = false;
75 var gDragging = false;
76 var gDragTouchID, gPinchStartWidth;
80 var gLastTrackPoint, gLastDrawnPoint;
81 var gCenterPosition = true;
86 gGeolocation = navigator.geolocation;
87 // Set up canvas context.
88 gGLMapCanvas = document.getElementById("map");
90 // Try to grab the standard context. If it fails, fallback to experimental.
91 // We also try to tell it we do not need a depth buffer.
92 gMap.gl = gGLMapCanvas.getContext("webgl", {depth: false}) ||
93 gGLMapCanvas.getContext("experimental-webgl", {depth: false});
97 // If we don't have a GL context, give up now
98 showGLWarningDialog();
102 // GL context can be lost at any time, handle that.
103 // See http://www.khronos.org/webgl/wiki/HandlingContextLost
104 gGLMapCanvas.addEventListener("webglcontextlost",
105 gMap.handleContextLost, false);
106 gGLMapCanvas.addEventListener("webglcontextrestored",
107 gMap.handleContextRestored, false);
109 gTrackCanvas = document.getElementById("track");
110 gTrackContext = gTrackCanvas.getContext("2d");
114 gGeolocation = geofake;
115 var hiddenList = document.getElementsByClassName("debugHide");
116 // last to first - list of elements with that class is changing!
117 for (var i = hiddenList.length - 1; i >= 0; i--) {
118 hiddenList[i].classList.remove("debugHide");
122 gAction.addEventListener("prefload-done", gMap.initGL, false);
124 console.log("map vars set, loading prefs...");
128 function loadPrefs(aEvent) {
129 if (aEvent && aEvent.type == "prefs-step") {
130 console.log("wait: " + gWaitCounter);
131 if (gWaitCounter == 0) {
132 gAction.removeEventListener(aEvent.type, loadPrefs, false);
133 gMapPrefsLoaded = true;
134 console.log("prefs loaded.");
136 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
137 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
138 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
139 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
141 gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
142 gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
143 gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
144 gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
145 gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
147 gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
149 document.getElementById("body").addEventListener("keydown", mapEvHandler, false);
151 document.addEventListener("visibilitychange", visibilityEvHandler, false);
153 console.log("Events added.");
155 console.log("Init loading tile...");
156 gLoadingTile = new Image();
157 gLoadingTile.onload = function() {
158 console.log("Loading tile loaded.");
159 var throwEv = new CustomEvent("prefload-done");
160 gAction.dispatchEvent(throwEv);
162 console.log("Set loading tile...");
163 gLoadingTile.src = "style/loading.png";
168 gAction.removeEventListener(aEvent.type, loadPrefs, false);
169 gAction.addEventListener("prefs-step", loadPrefs, false);
171 gPrefs.get("active_map_style", function(aValue) {
172 if (aValue && gMapStyles[aValue]) {
173 gMap.activeMap = aValue;
176 gMap.activeMap = "osm_mapnik";
178 document.getElementById("mapSelector").value = gMap.activeMap;
179 document.getElementById("copyright").innerHTML =
180 gMapStyles[gMap.activeMap].copyright;
182 var throwEv = new CustomEvent("prefs-step");
183 gAction.dispatchEvent(throwEv);
186 gPrefs.get("position", function(aValue) {
187 if (aValue && aValue.x && aValue.y && aValue.z) {
191 var throwEv = new CustomEvent("prefs-step");
192 gAction.dispatchEvent(throwEv);
195 gPrefs.get("center_map", function(aValue) {
196 if (aValue === undefined) {
197 document.getElementById("centerCheckbox").checked = true;
200 document.getElementById("centerCheckbox").checked = aValue;
202 setCentering(document.getElementById("centerCheckbox"));
204 var throwEv = new CustomEvent("prefs-step");
205 gAction.dispatchEvent(throwEv);
208 gPrefs.get("tracking_enabled", function(aValue) {
209 if (aValue === undefined) {
210 document.getElementById("trackCheckbox").checked = true;
213 document.getElementById("trackCheckbox").checked = aValue;
216 var throwEv = new CustomEvent("prefs-step");
217 gAction.dispatchEvent(throwEv);
220 var trackLoadStarted = false;
221 var redrawBase = 100;
222 gTrackStore.getListStepped(function(aTPoint) {
224 // Add in front and return new length.
225 var tracklen = gTrack.unshift(aTPoint);
226 // Redraw track periodically, larger distance the longer it gets
227 // (but clamped to the first value over a certain limit).
228 // Initial paint will do initial track drawing.
229 if (tracklen % redrawBase == 0) {
231 if (redrawBase < 1000) {
232 redrawBase = tracklen;
237 // Last point received.
240 if (!trackLoadStarted) {
241 // We have the most recent point, if present, rest will load async.
242 trackLoadStarted = true;
244 var throwEv = new CustomEvent("prefs-step");
245 gAction.dispatchEvent(throwEv);
253 glShaderProgram: null,
254 glVertexPositionAttr: null,
255 glTextureCoordAttr: null,
256 glResolutionAttr: null,
259 glTxCleanIntervalID: null,
260 glTexturesPerZoomLevel: 0,
262 activeMap: "osm_mapnik",
264 maxZoom: 18, // The minimum is 0.
267 x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
268 y: 23670000.0, // The range is 0-67108864 (2^gMap.maxZoom * gMap.tileSize)
269 z: 5 // This could be fractional if supported being between zoom levels.
271 baseDim: { // Map width, height and tile size in level 18 pixels.
277 get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; },
278 get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; },
280 getVertShaderSource: function() {
281 return 'attribute vec2 aVertexPosition;\n' +
282 'attribute vec2 aTextureCoord;\n\n' +
283 'uniform vec2 uResolution;\n\n' +
284 'varying highp vec2 vTextureCoord;\n\n' +
285 'void main(void) {\n' +
286 // convert the rectangle from pixels to -1.0 to +1.0 (clipspace) 0.0 to 1.0
287 ' vec2 clipSpace = aVertexPosition * 2.0 / uResolution - 1.0;\n' +
288 ' gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' +
289 ' vTextureCoord = aTextureCoord;\n' +
291 getFragShaderSource: function() {
292 return 'varying highp vec2 vTextureCoord;\n\n' +
293 'uniform sampler2D uImage;\n\n' +
294 'void main(void) {\n' +
295 ' gl_FragColor = texture2D(uImage, vTextureCoord);\n' +
299 // When called from the event listener, the "this" reference doesn't work, so use the object name.
300 console.log("Initializing WebGL...");
302 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
303 gMap.gl.clearColor(0.0, 0.0, 0.0, 0.5); // Set clear color to black, fully opaque.
304 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT|gMap.gl.DEPTH_BUFFER_BIT); // Clear the color.
306 // Create and initialize the shaders.
307 console.log("Create and compile shaders...");
308 var vertShader = gMap.gl.createShader(gMap.gl.VERTEX_SHADER);
309 var fragShader = gMap.gl.createShader(gMap.gl.FRAGMENT_SHADER);
310 gMap.gl.shaderSource(vertShader, gMap.getVertShaderSource());
311 // Compile the shader program.
312 gMap.gl.compileShader(vertShader);
313 // See if it compiled successfully.
314 if (!gMap.gl.getShaderParameter(vertShader, gMap.gl.COMPILE_STATUS)) {
315 console.log("An error occurred compiling the vertex shader: " + gMap.gl.getShaderInfoLog(vertShader));
318 gMap.gl.shaderSource(fragShader, gMap.getFragShaderSource());
319 // Compile the shader program.
320 gMap.gl.compileShader(fragShader);
321 // See if it compiled successfully.
322 if (!gMap.gl.getShaderParameter(fragShader, gMap.gl.COMPILE_STATUS)) {
323 console.log("An error occurred compiling the fragment shader: " + gMap.gl.getShaderInfoLog(fragShader));
327 console.log("Create and link shader program...");
328 gMap.glShaderProgram = gMap.gl.createProgram();
329 gMap.gl.attachShader(gMap.glShaderProgram, vertShader);
330 gMap.gl.attachShader(gMap.glShaderProgram, fragShader);
331 gMap.gl.linkProgram(gMap.glShaderProgram);
332 // If creating the shader program failed, alert
333 if (!gMap.gl.getProgramParameter(gMap.glShaderProgram, gMap.gl.LINK_STATUS)) {
334 alert("Unable to initialize the shader program.");
336 gMap.gl.useProgram(gMap.glShaderProgram);
337 // Get locations of the attributes.
338 gMap.glVertexPositionAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aVertexPosition");
339 gMap.glTextureCoordAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aTextureCoord");
340 gMap.glResolutionAttr = gMap.gl.getUniformLocation(gMap.glShaderProgram, "uResolution");
342 console.log("Set up vertex buffer...");
343 var tileVerticesBuffer = gMap.gl.createBuffer();
344 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, tileVerticesBuffer);
345 // The vertices are the coordinates of the corner points of the square.
354 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(vertices), gMap.gl.STATIC_DRAW);
355 gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr);
356 gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0);
358 gMap.loadImageToTexture(gLoadingTile, getTileKey("loading", {x: 0, y: 0, z: 0}));
360 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
362 // Create a buffer for the position of the rectangle corners.
363 console.log("Set up coord buffer...");
364 var mapVerticesTextureCoordBuffer = gMap.gl.createBuffer();
365 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer);
366 gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr);
367 gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0);
369 // Call texture cleaning every 30 seconds, for now (is 60 better?).
370 gMap.glTxCleanIntervalID = window.setInterval(gMap.cleanTextures, 30 * 1000);
374 // We may be called when context was lost and destroyed,
375 // only send event when we are in app startup
376 // (gAppInitDone is set to true right after we return this event).
377 var throwEv = new CustomEvent("mapinit-done");
378 gAction.dispatchEvent(throwEv);
387 assembleGL: function() {
388 if (!gMap.gl) { return; }
390 document.getElementById("zoomLevel").textContent = gMap.pos.z;
391 gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
392 gMap.baseDim.wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor;
393 gMap.baseDim.ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor;
394 gMap.baseDim.tsize = gMap.tileSize * gMap.zoomFactor;
396 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
397 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
398 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
399 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
401 if (gMapPrefsLoaded && mainDB)
402 gPrefs.set("position", gMap.pos);
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 // Only go to loading step if we haven't loaded the texture.
408 var coords = {x: x, y: y, z: gMap.pos.z};
409 var tileKey = getTileKey(gMap.activeMap, normalizeCoords(coords));
410 if (!gMap.glTextures[tileKey]) {
411 // Initiate loading/drawing of the actual tile.
412 gTileService.get(gMap.activeMap, coords,
413 function(aImage, aStyle, aCoords, aTileKey) {
414 // Only actually load if this still applies for the current view.
415 if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) {
416 var URL = window.URL;
417 var imgURL = URL.createObjectURL(aImage);
418 var imgObj = new Image();
419 imgObj.onload = function() {
420 gMap.loadImageToTexture(imgObj, aTileKey);
421 if (document.hidden != true) { // Only draw if we're actually visible.
422 window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
424 URL.revokeObjectURL(imgURL);
432 if (document.hidden != true) { // Only draw if we're actually visible.
433 window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
438 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
439 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
440 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
441 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
443 // Go through all the tiles in the map, find out if to draw them and do so.
444 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
445 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
446 // Rounding the pixel offsets ensures we position the tiles precisely.
447 var xoff = Math.round((x * gMap.baseDim.tsize - xMin) / gMap.zoomFactor);
448 var yoff = Math.round((y * gMap.baseDim.tsize - yMin) / gMap.zoomFactor);
449 // Draw the tile, first find out the actual texture to use.
450 var norm = normalizeCoords({x: x, y: y, z: gMap.pos.z});
451 var tileKey = getTileKey(gMap.activeMap, norm);
452 if (!gMap.glTextures[tileKey]) {
453 tileKey = getTileKey("loading", {x: 0, y: 0, z: 0});
455 gMap.drawTileGL(xoff, yoff, tileKey);
460 resizeAndDraw: function() {
461 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
462 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
463 if (gGLMapCanvas && gTrackCanvas) {
464 gGLMapCanvas.width = viewportWidth;
465 gGLMapCanvas.height = viewportHeight;
466 gTrackCanvas.width = viewportWidth;
467 gTrackCanvas.height = viewportHeight;
469 // Size viewport to canvas size.
470 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
472 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT);
473 // Make sure the vertex shader get the right resolution.
474 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
475 // Prepare recalculation of textures to keep for one zoom level.
476 gMap.glTexturesPerZoomLevel = 0;
483 drawTileGL: function(aLeft, aRight, aTileKey) {
484 gMap.gl.activeTexture(gMap.gl.TEXTURE0);
485 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
486 // Set uImage to refer to TEXTURE0
487 gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0);
489 var i_width = gMap.tileSize;
490 var y_start = aRight;
491 var i_height = gMap.tileSize;
492 var textureCoordinates = [
494 x_start + i_width, y_start,
495 x_start, y_start + i_height,
496 x_start, y_start + i_height,
497 x_start + i_width, y_start,
498 x_start + i_width, y_start + i_height,
500 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW);
502 // There are 6 indices in textureCoordinates.
503 gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
506 loadImageToTexture: function(aImage, aTileKey) {
507 // Create and bind texture.
508 gMap.glTextures[aTileKey] = gMap.gl.createTexture();
509 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
510 // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two).
511 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST);
512 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST);
513 // Upload the image into the texture.
514 gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage);
517 cleanTextures: function() {
518 // Get rid of unneeded textures to save memory.
519 // TODO: Be less aggressive, maybe keep neighboring zoom levels (but x/y coords there are zoom-specific).
520 if (!gMap.glTexturesPerZoomLevel) {
521 // Calculate how many textures we need to keep for one zoom level.
522 // ceil(width/size) gives us the minimum, keep one on either side as well.
523 gMap.glTexturesPerZoomLevel =
524 Math.ceil(gMap.gl.drawingBufferWidth / gMap.tileSize + 2) *
525 Math.ceil(gMap.gl.drawingBufferHeight / gMap.tileSize + 2);
526 console.log("Keeping " + gMap.glTexturesPerZoomLevel + " textures per level");
528 if (Object.keys(gMap.glTextures).length > gMap.glTexturesPerZoomLevel) {
529 console.log("Cleaning textures... (have " + Object.keys(gMap.glTextures).length + " atm)");
531 // Find coordinate ranges for tiles to keep.
532 var tMin = normalizeCoords({x: Math.floor((gMap.pos.x - gMap.baseDim.wid / 2) / gMap.baseDim.tsize) - 1,
533 y: Math.floor((gMap.pos.y - gMap.baseDim.ht / 2) / gMap.baseDim.tsize) - 1,
535 var tMax = normalizeCoords({x: Math.ceil((gMap.pos.x + gMap.baseDim.wid / 2) / gMap.baseDim.tsize) + 1,
536 y: Math.ceil((gMap.pos.y + gMap.baseDim.ht / 2) / gMap.baseDim.tsize) + 1,
538 console.log("In range: " + tMin.x + "," + tMin.y + "," + tMin.z + " - " + tMax.x + "," + tMax.y + "," + tMax.z);
539 for (var tileKey in gMap.glTextures) {
540 var keyMatches = tileKey.match(/([^:]+)::(\d+),(\d+),(\d+)/);
541 if (keyMatches && keyMatches[1] != "loading") {
543 style: keyMatches[1],
549 if (txData.style != gMap.activeMap) { delTx = true; console.log("Different map style: " + txData.style); }
550 if (!delTx && (txData.z < tMin.z || txData.z > tMax.z)) { delTx = true; console.log("Out-of-range zoom: " + txData.z); }
551 if (tMin.x < tMax.x) {
552 if (!delTx && (txData.x < tMin.x || txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
555 // We are crossing over the 0 coordinate!
556 if (!delTx && (txData.x < tMin.x && txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
558 if (tMin.y < tMax.y) {
559 if (!delTx && (txData.y < tMin.y || txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
562 // We are crossing over the 0 coordinate!
563 if (!delTx && (txData.y < tMin.y && txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
566 // Delete texture from GL and from the array we are holding.
567 gMap.gl.deleteTexture(gMap.glTextures[tileKey]);
568 delete gMap.glTextures[tileKey];
572 console.log("Cleaning complete, " + Object.keys(gMap.glTextures).length + " textures left)");
576 handleContextLost: function(event) {
577 event.preventDefault();
578 // GL context is gone, let's reset everything that depends on it.
579 clearInterval(gMap.glTxCleanIntervalID);
580 gMap.glTextures = {};
583 handleContextRestored: function(event) {
584 // When GL context is back, init GL again and draw.
590 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
591 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
594 if (gMap.pos.z < gMap.maxZoom) {
601 if (gMap.pos.z > 0) {
607 function zoomTo(aTargetLevel) {
608 aTargetLevel = parseInt(aTargetLevel);
609 if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) {
610 gMap.pos.z = aTargetLevel;
615 function gps2xy(aLatitude, aLongitude) {
616 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
617 var convLat = aLatitude * Math.PI / 180;
618 var rawY = (1 - Math.log(Math.tan(convLat) +
619 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
620 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
621 return {x: Math.round(rawX),
622 y: Math.round(rawY)};
625 function xy2gps(aX, aY) {
626 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
627 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
628 return {latitude: 180 / Math.PI *
629 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
630 longitude: aX / maxZoomFactor * 360 - 180};
633 function setMapStyle() {
634 var mapSel = document.getElementById("mapSelector");
635 if (mapSel.selectedIndex >= 0 && gMap.activeMap != mapSel.value) {
636 gMap.activeMap = mapSel.value;
637 gPrefs.set("active_map_style", gMap.activeMap);
638 document.getElementById("copyright").innerHTML =
639 gMapStyles[gMap.activeMap].copyright;
640 if (!gWaitCounter) { // Only do this when prefs are loaded already.
647 // A sane mod function that works for negative numbers.
650 return ((a % b) + b) % b;
653 function normalizeCoords(aCoords) {
654 var zoomFactor = Math.pow(2, aCoords.z);
655 return {x: mod(aCoords.x, zoomFactor),
656 y: mod(aCoords.y, zoomFactor),
660 function getTileKey(aStyle, aNormalizedCoords) {
661 return aStyle + "::" +
662 aNormalizedCoords.x + "," +
663 aNormalizedCoords.y + "," +
667 // Returns true if the tile is outside the current view.
668 function isOutsideWindow(t) {
669 var pos = decodeIndex(t);
671 var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z);
672 var wid = gMap.width * zoomFactor;
673 var ht = gMap.height * zoomFactor;
678 var sz = gMap.tileSize * zoomFactor;
679 if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 ||
680 pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2)
685 function encodeIndex(x, y, z) {
686 var norm = normalizeCoords({x: x, y: y, z: z});
687 return norm.x + "," + norm.y + "," + norm.z;
690 function decodeIndex(encodedIdx) {
691 var ind = encodedIdx.split(",", 3);
692 return {x: ind[0], y: ind[1], z: ind[2]};
695 function drawTrack() {
696 if (gTrackContext && (document.hidden != true)) { // Only draw if we're actually visible.
697 gLastDrawnPoint = null;
698 gCurPosMapCache = undefined;
699 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
701 for (var i = 0; i < gTrack.length; i++) {
702 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
703 (i + 1 >= gTrack.length || gTrack[i+1].beginSegment));
709 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
710 var trackpoint = gps2xy(aLatitude, aLongitude);
711 // lastPoint is for optimizing (not actually executing the draw until the last)
712 trackpoint.optimized = (lastPoint === false);
713 var mappos = {x: Math.round((trackpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
714 y: Math.round((trackpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
716 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
717 gTrackContext.strokeStyle = gTrackColor;
718 gTrackContext.fillStyle = gTrackContext.strokeStyle;
719 gTrackContext.lineWidth = gTrackWidth;
720 gTrackContext.lineCap = "round";
721 gTrackContext.lineJoin = "round";
723 // This breaks optimiziation, so make sure to reset optimization.
724 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
725 trackpoint.optimized = false;
726 // Close path if one was open.
727 if (gLastDrawnPoint && gLastDrawnPoint.optimized) {
728 gTrackContext.stroke();
731 if (!gLastDrawnPoint || (gLastDrawnPoint == trackpoint) || !gLastDrawnPoint.optimized) {
732 // Start drawing a segment.
733 gTrackContext.beginPath();
734 gTrackContext.arc(mappos.x, mappos.y,
735 gTrackContext.lineWidth, 0, Math.PI * 2, false);
736 gTrackContext.fill();
739 // Continue drawing segment, close if needed.
740 gTrackContext.lineTo(mappos.x, mappos.y);
741 if (!trackpoint.optimized)
742 gTrackContext.stroke();
744 gLastDrawnPoint = trackpoint;
747 function drawCurrentLocation(trackPoint) {
748 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
749 var circleRadius = Math.round(gCurLocSize / 2);
750 var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
751 y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
753 undrawCurrentLocation();
755 // Cache overdrawn area.
758 radius: circleRadius,
759 data: gTrackContext.getImageData(mappos.x - circleRadius,
760 mappos.y - circleRadius,
761 circleRadius * 2, circleRadius * 2)};
763 gTrackContext.strokeStyle = gCurLocColor;
764 gTrackContext.fillStyle = gTrackContext.strokeStyle;
765 gTrackContext.beginPath();
766 gTrackContext.arc(mappos.x, mappos.y,
767 circleRadius, 0, Math.PI * 2, false);
768 gTrackContext.fill();
771 function undrawCurrentLocation() {
772 if (gCurPosMapCache) {
773 var oldpoint = gCurPosMapCache.point;
774 var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
775 y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
776 gTrackContext.putImageData(gCurPosMapCache.data,
777 oldmp.x - gCurPosMapCache.radius,
778 oldmp.y - gCurPosMapCache.radius);
779 gCurPosMapCache = undefined;
783 function calcTrackDuration() {
784 // Get the duration of the track in s.
786 if (gTrack.length > 1) {
787 for (var i = 1; i < gTrack.length; i++) {
788 if (!gTrack[i].beginSegment) {
789 tDuration += (gTrack[i].time - gTrack[i-1].time);
793 return Math.round(tDuration / 1000); // The timestamps are in ms but we return seconds.
796 function calcTrackLength() {
797 // Get the length of the track in km.
799 if (gTrack.length > 1) {
800 for (var i = 1; i < gTrack.length; i++) {
801 if (!gTrack[i].beginSegment) {
802 tLength += getPointDistance(gTrack[i-1].coords, gTrack[i].coords);
809 function getPointDistance(aGPSPoint1, aGPSPoint2) {
810 // Get the distance in km between the two given GPS points.
811 // See http://stackoverflow.com/questions/365826/calculate-distance-between-2-gps-coordinates
812 // Earth is almost exactly a sphere and we calculate small distances on the surface, so we can do spherical great-circle math.
813 // Also see http://en.wikipedia.org/wiki/Great-circle_distance
815 var dLat = deg2rad(aGPSPoint2.latitude - aGPSPoint1.latitude);
816 var dLon = deg2rad(aGPSPoint2.longitude - aGPSPoint1.longitude);
817 var lat1 = deg2rad(aGPSPoint1.latitude);
818 var lat2 = deg2rad(aGPSPoint2.latitude);
820 var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
821 Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
822 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
826 function deg2rad(aDegreeValue) {
827 // Convert an angle in degrees to radiants.
828 return aDegreeValue * (Math.PI / 180);
832 handleEvent: function(aEvent) {
833 var touchEvent = aEvent.type.indexOf('touch') != -1;
836 aEvent.stopPropagation();
839 // Bail out if the event is happening on an input.
840 if (aEvent.target.tagName.toLowerCase() == "input")
843 // Bail out on unwanted map moves, but not zoom or keyboard events.
844 if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
845 // Bail out if this is neither a touch nor left-click.
846 if (!touchEvent && aEvent.button != 0)
849 // Bail out if the started touch can't be found.
850 if (touchEvent && gDragging &&
851 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
855 var coordObj = touchEvent ?
856 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
859 switch (aEvent.type) {
863 if (aEvent.targetTouches.length == 2) {
864 gPinchStartWidth = Math.sqrt(
865 Math.pow(aEvent.targetTouches.item(1).clientX -
866 aEvent.targetTouches.item(0).clientX, 2) +
867 Math.pow(aEvent.targetTouches.item(1).clientY -
868 aEvent.targetTouches.item(0).clientY, 2)
871 gDragTouchID = aEvent.changedTouches.item(0).identifier;
872 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
874 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
875 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
877 if (touchEvent || aEvent.button === 0) {
886 if (touchEvent && aEvent.targetTouches.length == 2) {
887 curPinchStartWidth = Math.sqrt(
888 Math.pow(aEvent.targetTouches.item(1).clientX -
889 aEvent.targetTouches.item(0).clientX, 2) +
890 Math.pow(aEvent.targetTouches.item(1).clientY -
891 aEvent.targetTouches.item(0).clientY, 2)
893 if (!gPinchStartWidth)
894 gPinchStartWidth = curPinchStartWidth;
896 if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
897 gPinchStartWidth / curPinchStartWidth < 0.6) {
898 var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
899 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
900 // Calculate new center of the map - preserve middle of pinch.
901 // This means that pixel distance between old center and middle
902 // must equal pixel distance of new center and middle.
903 var x = (aEvent.targetTouches.item(1).clientX +
904 aEvent.targetTouches.item(0).clientX) / 2 -
905 gGLMapCanvas.offsetLeft;
906 var y = (aEvent.targetTouches.item(1).clientY +
907 aEvent.targetTouches.item(0).clientY) / 2 -
908 gGLMapCanvas.offsetTop;
910 // Zoom factor after this action.
911 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
912 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
913 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
915 if (gPinchStartWidth < curPinchStartWidth)
920 // Reset pinch start width and start another pinch gesture.
921 gPinchStartWidth = null;
924 // If we are in a pinch, do not drag.
927 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
928 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
929 if (gDragging === true) {
930 var dX = x - gLastMouseX;
931 var dY = y - gLastMouseY;
932 gMap.pos.x -= dX * gMap.zoomFactor;
933 gMap.pos.y -= dY * gMap.zoomFactor;
942 gPinchStartWidth = null;
952 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
953 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
955 // Only accept (non-null) deltaY values
959 // Debug output: "coordinates" of the point the mouse was over.
961 var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor,
962 y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor};
963 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
964 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
965 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
966 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
967 pt2Coord.x + "/" + pt2Coord.y);
970 var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1);
971 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
972 // Calculate new center of the map - same point stays under the mouse.
973 // This means that the pixel distance between the old center and point
974 // must equal the pixel distance of the new center and that point.
975 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
976 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
978 // Zoom factor after this action.
979 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
980 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
981 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
983 if (aEvent.deltaY < 0)
990 // Allow keyboard control to move and zoom the map.
991 // Should use aEvent.key instead of aEvent.which but needs bug 680830.
992 // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
995 switch (aEvent.which) {
997 dX = -gMap.tileSize / 2;
1000 dX = gMap.tileSize / 2;
1003 dY = gMap.tileSize / 2;
1006 dY = -gMap.tileSize / 2;
1009 case 107: // + (numpad)
1010 case 171: // + (normal key)
1014 case 109: // - (numpad)
1015 case 173: // - (normal key)
1027 zoomTo(aEvent.which - 38);
1032 case 96: // 0 (numpad)
1033 case 97: // 1 (numpad)
1034 case 98: // 2 (numpad)
1035 case 99: // 3 (numpad)
1036 case 100: // 4 (numpad)
1037 case 101: // 5 (numpad)
1038 case 102: // 6 (numpad)
1039 case 103: // 7 (numpad)
1040 case 104: // 8 (numpad)
1041 zoomTo(aEvent.which - 86);
1043 case 105: // 9 (numpad)
1046 default: // not supported
1047 console.log("key not supported: " + aEvent.which);
1053 gMap.pos.x -= dX * gMap.zoomFactor;
1054 gMap.pos.y -= dY * gMap.zoomFactor;
1062 function visibilityEvHandler() {
1063 // Immediately draw if we just got visible.
1064 if (document.hidden != true) {
1067 // No need to handle the event where we become invisible as we care only draw
1068 // when we are visible anyhow.
1073 lastPos: {x: undefined, y: undefined},
1074 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
1075 this.tracking = true;
1076 var watchCall = function() {
1077 // calc new position in lat/lon degrees
1078 // 90° on Earth surface are ~10,000 km at the equator,
1079 // so try moving at most 10m at a time
1080 if (geofake.lastPos.x)
1081 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
1083 geofake.lastPos.x = 48.208174
1084 if (geofake.lastPos.y)
1085 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
1087 geofake.lastPos.y = 16.373819
1088 aSuccessCallback({timestamp: Date.now(),
1089 coords: {latitude: geofake.lastPos.x,
1090 longitude: geofake.lastPos.y,
1092 if (geofake.tracking)
1093 setTimeout(watchCall, 1000);
1095 setTimeout(watchCall, 1000);
1098 clearWatch: function(aID) {
1099 this.tracking = false;
1103 function setCentering(aCheckbox) {
1104 if (gMapPrefsLoaded && mainDB)
1105 gPrefs.set("center_map", aCheckbox.checked);
1106 gCenterPosition = aCheckbox.checked;
1109 function setTracking(aCheckbox) {
1110 if (gMapPrefsLoaded && mainDB)
1111 gPrefs.set("tracking_enabled", aCheckbox.checked);
1112 if (aCheckbox.checked)
1118 function startTracking() {
1120 gActionLabel.textContent = "Establishing Position";
1121 gAction.style.display = "block";
1122 gGeoWatchID = gGeolocation.watchPosition(
1123 function(position) {
1124 if (gActionLabel.textContent) {
1125 gActionLabel.textContent = "";
1126 gAction.style.display = "none";
1128 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
1129 var tPoint = {time: position.timestamp,
1130 coords: {latitude: position.coords.latitude,
1131 longitude: position.coords.longitude,
1132 altitude: position.coords.altitude,
1133 accuracy: position.coords.accuracy,
1134 altitudeAccuracy: position.coords.altitudeAccuracy,
1135 heading: position.coords.heading,
1136 speed: position.coords.speed},
1137 beginSegment: !gLastTrackPoint};
1138 // Only add point to track is accuracy is good enough.
1139 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
1140 gLastTrackPoint = tPoint;
1141 gTrack.push(tPoint);
1142 try { gTrackStore.push(tPoint); } catch(e) {}
1143 var redrawn = false;
1144 if (gCenterPosition) {
1145 var posCoord = gps2xy(position.coords.latitude,
1146 position.coords.longitude);
1147 if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 ||
1148 Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) {
1149 gMap.pos.x = posCoord.x;
1150 gMap.pos.y = posCoord.y;
1151 gMap.draw(); // This draws the current point as well.
1156 undrawCurrentLocation();
1157 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
1159 drawCurrentLocation(tPoint);
1162 // Ignore erros for the moment, but this is good for debugging.
1163 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
1165 console.log(error.message);
1167 {enableHighAccuracy: true}
1172 function endTracking() {
1173 if (gActionLabel.textContent) {
1174 gActionLabel.textContent = "";
1175 gAction.style.display = "none";
1178 gGeolocation.clearWatch(gGeoWatchID);
1182 function clearTrack() {
1184 gTrackStore.clear();
1188 var gTileService = {
1189 objStore: "tilecache",
1191 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
1193 get: function(aStyle, aCoords, aCallback) {
1194 var norm = normalizeCoords(aCoords);
1195 var dbkey = getTileKey(aStyle, norm);
1196 this.getDBCache(dbkey, function(aResult, aEvent) {
1198 // We did get a cached object.
1199 aCallback(aResult.image, aStyle, aCoords, dbkey);
1200 // Look at the timestamp and return if it's not too old.
1201 if (aResult.timestamp + gTileService.ageLimit > Date.now())
1203 // Reload cached tile otherwise.
1204 var oldDate = new Date(aResult.timestamp);
1205 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
1207 // Retrieve image from the web and store it in the cache.
1208 var XHR = new XMLHttpRequest();
1210 gMapStyles[aStyle].url
1211 .replace("{x}", norm.x)
1212 .replace("{y}", norm.y)
1213 .replace("{z}", norm.z)
1214 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 3)))
1215 .replace("[a-d]", String.fromCharCode(97 + Math.floor(Math.random() * 4)))
1216 .replace("[1-4]", 1 + Math.floor(Math.random() * 4)),
1218 XHR.responseType = "blob";
1219 XHR.addEventListener("load", function () {
1220 if (XHR.status === 200) {
1221 var blob = XHR.response;
1222 aCallback(blob, aStyle, aCoords, dbkey);
1223 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
1230 getDBCache: function(aKey, aCallback) {
1233 var transaction = mainDB.transaction([this.objStore]);
1234 var request = transaction.objectStore(this.objStore).get(aKey);
1235 request.onsuccess = function(event) {
1236 aCallback(request.result, event);
1238 request.onerror = function(event) {
1239 // Errors can be handled here.
1240 aCallback(undefined, event);
1244 setDBCache: function(aKey, aValue, aCallback) {
1247 var success = false;
1248 var transaction = mainDB.transaction([this.objStore], "readwrite");
1249 var objStore = transaction.objectStore(this.objStore);
1250 var request = objStore.put(aValue, aKey);
1251 request.onsuccess = function(event) {
1254 aCallback(success, event);
1256 request.onerror = function(event) {
1257 // Errors can be handled here.
1259 aCallback(success, event);
1263 unsetDBCache: function(aKey, aCallback) {
1266 var success = false;
1267 var transaction = mainDB.transaction([this.objStore], "readwrite");
1268 var request = transaction.objectStore(this.objStore).delete(aKey);
1269 request.onsuccess = function(event) {
1272 aCallback(success, event);
1274 request.onerror = function(event) {
1275 // Errors can be handled here.
1277 aCallback(success, event);
1281 clearDB: function(aCallback) {
1284 var success = false;
1285 var transaction = mainDB.transaction([this.objStore], "readwrite");
1286 var request = transaction.objectStore(this.objStore).clear();
1287 request.onsuccess = function(event) {
1290 aCallback(success, event);
1292 request.onerror = function(event) {
1293 // Errors can be handled here.
1295 aCallback(success, event);