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 console.log("active_map_style: >>" + aValue + "<<");
173 if (aValue && gMapStyles[aValue]) {
174 gMap.activeMap = aValue;
177 gMap.activeMap = "osm_mapnik";
179 document.getElementById("mapSelector").value = gMap.activeMap;
180 document.getElementById("copyright").innerHTML =
181 gMapStyles[gMap.activeMap].copyright;
183 var throwEv = new CustomEvent("prefs-step");
184 gAction.dispatchEvent(throwEv);
187 gPrefs.get("position", function(aValue) {
188 if (aValue && aValue.x && aValue.y && aValue.z) {
192 var throwEv = new CustomEvent("prefs-step");
193 gAction.dispatchEvent(throwEv);
196 gPrefs.get("center_map", function(aValue) {
197 if (aValue === undefined) {
198 document.getElementById("centerCheckbox").checked = true;
201 document.getElementById("centerCheckbox").checked = aValue;
203 setCentering(document.getElementById("centerCheckbox"));
205 var throwEv = new CustomEvent("prefs-step");
206 gAction.dispatchEvent(throwEv);
209 gPrefs.get("tracking_enabled", function(aValue) {
210 if (aValue === undefined) {
211 document.getElementById("trackCheckbox").checked = true;
214 document.getElementById("trackCheckbox").checked = aValue;
217 var throwEv = new CustomEvent("prefs-step");
218 gAction.dispatchEvent(throwEv);
221 var trackLoadStarted = false;
222 var redrawBase = 100;
223 gTrackStore.getListStepped(function(aTPoint) {
225 // Add in front and return new length.
226 var tracklen = gTrack.unshift(aTPoint);
227 // Redraw track periodically, larger distance the longer it gets
228 // (but clamped to the first value over a certain limit).
229 // Initial paint will do initial track drawing.
230 if (tracklen % redrawBase == 0) {
232 if (redrawBase < 1000) {
233 redrawBase = tracklen;
238 // Last point received.
241 if (!trackLoadStarted) {
242 // We have the most recent point, if present, rest will load async.
243 trackLoadStarted = true;
245 var throwEv = new CustomEvent("prefs-step");
246 gAction.dispatchEvent(throwEv);
254 glShaderProgram: null,
255 glVertexPositionAttr: null,
256 glTextureCoordAttr: null,
257 glResolutionAttr: null,
260 glTxCleanIntervalID: null,
261 glTexturesPerZoomLevel: 0,
263 activeMap: "osm_mapnik",
265 maxZoom: 18, // The minimum is 0.
268 x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
269 y: 23670000.0, // The range is 0-67108864 (2^gMap.maxZoom * gMap.tileSize)
270 z: 5 // This could be fractional if supported being between zoom levels.
272 baseDim: { // Map width, height and tile size in level 18 pixels.
278 get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; },
279 get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; },
281 getVertShaderSource: function() {
282 return 'attribute vec2 aVertexPosition;\n' +
283 'attribute vec2 aTextureCoord;\n\n' +
284 'uniform vec2 uResolution;\n\n' +
285 'varying highp vec2 vTextureCoord;\n\n' +
286 'void main(void) {\n' +
287 // convert the rectangle from pixels to -1.0 to +1.0 (clipspace) 0.0 to 1.0
288 ' vec2 clipSpace = aVertexPosition * 2.0 / uResolution - 1.0;\n' +
289 ' gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' +
290 ' vTextureCoord = aTextureCoord;\n' +
292 getFragShaderSource: function() {
293 return 'varying highp vec2 vTextureCoord;\n\n' +
294 'uniform sampler2D uImage;\n\n' +
295 'void main(void) {\n' +
296 ' gl_FragColor = texture2D(uImage, vTextureCoord);\n' +
300 // When called from the event listener, the "this" reference doesn't work, so use the object name.
301 console.log("Initializing WebGL...");
303 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
304 gMap.gl.clearColor(0.0, 0.0, 0.0, 0.5); // Set clear color to black, fully opaque.
305 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT|gMap.gl.DEPTH_BUFFER_BIT); // Clear the color.
307 // Create and initialize the shaders.
308 console.log("Create and compile shaders...");
309 var vertShader = gMap.gl.createShader(gMap.gl.VERTEX_SHADER);
310 var fragShader = gMap.gl.createShader(gMap.gl.FRAGMENT_SHADER);
311 gMap.gl.shaderSource(vertShader, gMap.getVertShaderSource());
312 // Compile the shader program.
313 gMap.gl.compileShader(vertShader);
314 // See if it compiled successfully.
315 if (!gMap.gl.getShaderParameter(vertShader, gMap.gl.COMPILE_STATUS)) {
316 console.log("An error occurred compiling the vertex shader: " + gMap.gl.getShaderInfoLog(vertShader));
319 gMap.gl.shaderSource(fragShader, gMap.getFragShaderSource());
320 // Compile the shader program.
321 gMap.gl.compileShader(fragShader);
322 // See if it compiled successfully.
323 if (!gMap.gl.getShaderParameter(fragShader, gMap.gl.COMPILE_STATUS)) {
324 console.log("An error occurred compiling the fragment shader: " + gMap.gl.getShaderInfoLog(fragShader));
328 console.log("Create and link shader program...");
329 gMap.glShaderProgram = gMap.gl.createProgram();
330 gMap.gl.attachShader(gMap.glShaderProgram, vertShader);
331 gMap.gl.attachShader(gMap.glShaderProgram, fragShader);
332 gMap.gl.linkProgram(gMap.glShaderProgram);
333 // If creating the shader program failed, alert
334 if (!gMap.gl.getProgramParameter(gMap.glShaderProgram, gMap.gl.LINK_STATUS)) {
335 alert("Unable to initialize the shader program.");
337 gMap.gl.useProgram(gMap.glShaderProgram);
338 // Get locations of the attributes.
339 gMap.glVertexPositionAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aVertexPosition");
340 gMap.glTextureCoordAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aTextureCoord");
341 gMap.glResolutionAttr = gMap.gl.getUniformLocation(gMap.glShaderProgram, "uResolution");
343 console.log("Set up vertex buffer...");
344 var tileVerticesBuffer = gMap.gl.createBuffer();
345 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, tileVerticesBuffer);
346 // The vertices are the coordinates of the corner points of the square.
355 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(vertices), gMap.gl.STATIC_DRAW);
356 gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr);
357 gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0);
359 gMap.loadImageToTexture(gLoadingTile, getTileKey("loading", {x: 0, y: 0, z: 0}));
361 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
363 // Create a buffer for the position of the rectangle corners.
364 console.log("Set up coord buffer...");
365 var mapVerticesTextureCoordBuffer = gMap.gl.createBuffer();
366 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer);
367 gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr);
368 gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0);
370 // Call texture cleaning every 30 seconds, for now (is 60 better?).
371 gMap.glTxCleanIntervalID = window.setInterval(gMap.cleanTextures, 30 * 1000);
375 // We may be called when context was lost and destroyed,
376 // only send event when we are in app startup
377 // (gAppInitDone is set to true right after we return this event).
378 var throwEv = new CustomEvent("mapinit-done");
379 gAction.dispatchEvent(throwEv);
388 assembleGL: function() {
389 if (!gMap.gl) { return; }
391 document.getElementById("zoomLevel").textContent = gMap.pos.z;
392 gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
393 gMap.baseDim.wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor;
394 gMap.baseDim.ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor;
395 gMap.baseDim.tsize = gMap.tileSize * gMap.zoomFactor;
397 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
398 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
399 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
400 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
402 if (gMapPrefsLoaded && mainDB)
403 gPrefs.set("position", gMap.pos);
405 // Go through all the tiles in the map, find out if to draw them and do so.
406 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
407 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
408 // Only go to loading step if we haven't loaded the texture.
409 var coords = {x: x, y: y, z: gMap.pos.z};
410 var tileKey = getTileKey(gMap.activeMap, normalizeCoords(coords));
411 if (!gMap.glTextures[tileKey]) {
412 // Initiate loading/drawing of the actual tile.
413 gTileService.get(gMap.activeMap, coords,
414 function(aImage, aStyle, aCoords, aTileKey) {
415 // Only actually load if this still applies for the current view.
416 if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) {
417 var URL = window.URL;
418 var imgURL = URL.createObjectURL(aImage);
419 var imgObj = new Image();
420 imgObj.onload = function() {
421 gMap.loadImageToTexture(imgObj, aTileKey);
422 if (document.hidden != true) { // Only draw if we're actually visible.
423 window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
425 URL.revokeObjectURL(imgURL);
433 if (document.hidden != true) { // Only draw if we're actually visible.
434 window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
439 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
440 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
441 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
442 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
444 // Go through all the tiles in the map, find out if to draw them and do so.
445 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
446 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
447 // Rounding the pixel offsets ensures we position the tiles precisely.
448 var xoff = Math.round((x * gMap.baseDim.tsize - xMin) / gMap.zoomFactor);
449 var yoff = Math.round((y * gMap.baseDim.tsize - yMin) / gMap.zoomFactor);
450 // Draw the tile, first find out the actual texture to use.
451 var norm = normalizeCoords({x: x, y: y, z: gMap.pos.z});
452 var tileKey = getTileKey(gMap.activeMap, norm);
453 if (!gMap.glTextures[tileKey]) {
454 tileKey = getTileKey("loading", {x: 0, y: 0, z: 0});
456 gMap.drawTileGL(xoff, yoff, tileKey);
461 resizeAndDraw: function() {
462 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
463 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
464 if (gGLMapCanvas && gTrackCanvas) {
465 gGLMapCanvas.width = viewportWidth;
466 gGLMapCanvas.height = viewportHeight;
467 gTrackCanvas.width = viewportWidth;
468 gTrackCanvas.height = viewportHeight;
470 // Size viewport to canvas size.
471 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
473 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT);
474 // Make sure the vertex shader get the right resolution.
475 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
476 // Prepare recalculation of textures to keep for one zoom level.
477 gMap.glTexturesPerZoomLevel = 0;
484 drawTileGL: function(aLeft, aRight, aTileKey) {
485 gMap.gl.activeTexture(gMap.gl.TEXTURE0);
486 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
487 // Set uImage to refer to TEXTURE0
488 gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0);
490 var i_width = gMap.tileSize;
491 var y_start = aRight;
492 var i_height = gMap.tileSize;
493 var textureCoordinates = [
495 x_start + i_width, y_start,
496 x_start, y_start + i_height,
497 x_start, y_start + i_height,
498 x_start + i_width, y_start,
499 x_start + i_width, y_start + i_height,
501 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW);
503 // There are 6 indices in textureCoordinates.
504 gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
507 loadImageToTexture: function(aImage, aTileKey) {
508 // Create and bind texture.
509 gMap.glTextures[aTileKey] = gMap.gl.createTexture();
510 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
511 // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two).
512 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST);
513 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST);
514 // Upload the image into the texture.
515 gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage);
518 cleanTextures: function() {
519 // Get rid of unneeded textures to save memory.
520 // TODO: Be less aggressive, maybe keep neighboring zoom levels (but x/y coords there are zoom-specific).
521 if (!gMap.glTexturesPerZoomLevel) {
522 // Calculate how many textures we need to keep for one zoom level.
523 // ceil(width/size) gives us the minimum, keep one on either side as well.
524 gMap.glTexturesPerZoomLevel =
525 Math.ceil(gMap.gl.drawingBufferWidth / gMap.tileSize + 2) *
526 Math.ceil(gMap.gl.drawingBufferHeight / gMap.tileSize + 2);
527 console.log("Keeping " + gMap.glTexturesPerZoomLevel + " textures per level");
529 if (Object.keys(gMap.glTextures).length > gMap.glTexturesPerZoomLevel) {
530 console.log("Cleaning textures... (have " + Object.keys(gMap.glTextures).length + " atm)");
532 // Find coordinate ranges for tiles to keep.
533 var tMin = normalizeCoords({x: Math.floor((gMap.pos.x - gMap.baseDim.wid / 2) / gMap.baseDim.tsize) - 1,
534 y: Math.floor((gMap.pos.y - gMap.baseDim.ht / 2) / gMap.baseDim.tsize) - 1,
536 var tMax = normalizeCoords({x: Math.ceil((gMap.pos.x + gMap.baseDim.wid / 2) / gMap.baseDim.tsize) + 1,
537 y: Math.ceil((gMap.pos.y + gMap.baseDim.ht / 2) / gMap.baseDim.tsize) + 1,
539 console.log("In range: " + tMin.x + "," + tMin.y + "," + tMin.z + " - " + tMax.x + "," + tMax.y + "," + tMax.z);
540 for (var tileKey in gMap.glTextures) {
541 var keyMatches = tileKey.match(/([^:]+)::(\d+),(\d+),(\d+)/);
542 if (keyMatches && keyMatches[1] != "loading") {
544 style: keyMatches[1],
550 if (txData.style != gMap.activeMap) { delTx = true; console.log("Different map style: " + txData.style); }
551 if (!delTx && (txData.z < tMin.z || txData.z > tMax.z)) { delTx = true; console.log("Out-of-range zoom: " + txData.z); }
552 if (tMin.x < tMax.x) {
553 if (!delTx && (txData.x < tMin.x || txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
556 // We are crossing over the 0 coordinate!
557 if (!delTx && (txData.x < tMin.x && txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
559 if (tMin.y < tMax.y) {
560 if (!delTx && (txData.y < tMin.y || txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
563 // We are crossing over the 0 coordinate!
564 if (!delTx && (txData.y < tMin.y && txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
567 // Delete texture from GL and from the array we are holding.
568 gMap.gl.deleteTexture(gMap.glTextures[tileKey]);
569 delete gMap.glTextures[tileKey];
573 console.log("Cleaning complete, " + Object.keys(gMap.glTextures).length + " textures left)");
577 handleContextLost: function(event) {
578 event.preventDefault();
579 // GL context is gone, let's reset everything that depends on it.
580 clearInterval(gMap.glTxCleanIntervalID);
581 gMap.glTextures = {};
584 handleContextRestored: function(event) {
585 // When GL context is back, init GL again and draw.
591 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
592 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
595 if (gMap.pos.z < gMap.maxZoom) {
602 if (gMap.pos.z > 0) {
608 function zoomTo(aTargetLevel) {
609 aTargetLevel = parseInt(aTargetLevel);
610 if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) {
611 gMap.pos.z = aTargetLevel;
616 function gps2xy(aLatitude, aLongitude) {
617 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
618 var convLat = aLatitude * Math.PI / 180;
619 var rawY = (1 - Math.log(Math.tan(convLat) +
620 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
621 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
622 return {x: Math.round(rawX),
623 y: Math.round(rawY)};
626 function xy2gps(aX, aY) {
627 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
628 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
629 return {latitude: 180 / Math.PI *
630 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
631 longitude: aX / maxZoomFactor * 360 - 180};
634 function setMapStyle() {
635 var mapSel = document.getElementById("mapSelector");
636 if (mapSel.selectedIndex >= 0 && gMap.activeMap != mapSel.value) {
637 gMap.activeMap = mapSel.value;
638 gPrefs.set("active_map_style", gMap.activeMap);
639 document.getElementById("copyright").innerHTML =
640 gMapStyles[gMap.activeMap].copyright;
641 if (!gWaitCounter) { // Only do this when prefs are loaded already.
648 // A sane mod function that works for negative numbers.
651 return ((a % b) + b) % b;
654 function normalizeCoords(aCoords) {
655 var zoomFactor = Math.pow(2, aCoords.z);
656 return {x: mod(aCoords.x, zoomFactor),
657 y: mod(aCoords.y, zoomFactor),
661 function getTileKey(aStyle, aNormalizedCoords) {
662 return aStyle + "::" +
663 aNormalizedCoords.x + "," +
664 aNormalizedCoords.y + "," +
668 // Returns true if the tile is outside the current view.
669 function isOutsideWindow(t) {
670 var pos = decodeIndex(t);
672 var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z);
673 var wid = gMap.width * zoomFactor;
674 var ht = gMap.height * zoomFactor;
679 var sz = gMap.tileSize * zoomFactor;
680 if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 ||
681 pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2)
686 function encodeIndex(x, y, z) {
687 var norm = normalizeCoords({x: x, y: y, z: z});
688 return norm.x + "," + norm.y + "," + norm.z;
691 function decodeIndex(encodedIdx) {
692 var ind = encodedIdx.split(",", 3);
693 return {x: ind[0], y: ind[1], z: ind[2]};
696 function drawTrack() {
697 if (gTrackContext && (document.hidden != true)) { // Only draw if we're actually visible.
698 gLastDrawnPoint = null;
699 gCurPosMapCache = undefined;
700 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
702 for (var i = 0; i < gTrack.length; i++) {
703 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
704 (i + 1 >= gTrack.length || gTrack[i+1].beginSegment));
710 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
711 var trackpoint = gps2xy(aLatitude, aLongitude);
712 // lastPoint is for optimizing (not actually executing the draw until the last)
713 trackpoint.optimized = (lastPoint === false);
714 var mappos = {x: Math.round((trackpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
715 y: Math.round((trackpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
717 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
718 gTrackContext.strokeStyle = gTrackColor;
719 gTrackContext.fillStyle = gTrackContext.strokeStyle;
720 gTrackContext.lineWidth = gTrackWidth;
721 gTrackContext.lineCap = "round";
722 gTrackContext.lineJoin = "round";
724 // This breaks optimiziation, so make sure to reset optimization.
725 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
726 trackpoint.optimized = false;
727 // Close path if one was open.
728 if (gLastDrawnPoint && gLastDrawnPoint.optimized) {
729 gTrackContext.stroke();
732 if (!gLastDrawnPoint || (gLastDrawnPoint == trackpoint) || !gLastDrawnPoint.optimized) {
733 // Start drawing a segment.
734 gTrackContext.beginPath();
735 gTrackContext.arc(mappos.x, mappos.y,
736 gTrackContext.lineWidth, 0, Math.PI * 2, false);
737 gTrackContext.fill();
740 // Continue drawing segment, close if needed.
741 gTrackContext.lineTo(mappos.x, mappos.y);
742 if (!trackpoint.optimized)
743 gTrackContext.stroke();
745 gLastDrawnPoint = trackpoint;
748 function drawCurrentLocation(trackPoint) {
749 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
750 var circleRadius = Math.round(gCurLocSize / 2);
751 var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
752 y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
754 undrawCurrentLocation();
756 // Cache overdrawn area.
759 radius: circleRadius,
760 data: gTrackContext.getImageData(mappos.x - circleRadius,
761 mappos.y - circleRadius,
762 circleRadius * 2, circleRadius * 2)};
764 gTrackContext.strokeStyle = gCurLocColor;
765 gTrackContext.fillStyle = gTrackContext.strokeStyle;
766 gTrackContext.beginPath();
767 gTrackContext.arc(mappos.x, mappos.y,
768 circleRadius, 0, Math.PI * 2, false);
769 gTrackContext.fill();
772 function undrawCurrentLocation() {
773 if (gCurPosMapCache) {
774 var oldpoint = gCurPosMapCache.point;
775 var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
776 y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
777 gTrackContext.putImageData(gCurPosMapCache.data,
778 oldmp.x - gCurPosMapCache.radius,
779 oldmp.y - gCurPosMapCache.radius);
780 gCurPosMapCache = undefined;
784 function calcTrackDuration() {
785 // Get the duration of the track in s.
787 if (gTrack.length > 1) {
788 for (var i = 1; i < gTrack.length; i++) {
789 if (!gTrack[i].beginSegment) {
790 tDuration += (gTrack[i].time - gTrack[i-1].time);
794 return Math.round(tDuration / 1000); // The timestamps are in ms but we return seconds.
797 function calcTrackLength() {
798 // Get the length of the track in km.
800 if (gTrack.length > 1) {
801 for (var i = 1; i < gTrack.length; i++) {
802 if (!gTrack[i].beginSegment) {
803 tLength += getPointDistance(gTrack[i-1].coords, gTrack[i].coords);
810 function getPointDistance(aGPSPoint1, aGPSPoint2) {
811 // Get the distance in km between the two given GPS points.
812 // See http://stackoverflow.com/questions/365826/calculate-distance-between-2-gps-coordinates
813 // Earth is almost exactly a sphere and we calculate small distances on the surface, so we can do spherical great-circle math.
814 // Also see http://en.wikipedia.org/wiki/Great-circle_distance
816 var dLat = deg2rad(aGPSPoint2.latitude - aGPSPoint1.latitude);
817 var dLon = deg2rad(aGPSPoint2.longitude - aGPSPoint1.longitude);
818 var lat1 = deg2rad(aGPSPoint1.latitude);
819 var lat2 = deg2rad(aGPSPoint2.latitude);
821 var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
822 Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
823 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
827 function deg2rad(aDegreeValue) {
828 // Convert an angle in degrees to radiants.
829 return aDegreeValue * (Math.PI / 180);
833 handleEvent: function(aEvent) {
834 var touchEvent = aEvent.type.indexOf('touch') != -1;
837 aEvent.stopPropagation();
840 // Bail out if the event is happening on an input.
841 if (aEvent.target.tagName.toLowerCase() == "input")
844 // Bail out on unwanted map moves, but not zoom or keyboard events.
845 if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
846 // Bail out if this is neither a touch nor left-click.
847 if (!touchEvent && aEvent.button != 0)
850 // Bail out if the started touch can't be found.
851 if (touchEvent && gDragging &&
852 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
856 var coordObj = touchEvent ?
857 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
860 switch (aEvent.type) {
864 if (aEvent.targetTouches.length == 2) {
865 gPinchStartWidth = Math.sqrt(
866 Math.pow(aEvent.targetTouches.item(1).clientX -
867 aEvent.targetTouches.item(0).clientX, 2) +
868 Math.pow(aEvent.targetTouches.item(1).clientY -
869 aEvent.targetTouches.item(0).clientY, 2)
872 gDragTouchID = aEvent.changedTouches.item(0).identifier;
873 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
875 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
876 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
878 if (touchEvent || aEvent.button === 0) {
887 if (touchEvent && aEvent.targetTouches.length == 2) {
888 curPinchStartWidth = Math.sqrt(
889 Math.pow(aEvent.targetTouches.item(1).clientX -
890 aEvent.targetTouches.item(0).clientX, 2) +
891 Math.pow(aEvent.targetTouches.item(1).clientY -
892 aEvent.targetTouches.item(0).clientY, 2)
894 if (!gPinchStartWidth)
895 gPinchStartWidth = curPinchStartWidth;
897 if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
898 gPinchStartWidth / curPinchStartWidth < 0.6) {
899 var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
900 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
901 // Calculate new center of the map - preserve middle of pinch.
902 // This means that pixel distance between old center and middle
903 // must equal pixel distance of new center and middle.
904 var x = (aEvent.targetTouches.item(1).clientX +
905 aEvent.targetTouches.item(0).clientX) / 2 -
906 gGLMapCanvas.offsetLeft;
907 var y = (aEvent.targetTouches.item(1).clientY +
908 aEvent.targetTouches.item(0).clientY) / 2 -
909 gGLMapCanvas.offsetTop;
911 // Zoom factor after this action.
912 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
913 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
914 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
916 if (gPinchStartWidth < curPinchStartWidth)
921 // Reset pinch start width and start another pinch gesture.
922 gPinchStartWidth = null;
925 // If we are in a pinch, do not drag.
928 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
929 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
930 if (gDragging === true) {
931 var dX = x - gLastMouseX;
932 var dY = y - gLastMouseY;
933 gMap.pos.x -= dX * gMap.zoomFactor;
934 gMap.pos.y -= dY * gMap.zoomFactor;
943 gPinchStartWidth = null;
953 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
954 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
956 // Only accept (non-null) deltaY values
960 // Debug output: "coordinates" of the point the mouse was over.
962 var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor,
963 y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor};
964 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
965 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
966 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
967 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
968 pt2Coord.x + "/" + pt2Coord.y);
971 var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1);
972 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
973 // Calculate new center of the map - same point stays under the mouse.
974 // This means that the pixel distance between the old center and point
975 // must equal the pixel distance of the new center and that point.
976 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
977 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
979 // Zoom factor after this action.
980 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
981 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
982 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
984 if (aEvent.deltaY < 0)
991 // Allow keyboard control to move and zoom the map.
992 // Should use aEvent.key instead of aEvent.which but needs bug 680830.
993 // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
996 switch (aEvent.which) {
998 dX = -gMap.tileSize / 2;
1001 dX = gMap.tileSize / 2;
1004 dY = gMap.tileSize / 2;
1007 dY = -gMap.tileSize / 2;
1010 case 107: // + (numpad)
1011 case 171: // + (normal key)
1015 case 109: // - (numpad)
1016 case 173: // - (normal key)
1028 zoomTo(aEvent.which - 38);
1033 case 96: // 0 (numpad)
1034 case 97: // 1 (numpad)
1035 case 98: // 2 (numpad)
1036 case 99: // 3 (numpad)
1037 case 100: // 4 (numpad)
1038 case 101: // 5 (numpad)
1039 case 102: // 6 (numpad)
1040 case 103: // 7 (numpad)
1041 case 104: // 8 (numpad)
1042 zoomTo(aEvent.which - 86);
1044 case 105: // 9 (numpad)
1047 default: // not supported
1048 console.log("key not supported: " + aEvent.which);
1054 gMap.pos.x -= dX * gMap.zoomFactor;
1055 gMap.pos.y -= dY * gMap.zoomFactor;
1063 function visibilityEvHandler() {
1064 // Immediately draw if we just got visible.
1065 if (document.hidden != true) {
1068 // No need to handle the event where we become invisible as we care only draw
1069 // when we are visible anyhow.
1074 lastPos: {x: undefined, y: undefined},
1075 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
1076 this.tracking = true;
1077 var watchCall = function() {
1078 // calc new position in lat/lon degrees
1079 // 90° on Earth surface are ~10,000 km at the equator,
1080 // so try moving at most 10m at a time
1081 if (geofake.lastPos.x)
1082 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
1084 geofake.lastPos.x = 48.208174
1085 if (geofake.lastPos.y)
1086 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
1088 geofake.lastPos.y = 16.373819
1089 aSuccessCallback({timestamp: Date.now(),
1090 coords: {latitude: geofake.lastPos.x,
1091 longitude: geofake.lastPos.y,
1093 if (geofake.tracking)
1094 setTimeout(watchCall, 1000);
1096 setTimeout(watchCall, 1000);
1099 clearWatch: function(aID) {
1100 this.tracking = false;
1104 function setCentering(aCheckbox) {
1105 if (gMapPrefsLoaded && mainDB)
1106 gPrefs.set("center_map", aCheckbox.checked);
1107 gCenterPosition = aCheckbox.checked;
1110 function setTracking(aCheckbox) {
1111 if (gMapPrefsLoaded && mainDB)
1112 gPrefs.set("tracking_enabled", aCheckbox.checked);
1113 if (aCheckbox.checked)
1119 function startTracking() {
1121 gActionLabel.textContent = "Establishing Position";
1122 gAction.style.display = "block";
1123 gGeoWatchID = gGeolocation.watchPosition(
1124 function(position) {
1125 if (gActionLabel.textContent) {
1126 gActionLabel.textContent = "";
1127 gAction.style.display = "none";
1129 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
1130 var tPoint = {time: position.timestamp,
1131 coords: {latitude: position.coords.latitude,
1132 longitude: position.coords.longitude,
1133 altitude: position.coords.altitude,
1134 accuracy: position.coords.accuracy,
1135 altitudeAccuracy: position.coords.altitudeAccuracy,
1136 heading: position.coords.heading,
1137 speed: position.coords.speed},
1138 beginSegment: !gLastTrackPoint};
1139 // Only add point to track is accuracy is good enough.
1140 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
1141 gLastTrackPoint = tPoint;
1142 gTrack.push(tPoint);
1143 try { gTrackStore.push(tPoint); } catch(e) {}
1144 var redrawn = false;
1145 if (gCenterPosition) {
1146 var posCoord = gps2xy(position.coords.latitude,
1147 position.coords.longitude);
1148 if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 ||
1149 Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) {
1150 gMap.pos.x = posCoord.x;
1151 gMap.pos.y = posCoord.y;
1152 gMap.draw(); // This draws the current point as well.
1157 undrawCurrentLocation();
1158 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
1160 drawCurrentLocation(tPoint);
1163 // Ignore erros for the moment, but this is good for debugging.
1164 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
1166 console.log(error.message);
1168 {enableHighAccuracy: true}
1173 function endTracking() {
1174 if (gActionLabel.textContent) {
1175 gActionLabel.textContent = "";
1176 gAction.style.display = "none";
1179 gGeolocation.clearWatch(gGeoWatchID);
1183 function clearTrack() {
1185 gTrackStore.clear();
1189 var gTileService = {
1190 objStore: "tilecache",
1192 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
1194 get: function(aStyle, aCoords, aCallback) {
1195 var norm = normalizeCoords(aCoords);
1196 var dbkey = getTileKey(aStyle, norm);
1197 this.getDBCache(dbkey, function(aResult, aEvent) {
1199 // We did get a cached object.
1200 aCallback(aResult.image, aStyle, aCoords, dbkey);
1201 // Look at the timestamp and return if it's not too old.
1202 if (aResult.timestamp + gTileService.ageLimit > Date.now())
1204 // Reload cached tile otherwise.
1205 var oldDate = new Date(aResult.timestamp);
1206 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
1208 // Retrieve image from the web and store it in the cache.
1209 var XHR = new XMLHttpRequest();
1211 gMapStyles[aStyle].url
1212 .replace("{x}", norm.x)
1213 .replace("{y}", norm.y)
1214 .replace("{z}", norm.z)
1215 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 3)))
1216 .replace("[a-d]", String.fromCharCode(97 + Math.floor(Math.random() * 4)))
1217 .replace("[1-4]", 1 + Math.floor(Math.random() * 4)),
1219 XHR.responseType = "blob";
1220 XHR.addEventListener("load", function () {
1221 if (XHR.status === 200) {
1222 var blob = XHR.response;
1223 aCallback(blob, aStyle, aCoords, dbkey);
1224 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
1231 getDBCache: function(aKey, aCallback) {
1234 var transaction = mainDB.transaction([this.objStore]);
1235 var request = transaction.objectStore(this.objStore).get(aKey);
1236 request.onsuccess = function(event) {
1237 aCallback(request.result, event);
1239 request.onerror = function(event) {
1240 // Errors can be handled here.
1241 aCallback(undefined, event);
1245 setDBCache: function(aKey, aValue, aCallback) {
1248 var success = false;
1249 var transaction = mainDB.transaction([this.objStore], "readwrite");
1250 var objStore = transaction.objectStore(this.objStore);
1251 var request = objStore.put(aValue, aKey);
1252 request.onsuccess = function(event) {
1255 aCallback(success, event);
1257 request.onerror = function(event) {
1258 // Errors can be handled here.
1260 aCallback(success, event);
1264 unsetDBCache: function(aKey, aCallback) {
1267 var success = false;
1268 var transaction = mainDB.transaction([this.objStore], "readwrite");
1269 var request = transaction.objectStore(this.objStore).delete(aKey);
1270 request.onsuccess = function(event) {
1273 aCallback(success, event);
1275 request.onerror = function(event) {
1276 // Errors can be handled here.
1278 aCallback(success, event);
1282 clearDB: function(aCallback) {
1285 var success = false;
1286 var transaction = mainDB.transaction([this.objStore], "readwrite");
1287 var request = transaction.objectStore(this.objStore).clear();
1288 request.onsuccess = function(event) {
1291 aCallback(success, event);
1293 request.onerror = function(event) {
1294 // Errors can be handled here.
1296 aCallback(success, event);