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");
112 gMap.activeMap = "osm_mapnik";
116 gGeolocation = geofake;
117 var hiddenList = document.getElementsByClassName("debugHide");
118 // last to first - list of elements with that class is changing!
119 for (var i = hiddenList.length - 1; i >= 0; i--) {
120 hiddenList[i].classList.remove("debugHide");
124 gAction.addEventListener("prefload-done", gMap.initGL, false);
126 console.log("map vars set, loading prefs...");
130 function loadPrefs(aEvent) {
131 if (aEvent && aEvent.type == "prefs-step") {
132 console.log("wait: " + gWaitCounter);
133 if (gWaitCounter == 0) {
134 gAction.removeEventListener(aEvent.type, loadPrefs, false);
135 gMapPrefsLoaded = true;
136 console.log("prefs loaded.");
138 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
139 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
140 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
141 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
143 gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
144 gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
145 gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
146 gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
147 gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
149 gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
151 document.getElementById("body").addEventListener("keydown", mapEvHandler, false);
153 document.addEventListener("visibilitychange", visibilityEvHandler, false);
155 console.log("Events added.");
156 document.getElementById("copyright").innerHTML =
157 gMapStyles[gMap.activeMap].copyright;
159 console.log("Init loading tile...");
160 gLoadingTile = new Image();
161 gLoadingTile.onload = function() {
162 console.log("Loading tile loaded.");
163 var throwEv = new CustomEvent("prefload-done");
164 gAction.dispatchEvent(throwEv);
166 console.log("Set loading tile...");
167 gLoadingTile.src = "style/loading.png";
172 gAction.removeEventListener(aEvent.type, loadPrefs, false);
173 gAction.addEventListener("prefs-step", loadPrefs, false);
175 gPrefs.get("active_map_style", function(aValue) {
176 if (aValue && gMapStyles[aValue]) {
177 gMap.activeMap = aValue;
178 document.getElementById("mapSelector").value = aValue;
181 var throwEv = new CustomEvent("prefs-step");
182 gAction.dispatchEvent(throwEv);
185 gPrefs.get("position", function(aValue) {
186 if (aValue && aValue.x && aValue.y && aValue.z) {
190 var throwEv = new CustomEvent("prefs-step");
191 gAction.dispatchEvent(throwEv);
194 gPrefs.get("center_map", function(aValue) {
195 if (aValue === undefined) {
196 document.getElementById("centerCheckbox").checked = true;
199 document.getElementById("centerCheckbox").checked = aValue;
201 setCentering(document.getElementById("centerCheckbox"));
203 var throwEv = new CustomEvent("prefs-step");
204 gAction.dispatchEvent(throwEv);
207 gPrefs.get("tracking_enabled", function(aValue) {
208 if (aValue === undefined) {
209 document.getElementById("trackCheckbox").checked = true;
212 document.getElementById("trackCheckbox").checked = aValue;
215 var throwEv = new CustomEvent("prefs-step");
216 gAction.dispatchEvent(throwEv);
219 var trackLoadStarted = false;
220 var redrawBase = 100;
221 gTrackStore.getListStepped(function(aTPoint) {
223 // Add in front and return new length.
224 var tracklen = gTrack.unshift(aTPoint);
225 // Redraw track periodically, larger distance the longer it gets
226 // (but clamped to the first value over a certain limit).
227 // Initial paint will do initial track drawing.
228 if (tracklen % redrawBase == 0) {
230 if (redrawBase < 1000) {
231 redrawBase = tracklen;
236 // Last point received.
239 if (!trackLoadStarted) {
240 // We have the most recent point, if present, rest will load async.
241 trackLoadStarted = true;
243 var throwEv = new CustomEvent("prefs-step");
244 gAction.dispatchEvent(throwEv);
252 glShaderProgram: null,
253 glVertexPositionAttr: null,
254 glTextureCoordAttr: null,
255 glResolutionAttr: null,
258 glTxCleanIntervalID: null,
259 glTexturesPerZoomLevel: 0,
261 activeMap: "osm_mapnik",
263 maxZoom: 18, // The minimum is 0.
266 x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
267 y: 23670000.0, // The range is 0-67108864 (2^gMap.maxZoom * gMap.tileSize)
268 z: 5 // This could be fractional if supported being between zoom levels.
270 baseDim: { // Map width, height and tile size in level 18 pixels.
276 get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; },
277 get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; },
279 getVertShaderSource: function() {
280 return 'attribute vec2 aVertexPosition;\n' +
281 'attribute vec2 aTextureCoord;\n\n' +
282 'uniform vec2 uResolution;\n\n' +
283 'varying highp vec2 vTextureCoord;\n\n' +
284 'void main(void) {\n' +
285 // convert the rectangle from pixels to -1.0 to +1.0 (clipspace) 0.0 to 1.0
286 ' vec2 clipSpace = aVertexPosition * 2.0 / uResolution - 1.0;\n' +
287 ' gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' +
288 ' vTextureCoord = aTextureCoord;\n' +
290 getFragShaderSource: function() {
291 return 'varying highp vec2 vTextureCoord;\n\n' +
292 'uniform sampler2D uImage;\n\n' +
293 'void main(void) {\n' +
294 ' gl_FragColor = texture2D(uImage, vTextureCoord);\n' +
298 // When called from the event listener, the "this" reference doesn't work, so use the object name.
299 console.log("Initializing WebGL...");
301 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
302 gMap.gl.clearColor(0.0, 0.0, 0.0, 0.5); // Set clear color to black, fully opaque.
303 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT|gMap.gl.DEPTH_BUFFER_BIT); // Clear the color.
305 // Create and initialize the shaders.
306 console.log("Create and compile shaders...");
307 var vertShader = gMap.gl.createShader(gMap.gl.VERTEX_SHADER);
308 var fragShader = gMap.gl.createShader(gMap.gl.FRAGMENT_SHADER);
309 gMap.gl.shaderSource(vertShader, gMap.getVertShaderSource());
310 // Compile the shader program.
311 gMap.gl.compileShader(vertShader);
312 // See if it compiled successfully.
313 if (!gMap.gl.getShaderParameter(vertShader, gMap.gl.COMPILE_STATUS)) {
314 console.log("An error occurred compiling the vertex shader: " + gMap.gl.getShaderInfoLog(vertShader));
317 gMap.gl.shaderSource(fragShader, gMap.getFragShaderSource());
318 // Compile the shader program.
319 gMap.gl.compileShader(fragShader);
320 // See if it compiled successfully.
321 if (!gMap.gl.getShaderParameter(fragShader, gMap.gl.COMPILE_STATUS)) {
322 console.log("An error occurred compiling the fragment shader: " + gMap.gl.getShaderInfoLog(fragShader));
326 console.log("Create and link shader program...");
327 gMap.glShaderProgram = gMap.gl.createProgram();
328 gMap.gl.attachShader(gMap.glShaderProgram, vertShader);
329 gMap.gl.attachShader(gMap.glShaderProgram, fragShader);
330 gMap.gl.linkProgram(gMap.glShaderProgram);
331 // If creating the shader program failed, alert
332 if (!gMap.gl.getProgramParameter(gMap.glShaderProgram, gMap.gl.LINK_STATUS)) {
333 alert("Unable to initialize the shader program.");
335 gMap.gl.useProgram(gMap.glShaderProgram);
336 // Get locations of the attributes.
337 gMap.glVertexPositionAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aVertexPosition");
338 gMap.glTextureCoordAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aTextureCoord");
339 gMap.glResolutionAttr = gMap.gl.getUniformLocation(gMap.glShaderProgram, "uResolution");
341 console.log("Set up vertex buffer...");
342 var tileVerticesBuffer = gMap.gl.createBuffer();
343 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, tileVerticesBuffer);
344 // The vertices are the coordinates of the corner points of the square.
353 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(vertices), gMap.gl.STATIC_DRAW);
354 gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr);
355 gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0);
357 gMap.loadImageToTexture(gLoadingTile, getTileKey("loading", {x: 0, y: 0, z: 0}));
359 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
361 // Create a buffer for the position of the rectangle corners.
362 console.log("Set up coord buffer...");
363 var mapVerticesTextureCoordBuffer = gMap.gl.createBuffer();
364 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer);
365 gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr);
366 gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0);
368 // Call texture cleaning every 30 seconds, for now (is 60 better?).
369 gMap.glTxCleanIntervalID = window.setInterval(gMap.cleanTextures, 30 * 1000);
373 // We may be called when context was lost and destroyed,
374 // only send event when we are in app startup
375 // (gAppInitDone is set to true right after we return this event).
376 var throwEv = new CustomEvent("mapinit-done");
377 gAction.dispatchEvent(throwEv);
386 assembleGL: function() {
387 if (!gMap.gl) { return; }
389 document.getElementById("zoomLevel").textContent = gMap.pos.z;
390 gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
391 gMap.baseDim.wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor;
392 gMap.baseDim.ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor;
393 gMap.baseDim.tsize = gMap.tileSize * gMap.zoomFactor;
395 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
396 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
397 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
398 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
400 if (gMapPrefsLoaded && mainDB)
401 gPrefs.set("position", gMap.pos);
403 // Go through all the tiles in the map, find out if to draw them and do so.
404 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
405 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
406 // Only go to loading step if we haven't loaded the texture.
407 var coords = {x: x, y: y, z: gMap.pos.z};
408 var tileKey = getTileKey(gMap.activeMap, normalizeCoords(coords));
409 if (!gMap.glTextures[tileKey]) {
410 // Initiate loading/drawing of the actual tile.
411 gTileService.get(gMap.activeMap, coords,
412 function(aImage, aStyle, aCoords, aTileKey) {
413 // Only actually load if this still applies for the current view.
414 if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) {
415 var URL = window.URL;
416 var imgURL = URL.createObjectURL(aImage);
417 var imgObj = new Image();
418 imgObj.onload = function() {
419 gMap.loadImageToTexture(imgObj, aTileKey);
420 if (document.hidden != true) { // Only draw if we're actually visible.
421 window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
423 URL.revokeObjectURL(imgURL);
431 if (document.hidden != true) { // Only draw if we're actually visible.
432 window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
437 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
438 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
439 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
440 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
442 // Go through all the tiles in the map, find out if to draw them and do so.
443 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
444 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
445 // Rounding the pixel offsets ensures we position the tiles precisely.
446 var xoff = Math.round((x * gMap.baseDim.tsize - xMin) / gMap.zoomFactor);
447 var yoff = Math.round((y * gMap.baseDim.tsize - yMin) / gMap.zoomFactor);
448 // Draw the tile, first find out the actual texture to use.
449 var norm = normalizeCoords({x: x, y: y, z: gMap.pos.z});
450 var tileKey = getTileKey(gMap.activeMap, norm);
451 if (!gMap.glTextures[tileKey]) {
452 tileKey = getTileKey("loading", {x: 0, y: 0, z: 0});
454 gMap.drawTileGL(xoff, yoff, tileKey);
459 resizeAndDraw: function() {
460 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
461 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
462 if (gGLMapCanvas && gTrackCanvas) {
463 gGLMapCanvas.width = viewportWidth;
464 gGLMapCanvas.height = viewportHeight;
465 gTrackCanvas.width = viewportWidth;
466 gTrackCanvas.height = viewportHeight;
468 // Size viewport to canvas size.
469 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
471 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT);
472 // Make sure the vertex shader get the right resolution.
473 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
474 // Prepare recalculation of textures to keep for one zoom level.
475 gMap.glTexturesPerZoomLevel = 0;
482 drawTileGL: function(aLeft, aRight, aTileKey) {
483 gMap.gl.activeTexture(gMap.gl.TEXTURE0);
484 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
485 // Set uImage to refer to TEXTURE0
486 gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0);
488 var i_width = gMap.tileSize;
489 var y_start = aRight;
490 var i_height = gMap.tileSize;
491 var textureCoordinates = [
493 x_start + i_width, y_start,
494 x_start, y_start + i_height,
495 x_start, y_start + i_height,
496 x_start + i_width, y_start,
497 x_start + i_width, y_start + i_height,
499 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW);
501 // There are 6 indices in textureCoordinates.
502 gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
505 loadImageToTexture: function(aImage, aTileKey) {
506 // Create and bind texture.
507 gMap.glTextures[aTileKey] = gMap.gl.createTexture();
508 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
509 // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two).
510 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST);
511 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST);
512 // Upload the image into the texture.
513 gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage);
516 cleanTextures: function() {
517 // Get rid of unneeded textures to save memory.
518 // TODO: Be less aggressive, maybe keep neighboring zoom levels (but x/y coords there are zoom-specific).
519 if (!gMap.glTexturesPerZoomLevel) {
520 // Calculate how many textures we need to keep for one zoom level.
521 // ceil(width/size) gives us the minimum, keep one on either side as well.
522 gMap.glTexturesPerZoomLevel =
523 Math.ceil(gMap.gl.drawingBufferWidth / gMap.tileSize + 2) *
524 Math.ceil(gMap.gl.drawingBufferHeight / gMap.tileSize + 2);
525 console.log("Keeping " + gMap.glTexturesPerZoomLevel + " textures per level");
527 if (Object.keys(gMap.glTextures).length > gMap.glTexturesPerZoomLevel) {
528 console.log("Cleaning textures... (have " + Object.keys(gMap.glTextures).length + " atm)");
530 // Find coordinate ranges for tiles to keep.
531 var tMin = normalizeCoords({x: Math.floor((gMap.pos.x - gMap.baseDim.wid / 2) / gMap.baseDim.tsize) - 1,
532 y: Math.floor((gMap.pos.y - gMap.baseDim.ht / 2) / gMap.baseDim.tsize) - 1,
534 var tMax = normalizeCoords({x: Math.ceil((gMap.pos.x + gMap.baseDim.wid / 2) / gMap.baseDim.tsize) + 1,
535 y: Math.ceil((gMap.pos.y + gMap.baseDim.ht / 2) / gMap.baseDim.tsize) + 1,
537 console.log("In range: " + tMin.x + "," + tMin.y + "," + tMin.z + " - " + tMax.x + "," + tMax.y + "," + tMax.z);
538 for (var tileKey in gMap.glTextures) {
539 var keyMatches = tileKey.match(/([^:]+)::(\d+),(\d+),(\d+)/);
540 if (keyMatches && keyMatches[1] != "loading") {
542 style: keyMatches[1],
548 if (txData.style != gMap.activeMap) { delTx = true; console.log("Different map style: " + txData.style); }
549 if (!delTx && (txData.z < tMin.z || txData.z > tMax.z)) { delTx = true; console.log("Out-of-range zoom: " + txData.z); }
550 if (tMin.x < tMax.x) {
551 if (!delTx && (txData.x < tMin.x || txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
554 // We are crossing over the 0 coordinate!
555 if (!delTx && (txData.x < tMin.x && txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
557 if (tMin.y < tMax.y) {
558 if (!delTx && (txData.y < tMin.y || txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
561 // We are crossing over the 0 coordinate!
562 if (!delTx && (txData.y < tMin.y && txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
565 // Delete texture from GL and from the array we are holding.
566 gMap.gl.deleteTexture(gMap.glTextures[tileKey]);
567 delete gMap.glTextures[tileKey];
571 console.log("Cleaning complete, " + Object.keys(gMap.glTextures).length + " textures left)");
575 handleContextLost: function(event) {
576 event.preventDefault();
577 // GL context is gone, let's reset everything that depends on it.
578 clearInterval(gMap.glTxCleanIntervalID);
579 gMap.glTextures = {};
582 handleContextRestored: function(event) {
583 // When GL context is back, init GL again and draw.
589 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
590 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
593 if (gMap.pos.z < gMap.maxZoom) {
600 if (gMap.pos.z > 0) {
606 function zoomTo(aTargetLevel) {
607 aTargetLevel = parseInt(aTargetLevel);
608 if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) {
609 gMap.pos.z = aTargetLevel;
614 function gps2xy(aLatitude, aLongitude) {
615 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
616 var convLat = aLatitude * Math.PI / 180;
617 var rawY = (1 - Math.log(Math.tan(convLat) +
618 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
619 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
620 return {x: Math.round(rawX),
621 y: Math.round(rawY)};
624 function xy2gps(aX, aY) {
625 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
626 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
627 return {latitude: 180 / Math.PI *
628 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
629 longitude: aX / maxZoomFactor * 360 - 180};
632 function setMapStyle() {
633 var mapSel = document.getElementById("mapSelector");
634 if (!gWaitCounter && mapSel.selectedIndex >= 0 && gMap.activeMap != mapSel.value) {
635 gMap.activeMap = mapSel.value;
636 gPrefs.set("active_map_style", gMap.activeMap);
637 document.getElementById("copyright").innerHTML =
638 gMapStyles[gMap.activeMap].copyright;
644 // A sane mod function that works for negative numbers.
647 return ((a % b) + b) % b;
650 function normalizeCoords(aCoords) {
651 var zoomFactor = Math.pow(2, aCoords.z);
652 return {x: mod(aCoords.x, zoomFactor),
653 y: mod(aCoords.y, zoomFactor),
657 function getTileKey(aStyle, aNormalizedCoords) {
658 return aStyle + "::" +
659 aNormalizedCoords.x + "," +
660 aNormalizedCoords.y + "," +
664 // Returns true if the tile is outside the current view.
665 function isOutsideWindow(t) {
666 var pos = decodeIndex(t);
668 var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z);
669 var wid = gMap.width * zoomFactor;
670 var ht = gMap.height * zoomFactor;
675 var sz = gMap.tileSize * zoomFactor;
676 if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 ||
677 pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2)
682 function encodeIndex(x, y, z) {
683 var norm = normalizeCoords({x: x, y: y, z: z});
684 return norm.x + "," + norm.y + "," + norm.z;
687 function decodeIndex(encodedIdx) {
688 var ind = encodedIdx.split(",", 3);
689 return {x: ind[0], y: ind[1], z: ind[2]};
692 function drawTrack() {
693 if (gTrackContext && (document.hidden != true)) { // Only draw if we're actually visible.
694 gLastDrawnPoint = null;
695 gCurPosMapCache = undefined;
696 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
698 for (var i = 0; i < gTrack.length; i++) {
699 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
700 (i + 1 >= gTrack.length || gTrack[i+1].beginSegment));
706 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
707 var trackpoint = gps2xy(aLatitude, aLongitude);
708 // lastPoint is for optimizing (not actually executing the draw until the last)
709 trackpoint.optimized = (lastPoint === false);
710 var mappos = {x: Math.round((trackpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
711 y: Math.round((trackpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
713 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
714 gTrackContext.strokeStyle = gTrackColor;
715 gTrackContext.fillStyle = gTrackContext.strokeStyle;
716 gTrackContext.lineWidth = gTrackWidth;
717 gTrackContext.lineCap = "round";
718 gTrackContext.lineJoin = "round";
720 // This breaks optimiziation, so make sure to reset optimization.
721 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
722 trackpoint.optimized = false;
723 // Close path if one was open.
724 if (gLastDrawnPoint && gLastDrawnPoint.optimized) {
725 gTrackContext.stroke();
728 if (!gLastDrawnPoint || (gLastDrawnPoint == trackpoint) || !gLastDrawnPoint.optimized) {
729 // Start drawing a segment.
730 gTrackContext.beginPath();
731 gTrackContext.arc(mappos.x, mappos.y,
732 gTrackContext.lineWidth, 0, Math.PI * 2, false);
733 gTrackContext.fill();
736 // Continue drawing segment, close if needed.
737 gTrackContext.lineTo(mappos.x, mappos.y);
738 if (!trackpoint.optimized)
739 gTrackContext.stroke();
741 gLastDrawnPoint = trackpoint;
744 function drawCurrentLocation(trackPoint) {
745 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
746 var circleRadius = Math.round(gCurLocSize / 2);
747 var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
748 y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
750 undrawCurrentLocation();
752 // Cache overdrawn area.
755 radius: circleRadius,
756 data: gTrackContext.getImageData(mappos.x - circleRadius,
757 mappos.y - circleRadius,
758 circleRadius * 2, circleRadius * 2)};
760 gTrackContext.strokeStyle = gCurLocColor;
761 gTrackContext.fillStyle = gTrackContext.strokeStyle;
762 gTrackContext.beginPath();
763 gTrackContext.arc(mappos.x, mappos.y,
764 circleRadius, 0, Math.PI * 2, false);
765 gTrackContext.fill();
768 function undrawCurrentLocation() {
769 if (gCurPosMapCache) {
770 var oldpoint = gCurPosMapCache.point;
771 var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
772 y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
773 gTrackContext.putImageData(gCurPosMapCache.data,
774 oldmp.x - gCurPosMapCache.radius,
775 oldmp.y - gCurPosMapCache.radius);
776 gCurPosMapCache = undefined;
780 function calcTrackDuration() {
781 // Get the duration of the track in s.
783 if (gTrack.length > 1) {
784 for (var i = 1; i < gTrack.length; i++) {
785 if (!gTrack[i].beginSegment) {
786 tDuration += (gTrack[i].time - gTrack[i-1].time);
790 return Math.round(tDuration / 1000); // The timestamps are in ms but we return seconds.
793 function calcTrackLength() {
794 // Get the length of the track in km.
796 if (gTrack.length > 1) {
797 for (var i = 1; i < gTrack.length; i++) {
798 if (!gTrack[i].beginSegment) {
799 tLength += getPointDistance(gTrack[i-1].coords, gTrack[i].coords);
806 function getPointDistance(aGPSPoint1, aGPSPoint2) {
807 // Get the distance in km between the two given GPS points.
808 // See http://stackoverflow.com/questions/365826/calculate-distance-between-2-gps-coordinates
809 // Earth is almost exactly a sphere and we calculate small distances on the surface, so we can do spherical great-circle math.
810 // Also see http://en.wikipedia.org/wiki/Great-circle_distance
812 var dLat = deg2rad(aGPSPoint2.latitude - aGPSPoint1.latitude);
813 var dLon = deg2rad(aGPSPoint2.longitude - aGPSPoint1.longitude);
814 var lat1 = deg2rad(aGPSPoint1.latitude);
815 var lat2 = deg2rad(aGPSPoint2.latitude);
817 var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
818 Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
819 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
823 function deg2rad(aDegreeValue) {
824 // Convert an angle in degrees to radiants.
825 return aDegreeValue * (Math.PI / 180);
829 handleEvent: function(aEvent) {
830 var touchEvent = aEvent.type.indexOf('touch') != -1;
833 aEvent.stopPropagation();
836 // Bail out if the event is happening on an input.
837 if (aEvent.target.tagName.toLowerCase() == "input")
840 // Bail out on unwanted map moves, but not zoom or keyboard events.
841 if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
842 // Bail out if this is neither a touch nor left-click.
843 if (!touchEvent && aEvent.button != 0)
846 // Bail out if the started touch can't be found.
847 if (touchEvent && gDragging &&
848 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
852 var coordObj = touchEvent ?
853 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
856 switch (aEvent.type) {
860 if (aEvent.targetTouches.length == 2) {
861 gPinchStartWidth = Math.sqrt(
862 Math.pow(aEvent.targetTouches.item(1).clientX -
863 aEvent.targetTouches.item(0).clientX, 2) +
864 Math.pow(aEvent.targetTouches.item(1).clientY -
865 aEvent.targetTouches.item(0).clientY, 2)
868 gDragTouchID = aEvent.changedTouches.item(0).identifier;
869 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
871 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
872 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
874 if (touchEvent || aEvent.button === 0) {
883 if (touchEvent && aEvent.targetTouches.length == 2) {
884 curPinchStartWidth = Math.sqrt(
885 Math.pow(aEvent.targetTouches.item(1).clientX -
886 aEvent.targetTouches.item(0).clientX, 2) +
887 Math.pow(aEvent.targetTouches.item(1).clientY -
888 aEvent.targetTouches.item(0).clientY, 2)
890 if (!gPinchStartWidth)
891 gPinchStartWidth = curPinchStartWidth;
893 if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
894 gPinchStartWidth / curPinchStartWidth < 0.6) {
895 var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
896 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
897 // Calculate new center of the map - preserve middle of pinch.
898 // This means that pixel distance between old center and middle
899 // must equal pixel distance of new center and middle.
900 var x = (aEvent.targetTouches.item(1).clientX +
901 aEvent.targetTouches.item(0).clientX) / 2 -
902 gGLMapCanvas.offsetLeft;
903 var y = (aEvent.targetTouches.item(1).clientY +
904 aEvent.targetTouches.item(0).clientY) / 2 -
905 gGLMapCanvas.offsetTop;
907 // Zoom factor after this action.
908 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
909 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
910 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
912 if (gPinchStartWidth < curPinchStartWidth)
917 // Reset pinch start width and start another pinch gesture.
918 gPinchStartWidth = null;
921 // If we are in a pinch, do not drag.
924 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
925 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
926 if (gDragging === true) {
927 var dX = x - gLastMouseX;
928 var dY = y - gLastMouseY;
929 gMap.pos.x -= dX * gMap.zoomFactor;
930 gMap.pos.y -= dY * gMap.zoomFactor;
939 gPinchStartWidth = null;
949 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
950 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
952 // Only accept (non-null) deltaY values
956 // Debug output: "coordinates" of the point the mouse was over.
958 var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor,
959 y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor};
960 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
961 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
962 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
963 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
964 pt2Coord.x + "/" + pt2Coord.y);
967 var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1);
968 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
969 // Calculate new center of the map - same point stays under the mouse.
970 // This means that the pixel distance between the old center and point
971 // must equal the pixel distance of the new center and that point.
972 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
973 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
975 // Zoom factor after this action.
976 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
977 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
978 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
980 if (aEvent.deltaY < 0)
987 // Allow keyboard control to move and zoom the map.
988 // Should use aEvent.key instead of aEvent.which but needs bug 680830.
989 // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
992 switch (aEvent.which) {
994 dX = -gMap.tileSize / 2;
997 dX = gMap.tileSize / 2;
1000 dY = gMap.tileSize / 2;
1003 dY = -gMap.tileSize / 2;
1006 case 107: // + (numpad)
1007 case 171: // + (normal key)
1011 case 109: // - (numpad)
1012 case 173: // - (normal key)
1024 zoomTo(aEvent.which - 38);
1029 case 96: // 0 (numpad)
1030 case 97: // 1 (numpad)
1031 case 98: // 2 (numpad)
1032 case 99: // 3 (numpad)
1033 case 100: // 4 (numpad)
1034 case 101: // 5 (numpad)
1035 case 102: // 6 (numpad)
1036 case 103: // 7 (numpad)
1037 case 104: // 8 (numpad)
1038 zoomTo(aEvent.which - 86);
1040 case 105: // 9 (numpad)
1043 default: // not supported
1044 console.log("key not supported: " + aEvent.which);
1050 gMap.pos.x -= dX * gMap.zoomFactor;
1051 gMap.pos.y -= dY * gMap.zoomFactor;
1059 function visibilityEvHandler() {
1060 // Immediately draw if we just got visible.
1061 if (document.hidden != true) {
1064 // No need to handle the event where we become invisible as we care only draw
1065 // when we are visible anyhow.
1070 lastPos: {x: undefined, y: undefined},
1071 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
1072 this.tracking = true;
1073 var watchCall = function() {
1074 // calc new position in lat/lon degrees
1075 // 90° on Earth surface are ~10,000 km at the equator,
1076 // so try moving at most 10m at a time
1077 if (geofake.lastPos.x)
1078 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
1080 geofake.lastPos.x = 48.208174
1081 if (geofake.lastPos.y)
1082 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
1084 geofake.lastPos.y = 16.373819
1085 aSuccessCallback({timestamp: Date.now(),
1086 coords: {latitude: geofake.lastPos.x,
1087 longitude: geofake.lastPos.y,
1089 if (geofake.tracking)
1090 setTimeout(watchCall, 1000);
1092 setTimeout(watchCall, 1000);
1095 clearWatch: function(aID) {
1096 this.tracking = false;
1100 function setCentering(aCheckbox) {
1101 if (gMapPrefsLoaded && mainDB)
1102 gPrefs.set("center_map", aCheckbox.checked);
1103 gCenterPosition = aCheckbox.checked;
1106 function setTracking(aCheckbox) {
1107 if (gMapPrefsLoaded && mainDB)
1108 gPrefs.set("tracking_enabled", aCheckbox.checked);
1109 if (aCheckbox.checked)
1115 function startTracking() {
1117 gActionLabel.textContent = "Establishing Position";
1118 gAction.style.display = "block";
1119 gGeoWatchID = gGeolocation.watchPosition(
1120 function(position) {
1121 if (gActionLabel.textContent) {
1122 gActionLabel.textContent = "";
1123 gAction.style.display = "none";
1125 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
1126 var tPoint = {time: position.timestamp,
1127 coords: {latitude: position.coords.latitude,
1128 longitude: position.coords.longitude,
1129 altitude: position.coords.altitude,
1130 accuracy: position.coords.accuracy,
1131 altitudeAccuracy: position.coords.altitudeAccuracy,
1132 heading: position.coords.heading,
1133 speed: position.coords.speed},
1134 beginSegment: !gLastTrackPoint};
1135 // Only add point to track is accuracy is good enough.
1136 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
1137 gLastTrackPoint = tPoint;
1138 gTrack.push(tPoint);
1139 try { gTrackStore.push(tPoint); } catch(e) {}
1140 var redrawn = false;
1141 if (gCenterPosition) {
1142 var posCoord = gps2xy(position.coords.latitude,
1143 position.coords.longitude);
1144 if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 ||
1145 Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) {
1146 gMap.pos.x = posCoord.x;
1147 gMap.pos.y = posCoord.y;
1148 gMap.draw(); // This draws the current point as well.
1153 undrawCurrentLocation();
1154 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
1156 drawCurrentLocation(tPoint);
1159 // Ignore erros for the moment, but this is good for debugging.
1160 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
1162 console.log(error.message);
1164 {enableHighAccuracy: true}
1169 function endTracking() {
1170 if (gActionLabel.textContent) {
1171 gActionLabel.textContent = "";
1172 gAction.style.display = "none";
1175 gGeolocation.clearWatch(gGeoWatchID);
1179 function clearTrack() {
1181 gTrackStore.clear();
1185 var gTileService = {
1186 objStore: "tilecache",
1188 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
1190 get: function(aStyle, aCoords, aCallback) {
1191 var norm = normalizeCoords(aCoords);
1192 var dbkey = getTileKey(aStyle, norm);
1193 this.getDBCache(dbkey, function(aResult, aEvent) {
1195 // We did get a cached object.
1196 aCallback(aResult.image, aStyle, aCoords, dbkey);
1197 // Look at the timestamp and return if it's not too old.
1198 if (aResult.timestamp + gTileService.ageLimit > Date.now())
1200 // Reload cached tile otherwise.
1201 var oldDate = new Date(aResult.timestamp);
1202 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
1204 // Retrieve image from the web and store it in the cache.
1205 var XHR = new XMLHttpRequest();
1207 gMapStyles[aStyle].url
1208 .replace("{x}", norm.x)
1209 .replace("{y}", norm.y)
1210 .replace("{z}", norm.z)
1211 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 3)))
1212 .replace("[a-d]", String.fromCharCode(97 + Math.floor(Math.random() * 4)))
1213 .replace("[1-4]", 1 + Math.floor(Math.random() * 4)),
1215 XHR.responseType = "blob";
1216 XHR.addEventListener("load", function () {
1217 if (XHR.status === 200) {
1218 var blob = XHR.response;
1219 aCallback(blob, aStyle, aCoords, dbkey);
1220 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
1227 getDBCache: function(aKey, aCallback) {
1230 var transaction = mainDB.transaction([this.objStore]);
1231 var request = transaction.objectStore(this.objStore).get(aKey);
1232 request.onsuccess = function(event) {
1233 aCallback(request.result, event);
1235 request.onerror = function(event) {
1236 // Errors can be handled here.
1237 aCallback(undefined, event);
1241 setDBCache: function(aKey, aValue, aCallback) {
1244 var success = false;
1245 var transaction = mainDB.transaction([this.objStore], "readwrite");
1246 var objStore = transaction.objectStore(this.objStore);
1247 var request = objStore.put(aValue, aKey);
1248 request.onsuccess = function(event) {
1251 aCallback(success, event);
1253 request.onerror = function(event) {
1254 // Errors can be handled here.
1256 aCallback(success, event);
1260 unsetDBCache: function(aKey, aCallback) {
1263 var success = false;
1264 var transaction = mainDB.transaction([this.objStore], "readwrite");
1265 var request = transaction.objectStore(this.objStore).delete(aKey);
1266 request.onsuccess = function(event) {
1269 aCallback(success, event);
1271 request.onerror = function(event) {
1272 // Errors can be handled here.
1274 aCallback(success, event);
1278 clearDB: function(aCallback) {
1281 var success = false;
1282 var transaction = mainDB.transaction([this.objStore], "readwrite");
1283 var request = transaction.objectStore(this.objStore).clear();
1284 request.onsuccess = function(event) {
1287 aCallback(success, event);
1289 request.onerror = function(event) {
1290 // Errors can be handled here.
1292 aCallback(success, event);