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("position", function(aValue) {
176 if (aValue && aValue.x && aValue.y && aValue.z) {
180 var throwEv = new CustomEvent("prefs-step");
181 gAction.dispatchEvent(throwEv);
184 gPrefs.get("center_map", function(aValue) {
185 if (aValue === undefined)
186 document.getElementById("centerCheckbox").checked = true;
188 document.getElementById("centerCheckbox").checked = aValue;
189 setCentering(document.getElementById("centerCheckbox"));
191 var throwEv = new CustomEvent("prefs-step");
192 gAction.dispatchEvent(throwEv);
195 gPrefs.get("tracking_enabled", function(aValue) {
196 if (aValue === undefined)
197 document.getElementById("trackCheckbox").checked = true;
199 document.getElementById("trackCheckbox").checked = aValue;
201 var throwEv = new CustomEvent("prefs-step");
202 gAction.dispatchEvent(throwEv);
205 var trackLoadStarted = false;
206 var redrawBase = 100;
207 gTrackStore.getListStepped(function(aTPoint) {
209 // Add in front and return new length.
210 var tracklen = gTrack.unshift(aTPoint);
211 // Redraw track periodically, larger distance the longer it gets
212 // (but clamped to the first value over a certain limit).
213 // Initial paint will do initial track drawing.
214 if (tracklen % redrawBase == 0) {
216 if (redrawBase < 1000) {
217 redrawBase = tracklen;
222 // Last point received.
225 if (!trackLoadStarted) {
226 // We have the most recent point, if present, rest will load async.
227 trackLoadStarted = true;
229 var throwEv = new CustomEvent("prefs-step");
230 gAction.dispatchEvent(throwEv);
238 glShaderProgram: null,
239 glVertexPositionAttr: null,
240 glTextureCoordAttr: null,
241 glResolutionAttr: null,
244 glTxCleanIntervalID: null,
245 glTexturesPerZoomLevel: 0,
247 activeMap: "osm_mapnik",
249 maxZoom: 18, // The minimum is 0.
252 x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
253 y: 23670000.0, // The range is 0-67108864 (2^gMap.maxZoom * gMap.tileSize)
254 z: 5 // This could be fractional if supported being between zoom levels.
256 baseDim: { // Map width, height and tile size in level 18 pixels.
262 get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; },
263 get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; },
265 getVertShaderSource: function() {
266 return 'attribute vec2 aVertexPosition;\n' +
267 'attribute vec2 aTextureCoord;\n\n' +
268 'uniform vec2 uResolution;\n\n' +
269 'varying highp vec2 vTextureCoord;\n\n' +
270 'void main(void) {\n' +
271 // convert the rectangle from pixels to -1.0 to +1.0 (clipspace) 0.0 to 1.0
272 ' vec2 clipSpace = aVertexPosition * 2.0 / uResolution - 1.0;\n' +
273 ' gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' +
274 ' vTextureCoord = aTextureCoord;\n' +
276 getFragShaderSource: function() {
277 return 'varying highp vec2 vTextureCoord;\n\n' +
278 'uniform sampler2D uImage;\n\n' +
279 'void main(void) {\n' +
280 ' gl_FragColor = texture2D(uImage, vTextureCoord);\n' +
284 // When called from the event listener, the "this" reference doesn't work, so use the object name.
285 console.log("Initializing WebGL...");
287 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
288 gMap.gl.clearColor(0.0, 0.0, 0.0, 0.5); // Set clear color to black, fully opaque.
289 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT|gMap.gl.DEPTH_BUFFER_BIT); // Clear the color.
291 // Create and initialize the shaders.
292 console.log("Create and compile shaders...");
293 var vertShader = gMap.gl.createShader(gMap.gl.VERTEX_SHADER);
294 var fragShader = gMap.gl.createShader(gMap.gl.FRAGMENT_SHADER);
295 gMap.gl.shaderSource(vertShader, gMap.getVertShaderSource());
296 // Compile the shader program.
297 gMap.gl.compileShader(vertShader);
298 // See if it compiled successfully.
299 if (!gMap.gl.getShaderParameter(vertShader, gMap.gl.COMPILE_STATUS)) {
300 console.log("An error occurred compiling the vertex shader: " + gMap.gl.getShaderInfoLog(vertShader));
303 gMap.gl.shaderSource(fragShader, gMap.getFragShaderSource());
304 // Compile the shader program.
305 gMap.gl.compileShader(fragShader);
306 // See if it compiled successfully.
307 if (!gMap.gl.getShaderParameter(fragShader, gMap.gl.COMPILE_STATUS)) {
308 console.log("An error occurred compiling the fragment shader: " + gMap.gl.getShaderInfoLog(fragShader));
312 console.log("Create and link shader program...");
313 gMap.glShaderProgram = gMap.gl.createProgram();
314 gMap.gl.attachShader(gMap.glShaderProgram, vertShader);
315 gMap.gl.attachShader(gMap.glShaderProgram, fragShader);
316 gMap.gl.linkProgram(gMap.glShaderProgram);
317 // If creating the shader program failed, alert
318 if (!gMap.gl.getProgramParameter(gMap.glShaderProgram, gMap.gl.LINK_STATUS)) {
319 alert("Unable to initialize the shader program.");
321 gMap.gl.useProgram(gMap.glShaderProgram);
322 // Get locations of the attributes.
323 gMap.glVertexPositionAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aVertexPosition");
324 gMap.glTextureCoordAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aTextureCoord");
325 gMap.glResolutionAttr = gMap.gl.getUniformLocation(gMap.glShaderProgram, "uResolution");
327 console.log("Set up vertex buffer...");
328 var tileVerticesBuffer = gMap.gl.createBuffer();
329 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, tileVerticesBuffer);
330 // The vertices are the coordinates of the corner points of the square.
339 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(vertices), gMap.gl.STATIC_DRAW);
340 gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr);
341 gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0);
343 gMap.loadImageToTexture(gLoadingTile, getTileKey("loading", {x: 0, y: 0, z: 0}));
345 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
347 // Create a buffer for the position of the rectangle corners.
348 console.log("Set up coord buffer...");
349 var mapVerticesTextureCoordBuffer = gMap.gl.createBuffer();
350 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer);
351 gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr);
352 gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0);
354 // Call texture cleaning every 30 seconds, for now (is 60 better?).
355 gMap.glTxCleanIntervalID = window.setInterval(gMap.cleanTextures, 30 * 1000);
359 // We may be called when context was lost and destroyed,
360 // only send event when we are in app startup
361 // (gAppInitDone is set to true right after we return this event).
362 var throwEv = new CustomEvent("mapinit-done");
363 gAction.dispatchEvent(throwEv);
372 assembleGL: function() {
373 if (!gMap.gl) { return; }
375 document.getElementById("zoomLevel").textContent = gMap.pos.z;
376 gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
377 gMap.baseDim.wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor;
378 gMap.baseDim.ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor;
379 gMap.baseDim.tsize = gMap.tileSize * gMap.zoomFactor;
381 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
382 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
383 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
384 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
386 if (gMapPrefsLoaded && mainDB)
387 gPrefs.set("position", gMap.pos);
389 // Go through all the tiles in the map, find out if to draw them and do so.
390 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
391 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
392 // Only go to loading step if we haven't loaded the texture.
393 var coords = {x: x, y: y, z: gMap.pos.z};
394 var tileKey = getTileKey(gMap.activeMap, normalizeCoords(coords));
395 if (!gMap.glTextures[tileKey]) {
396 // Initiate loading/drawing of the actual tile.
397 gTileService.get(gMap.activeMap, coords,
398 function(aImage, aStyle, aCoords, aTileKey) {
399 // Only actually load if this still applies for the current view.
400 if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) {
401 var URL = window.URL;
402 var imgURL = URL.createObjectURL(aImage);
403 var imgObj = new Image();
404 imgObj.onload = function() {
405 gMap.loadImageToTexture(imgObj, aTileKey);
406 if (document.hidden != true) { // Only draw if we're actually visible.
407 window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
409 URL.revokeObjectURL(imgURL);
417 if (document.hidden != true) { // Only draw if we're actually visible.
418 window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
423 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
424 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
425 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
426 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
428 // Go through all the tiles in the map, find out if to draw them and do so.
429 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
430 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
431 // Rounding the pixel offsets ensures we position the tiles precisely.
432 var xoff = Math.round((x * gMap.baseDim.tsize - xMin) / gMap.zoomFactor);
433 var yoff = Math.round((y * gMap.baseDim.tsize - yMin) / gMap.zoomFactor);
434 // Draw the tile, first find out the actual texture to use.
435 var norm = normalizeCoords({x: x, y: y, z: gMap.pos.z});
436 var tileKey = getTileKey(gMap.activeMap, norm);
437 if (!gMap.glTextures[tileKey]) {
438 tileKey = getTileKey("loading", {x: 0, y: 0, z: 0});
440 gMap.drawTileGL(xoff, yoff, tileKey);
445 resizeAndDraw: function() {
446 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
447 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
448 if (gGLMapCanvas && gTrackCanvas) {
449 gGLMapCanvas.width = viewportWidth;
450 gGLMapCanvas.height = viewportHeight;
451 gTrackCanvas.width = viewportWidth;
452 gTrackCanvas.height = viewportHeight;
454 // Size viewport to canvas size.
455 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
457 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT);
458 // Make sure the vertex shader get the right resolution.
459 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
460 // Prepare recalculation of textures to keep for one zoom level.
461 gMap.glTexturesPerZoomLevel = 0;
468 drawTileGL: function(aLeft, aRight, aTileKey) {
469 gMap.gl.activeTexture(gMap.gl.TEXTURE0);
470 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
471 // Set uImage to refer to TEXTURE0
472 gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0);
474 var i_width = gMap.tileSize;
475 var y_start = aRight;
476 var i_height = gMap.tileSize;
477 var textureCoordinates = [
479 x_start + i_width, y_start,
480 x_start, y_start + i_height,
481 x_start, y_start + i_height,
482 x_start + i_width, y_start,
483 x_start + i_width, y_start + i_height,
485 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW);
487 // There are 6 indices in textureCoordinates.
488 gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
491 loadImageToTexture: function(aImage, aTileKey) {
492 // Create and bind texture.
493 gMap.glTextures[aTileKey] = gMap.gl.createTexture();
494 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
495 // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two).
496 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST);
497 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST);
498 // Upload the image into the texture.
499 gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage);
502 cleanTextures: function() {
503 // Get rid of unneeded textures to save memory.
504 // TODO: Be less aggressive, maybe keep neighboring zoom levels (but x/y coords there are zoom-specific).
505 if (!gMap.glTexturesPerZoomLevel) {
506 // Calculate how many textures we need to keep for one zoom level.
507 // ceil(width/size) gives us the minimum, keep one on either side as well.
508 gMap.glTexturesPerZoomLevel =
509 Math.ceil(gMap.gl.drawingBufferWidth / gMap.tileSize + 2) *
510 Math.ceil(gMap.gl.drawingBufferHeight / gMap.tileSize + 2);
511 console.log("Keeping " + gMap.glTexturesPerZoomLevel + " textures per level");
513 if (Object.keys(gMap.glTextures).length > gMap.glTexturesPerZoomLevel) {
514 console.log("Cleaning textures... (have " + Object.keys(gMap.glTextures).length + " atm)");
516 // Find coordinate ranges for tiles to keep.
517 var tMin = normalizeCoords({x: Math.floor((gMap.pos.x - gMap.baseDim.wid / 2) / gMap.baseDim.tsize) - 1,
518 y: Math.floor((gMap.pos.y - gMap.baseDim.ht / 2) / gMap.baseDim.tsize) - 1,
520 var tMax = normalizeCoords({x: Math.ceil((gMap.pos.x + gMap.baseDim.wid / 2) / gMap.baseDim.tsize) + 1,
521 y: Math.ceil((gMap.pos.y + gMap.baseDim.ht / 2) / gMap.baseDim.tsize) + 1,
523 console.log("In range: " + tMin.x + "," + tMin.y + "," + tMin.z + " - " + tMax.x + "," + tMax.y + "," + tMax.z);
524 for (var tileKey in gMap.glTextures) {
525 var keyMatches = tileKey.match(/([^:]+)::(\d+),(\d+),(\d+)/);
526 if (keyMatches && keyMatches[1] != "loading") {
528 style: keyMatches[1],
534 if (txData.style != gMap.activeMap) { delTx = true; console.log("Different map style: " + txData.style); }
535 if (!delTx && (txData.z < tMin.z || txData.z > tMax.z)) { delTx = true; console.log("Out-of-range zoom: " + txData.z); }
536 if (tMin.x < tMax.x) {
537 if (!delTx && (txData.x < tMin.x || txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
540 // We are crossing over the 0 coordinate!
541 if (!delTx && (txData.x < tMin.x && txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
543 if (tMin.y < tMax.y) {
544 if (!delTx && (txData.y < tMin.y || txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
547 // We are crossing over the 0 coordinate!
548 if (!delTx && (txData.y < tMin.y && txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
551 // Delete texture from GL and from the array we are holding.
552 gMap.gl.deleteTexture(gMap.glTextures[tileKey]);
553 delete gMap.glTextures[tileKey];
557 console.log("Cleaning complete, " + Object.keys(gMap.glTextures).length + " textures left)");
561 handleContextLost: function(event) {
562 event.preventDefault();
563 // GL context is gone, let's reset everything that depends on it.
564 clearInterval(gMap.glTxCleanIntervalID);
565 gMap.glTextures = {};
568 handleContextRestored: function(event) {
569 // When GL context is back, init GL again and draw.
575 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
576 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
579 if (gMap.pos.z < gMap.maxZoom) {
586 if (gMap.pos.z > 0) {
592 function zoomTo(aTargetLevel) {
593 aTargetLevel = parseInt(aTargetLevel);
594 if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) {
595 gMap.pos.z = aTargetLevel;
600 function gps2xy(aLatitude, aLongitude) {
601 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
602 var convLat = aLatitude * Math.PI / 180;
603 var rawY = (1 - Math.log(Math.tan(convLat) +
604 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
605 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
606 return {x: Math.round(rawX),
607 y: Math.round(rawY)};
610 function xy2gps(aX, aY) {
611 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
612 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
613 return {latitude: 180 / Math.PI *
614 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
615 longitude: aX / maxZoomFactor * 360 - 180};
618 function setMapStyle() {
619 var mapSel = document.getElementById("mapSelector");
620 if (mapSel.selectedIndex >= 0 && gMap.activeMap != mapSel.value) {
621 gMap.activeMap = mapSel.value;
622 document.getElementById("copyright").innerHTML =
623 gMapStyles[gMap.activeMap].copyright;
629 // A sane mod function that works for negative numbers.
632 return ((a % b) + b) % b;
635 function normalizeCoords(aCoords) {
636 var zoomFactor = Math.pow(2, aCoords.z);
637 return {x: mod(aCoords.x, zoomFactor),
638 y: mod(aCoords.y, zoomFactor),
642 function getTileKey(aStyle, aNormalizedCoords) {
643 return aStyle + "::" +
644 aNormalizedCoords.x + "," +
645 aNormalizedCoords.y + "," +
649 // Returns true if the tile is outside the current view.
650 function isOutsideWindow(t) {
651 var pos = decodeIndex(t);
653 var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z);
654 var wid = gMap.width * zoomFactor;
655 var ht = gMap.height * zoomFactor;
660 var sz = gMap.tileSize * zoomFactor;
661 if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 ||
662 pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2)
667 function encodeIndex(x, y, z) {
668 var norm = normalizeCoords({x: x, y: y, z: z});
669 return norm.x + "," + norm.y + "," + norm.z;
672 function decodeIndex(encodedIdx) {
673 var ind = encodedIdx.split(",", 3);
674 return {x: ind[0], y: ind[1], z: ind[2]};
677 function drawTrack() {
678 if (gTrackContext && (document.hidden != true)) { // Only draw if we're actually visible.
679 gLastDrawnPoint = null;
680 gCurPosMapCache = undefined;
681 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
683 for (var i = 0; i < gTrack.length; i++) {
684 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
685 (i + 1 >= gTrack.length || gTrack[i+1].beginSegment));
691 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
692 var trackpoint = gps2xy(aLatitude, aLongitude);
693 // lastPoint is for optimizing (not actually executing the draw until the last)
694 trackpoint.optimized = (lastPoint === false);
695 var mappos = {x: Math.round((trackpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
696 y: Math.round((trackpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
698 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
699 gTrackContext.strokeStyle = gTrackColor;
700 gTrackContext.fillStyle = gTrackContext.strokeStyle;
701 gTrackContext.lineWidth = gTrackWidth;
702 gTrackContext.lineCap = "round";
703 gTrackContext.lineJoin = "round";
705 // This breaks optimiziation, so make sure to reset optimization.
706 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
707 trackpoint.optimized = false;
708 // Close path if one was open.
709 if (gLastDrawnPoint && gLastDrawnPoint.optimized) {
710 gTrackContext.stroke();
713 if (!gLastDrawnPoint || (gLastDrawnPoint == trackpoint) || !gLastDrawnPoint.optimized) {
714 // Start drawing a segment.
715 gTrackContext.beginPath();
716 gTrackContext.arc(mappos.x, mappos.y,
717 gTrackContext.lineWidth, 0, Math.PI * 2, false);
718 gTrackContext.fill();
721 // Continue drawing segment, close if needed.
722 gTrackContext.lineTo(mappos.x, mappos.y);
723 if (!trackpoint.optimized)
724 gTrackContext.stroke();
726 gLastDrawnPoint = trackpoint;
729 function drawCurrentLocation(trackPoint) {
730 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
731 var circleRadius = Math.round(gCurLocSize / 2);
732 var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
733 y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
735 undrawCurrentLocation();
737 // Cache overdrawn area.
740 radius: circleRadius,
741 data: gTrackContext.getImageData(mappos.x - circleRadius,
742 mappos.y - circleRadius,
743 circleRadius * 2, circleRadius * 2)};
745 gTrackContext.strokeStyle = gCurLocColor;
746 gTrackContext.fillStyle = gTrackContext.strokeStyle;
747 gTrackContext.beginPath();
748 gTrackContext.arc(mappos.x, mappos.y,
749 circleRadius, 0, Math.PI * 2, false);
750 gTrackContext.fill();
753 function undrawCurrentLocation() {
754 if (gCurPosMapCache) {
755 var oldpoint = gCurPosMapCache.point;
756 var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
757 y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
758 gTrackContext.putImageData(gCurPosMapCache.data,
759 oldmp.x - gCurPosMapCache.radius,
760 oldmp.y - gCurPosMapCache.radius);
761 gCurPosMapCache = undefined;
765 function calcTrackDuration() {
766 // Get the duration of the track in s.
768 if (gTrack.length > 1) {
769 for (var i = 1; i < gTrack.length; i++) {
770 if (!gTrack[i].beginSegment) {
771 tDuration += (gTrack[i].time - gTrack[i-1].time);
775 return Math.round(tDuration / 1000); // The timestamps are in ms but we return seconds.
778 function calcTrackLength() {
779 // Get the length of the track in km.
781 if (gTrack.length > 1) {
782 for (var i = 1; i < gTrack.length; i++) {
783 if (!gTrack[i].beginSegment) {
784 tLength += getPointDistance(gTrack[i-1].coords, gTrack[i].coords);
791 function getPointDistance(aGPSPoint1, aGPSPoint2) {
792 // Get the distance in km between the two given GPS points.
793 // See http://stackoverflow.com/questions/365826/calculate-distance-between-2-gps-coordinates
794 // Earth is almost exactly a sphere and we calculate small distances on the surface, so we can do spherical great-circle math.
795 // Also see http://en.wikipedia.org/wiki/Great-circle_distance
797 var dLat = deg2rad(aGPSPoint2.latitude - aGPSPoint1.latitude);
798 var dLon = deg2rad(aGPSPoint2.longitude - aGPSPoint1.longitude);
799 var lat1 = deg2rad(aGPSPoint1.latitude);
800 var lat2 = deg2rad(aGPSPoint2.latitude);
802 var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
803 Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
804 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
808 function deg2rad(aDegreeValue) {
809 // Convert an angle in degrees to radiants.
810 return aDegreeValue * (Math.PI / 180);
814 handleEvent: function(aEvent) {
815 var touchEvent = aEvent.type.indexOf('touch') != -1;
818 aEvent.stopPropagation();
821 // Bail out if the event is happening on an input.
822 if (aEvent.target.tagName.toLowerCase() == "input")
825 // Bail out on unwanted map moves, but not zoom or keyboard events.
826 if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
827 // Bail out if this is neither a touch nor left-click.
828 if (!touchEvent && aEvent.button != 0)
831 // Bail out if the started touch can't be found.
832 if (touchEvent && gDragging &&
833 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
837 var coordObj = touchEvent ?
838 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
841 switch (aEvent.type) {
845 if (aEvent.targetTouches.length == 2) {
846 gPinchStartWidth = Math.sqrt(
847 Math.pow(aEvent.targetTouches.item(1).clientX -
848 aEvent.targetTouches.item(0).clientX, 2) +
849 Math.pow(aEvent.targetTouches.item(1).clientY -
850 aEvent.targetTouches.item(0).clientY, 2)
853 gDragTouchID = aEvent.changedTouches.item(0).identifier;
854 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
856 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
857 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
859 if (touchEvent || aEvent.button === 0) {
868 if (touchEvent && aEvent.targetTouches.length == 2) {
869 curPinchStartWidth = Math.sqrt(
870 Math.pow(aEvent.targetTouches.item(1).clientX -
871 aEvent.targetTouches.item(0).clientX, 2) +
872 Math.pow(aEvent.targetTouches.item(1).clientY -
873 aEvent.targetTouches.item(0).clientY, 2)
875 if (!gPinchStartWidth)
876 gPinchStartWidth = curPinchStartWidth;
878 if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
879 gPinchStartWidth / curPinchStartWidth < 0.6) {
880 var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
881 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
882 // Calculate new center of the map - preserve middle of pinch.
883 // This means that pixel distance between old center and middle
884 // must equal pixel distance of new center and middle.
885 var x = (aEvent.targetTouches.item(1).clientX +
886 aEvent.targetTouches.item(0).clientX) / 2 -
887 gGLMapCanvas.offsetLeft;
888 var y = (aEvent.targetTouches.item(1).clientY +
889 aEvent.targetTouches.item(0).clientY) / 2 -
890 gGLMapCanvas.offsetTop;
892 // Zoom factor after this action.
893 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
894 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
895 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
897 if (gPinchStartWidth < curPinchStartWidth)
902 // Reset pinch start width and start another pinch gesture.
903 gPinchStartWidth = null;
906 // If we are in a pinch, do not drag.
909 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
910 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
911 if (gDragging === true) {
912 var dX = x - gLastMouseX;
913 var dY = y - gLastMouseY;
914 gMap.pos.x -= dX * gMap.zoomFactor;
915 gMap.pos.y -= dY * gMap.zoomFactor;
924 gPinchStartWidth = null;
934 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
935 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
937 // Only accept (non-null) deltaY values
941 // Debug output: "coordinates" of the point the mouse was over.
943 var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor,
944 y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor};
945 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
946 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
947 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
948 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
949 pt2Coord.x + "/" + pt2Coord.y);
952 var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1);
953 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
954 // Calculate new center of the map - same point stays under the mouse.
955 // This means that the pixel distance between the old center and point
956 // must equal the pixel distance of the new center and that point.
957 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
958 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
960 // Zoom factor after this action.
961 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
962 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
963 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
965 if (aEvent.deltaY < 0)
972 // Allow keyboard control to move and zoom the map.
973 // Should use aEvent.key instead of aEvent.which but needs bug 680830.
974 // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
977 switch (aEvent.which) {
979 dX = -gMap.tileSize / 2;
982 dX = gMap.tileSize / 2;
985 dY = gMap.tileSize / 2;
988 dY = -gMap.tileSize / 2;
991 case 107: // + (numpad)
992 case 171: // + (normal key)
996 case 109: // - (numpad)
997 case 173: // - (normal key)
1009 zoomTo(aEvent.which - 38);
1014 case 96: // 0 (numpad)
1015 case 97: // 1 (numpad)
1016 case 98: // 2 (numpad)
1017 case 99: // 3 (numpad)
1018 case 100: // 4 (numpad)
1019 case 101: // 5 (numpad)
1020 case 102: // 6 (numpad)
1021 case 103: // 7 (numpad)
1022 case 104: // 8 (numpad)
1023 zoomTo(aEvent.which - 86);
1025 case 105: // 9 (numpad)
1028 default: // not supported
1029 console.log("key not supported: " + aEvent.which);
1035 gMap.pos.x -= dX * gMap.zoomFactor;
1036 gMap.pos.y -= dY * gMap.zoomFactor;
1044 function visibilityEvHandler() {
1045 // Immediately draw if we just got visible.
1046 if (document.hidden != true) {
1049 // No need to handle the event where we become invisible as we care only draw
1050 // when we are visible anyhow.
1055 lastPos: {x: undefined, y: undefined},
1056 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
1057 this.tracking = true;
1058 var watchCall = function() {
1059 // calc new position in lat/lon degrees
1060 // 90° on Earth surface are ~10,000 km at the equator,
1061 // so try moving at most 10m at a time
1062 if (geofake.lastPos.x)
1063 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
1065 geofake.lastPos.x = 48.208174
1066 if (geofake.lastPos.y)
1067 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
1069 geofake.lastPos.y = 16.373819
1070 aSuccessCallback({timestamp: Date.now(),
1071 coords: {latitude: geofake.lastPos.x,
1072 longitude: geofake.lastPos.y,
1074 if (geofake.tracking)
1075 setTimeout(watchCall, 1000);
1077 setTimeout(watchCall, 1000);
1080 clearWatch: function(aID) {
1081 this.tracking = false;
1085 function setCentering(aCheckbox) {
1086 if (gMapPrefsLoaded && mainDB)
1087 gPrefs.set("center_map", aCheckbox.checked);
1088 gCenterPosition = aCheckbox.checked;
1091 function setTracking(aCheckbox) {
1092 if (gMapPrefsLoaded && mainDB)
1093 gPrefs.set("tracking_enabled", aCheckbox.checked);
1094 if (aCheckbox.checked)
1100 function startTracking() {
1102 gActionLabel.textContent = "Establishing Position";
1103 gAction.style.display = "block";
1104 gGeoWatchID = gGeolocation.watchPosition(
1105 function(position) {
1106 if (gActionLabel.textContent) {
1107 gActionLabel.textContent = "";
1108 gAction.style.display = "none";
1110 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
1111 var tPoint = {time: position.timestamp,
1112 coords: {latitude: position.coords.latitude,
1113 longitude: position.coords.longitude,
1114 altitude: position.coords.altitude,
1115 accuracy: position.coords.accuracy,
1116 altitudeAccuracy: position.coords.altitudeAccuracy,
1117 heading: position.coords.heading,
1118 speed: position.coords.speed},
1119 beginSegment: !gLastTrackPoint};
1120 // Only add point to track is accuracy is good enough.
1121 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
1122 gLastTrackPoint = tPoint;
1123 gTrack.push(tPoint);
1124 try { gTrackStore.push(tPoint); } catch(e) {}
1125 var redrawn = false;
1126 if (gCenterPosition) {
1127 var posCoord = gps2xy(position.coords.latitude,
1128 position.coords.longitude);
1129 if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 ||
1130 Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) {
1131 gMap.pos.x = posCoord.x;
1132 gMap.pos.y = posCoord.y;
1133 gMap.draw(); // This draws the current point as well.
1138 undrawCurrentLocation();
1139 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
1141 drawCurrentLocation(tPoint);
1144 // Ignore erros for the moment, but this is good for debugging.
1145 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
1147 console.log(error.message);
1149 {enableHighAccuracy: true}
1154 function endTracking() {
1155 if (gActionLabel.textContent) {
1156 gActionLabel.textContent = "";
1157 gAction.style.display = "none";
1160 gGeolocation.clearWatch(gGeoWatchID);
1164 function clearTrack() {
1166 gTrackStore.clear();
1170 var gTileService = {
1171 objStore: "tilecache",
1173 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
1175 get: function(aStyle, aCoords, aCallback) {
1176 var norm = normalizeCoords(aCoords);
1177 var dbkey = getTileKey(aStyle, norm);
1178 this.getDBCache(dbkey, function(aResult, aEvent) {
1180 // We did get a cached object.
1181 aCallback(aResult.image, aStyle, aCoords, dbkey);
1182 // Look at the timestamp and return if it's not too old.
1183 if (aResult.timestamp + gTileService.ageLimit > Date.now())
1185 // Reload cached tile otherwise.
1186 var oldDate = new Date(aResult.timestamp);
1187 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
1189 // Retrieve image from the web and store it in the cache.
1190 var XHR = new XMLHttpRequest();
1192 gMapStyles[aStyle].url
1193 .replace("{x}", norm.x)
1194 .replace("{y}", norm.y)
1195 .replace("{z}", norm.z)
1196 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 3)))
1197 .replace("[a-d]", String.fromCharCode(97 + Math.floor(Math.random() * 4)))
1198 .replace("[1-4]", 1 + Math.floor(Math.random() * 4)),
1200 XHR.responseType = "blob";
1201 XHR.addEventListener("load", function () {
1202 if (XHR.status === 200) {
1203 var blob = XHR.response;
1204 aCallback(blob, aStyle, aCoords, dbkey);
1205 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
1212 getDBCache: function(aKey, aCallback) {
1215 var transaction = mainDB.transaction([this.objStore]);
1216 var request = transaction.objectStore(this.objStore).get(aKey);
1217 request.onsuccess = function(event) {
1218 aCallback(request.result, event);
1220 request.onerror = function(event) {
1221 // Errors can be handled here.
1222 aCallback(undefined, event);
1226 setDBCache: function(aKey, aValue, aCallback) {
1229 var success = false;
1230 var transaction = mainDB.transaction([this.objStore], "readwrite");
1231 var objStore = transaction.objectStore(this.objStore);
1232 var request = objStore.put(aValue, aKey);
1233 request.onsuccess = function(event) {
1236 aCallback(success, event);
1238 request.onerror = function(event) {
1239 // Errors can be handled here.
1241 aCallback(success, event);
1245 unsetDBCache: function(aKey, aCallback) {
1248 var success = false;
1249 var transaction = mainDB.transaction([this.objStore], "readwrite");
1250 var request = transaction.objectStore(this.objStore).delete(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 clearDB: function(aCallback) {
1266 var success = false;
1267 var transaction = mainDB.transaction([this.objStore], "readwrite");
1268 var request = transaction.objectStore(this.objStore).clear();
1269 request.onsuccess = function(event) {
1272 aCallback(success, event);
1274 request.onerror = function(event) {
1275 // Errors can be handled here.
1277 aCallback(success, event);