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: "https://tilecache[1-4].kairo.at/osmde/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
33 //url: "http://[a-d].tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png", // https is not supported at all
34 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>'},
36 {name: "ÖPNV-Karte (OSM)",
37 url: "https://tilecache[1-4].kairo.at/oepnv/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
38 //url: "http://tileserver.memomaps.de/tilegen/{z}/{x}/{y}.png", // memomaps.de does not support CORS or https at this time :(
39 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>.'},
41 {name: "MapQuest OSM",
42 url: "https://tilecache[1-4].kairo.at/mapqosm/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
43 //url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png", // https has wrong cert, akamai instead of mqcdn
44 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>.'},
46 {name: "MapQuest Open Aerial",
47 url: "https://tilecache[1-4].kairo.at/mapqsat/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
48 //url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg",
49 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.'},
51 {name: "OSM HOT style",
52 url: "https://tilecache[1-4].kairo.at/osmhot/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
53 //url: "http://[a-c].tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", // https has CAcert which doesn't work in browsers
54 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>'},
56 {name: "Hike and Bike (OSM)",
57 url: "https://tilecache[1-4].kairo.at/hikebike/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
58 //url: "http://toolserver.org/tiles/hikebike/{z}/{x}/{y}.png", // toolserver.org does not support CORS at this time :(
59 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>'},
61 {name: "Outdoors (OSM)",
62 url: "https://[a-c].tile.thunderforest.com/outdoors/{z}/{x}/{y}.png", // url: "http://[a-c].tile.opencyclemap.org/outdoors/{z}/{x}/{y}.png",
63 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 by <a href="http://www.thunderforest.com/">Thunderforest</a>.'},
65 {name: "Stamen Toner (B+W)",
66 url: "https://tilecache[1-4].kairo.at/toner/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
67 //url: "http://[a-c].tile.stamen.com/toner/{z}/{x}/{y}.jpg", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
68 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>.'},
70 {name: "Stamen Terrain (USA only)",
71 url: "https://tilecache[1-4].kairo.at/terrain/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
72 //url: "http://[a-c].tile.stamen.com/terrain/{z}/{x}/{y}.jpg", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
73 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>.'},
75 {name: "Stamen Watercolor (artistic)",
76 url: "https://tilecache[1-4].kairo.at/watercolor/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
77 //url: "http://[a-c].tile.stamen.com/watercolor/{z}/{x}/{y}.jpg", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
78 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>.'},
86 var gMapPrefsLoaded = false;
88 var gDragging = false;
89 var gDragTouchID, gPinchStartWidth;
91 var gGeoWatchID, gGPSWakeLock;
93 var gLastTrackPoint, gLastDrawnPoint;
94 var gCenterPosition = true;
99 gGeolocation = navigator.geolocation;
100 // Set up canvas context.
101 gGLMapCanvas = document.getElementById("map");
103 // Try to grab the standard context. If it fails, fallback to experimental.
104 // We also try to tell it we do not need a depth buffer.
105 gMap.gl = gGLMapCanvas.getContext("webgl", {depth: false}) ||
106 gGLMapCanvas.getContext("experimental-webgl", {depth: false});
110 // If we don't have a GL context, give up now
111 showGLWarningDialog();
115 // GL context can be lost at any time, handle that.
116 // See http://www.khronos.org/webgl/wiki/HandlingContextLost
117 gGLMapCanvas.addEventListener("webglcontextlost",
118 gMap.handleContextLost, false);
119 gGLMapCanvas.addEventListener("webglcontextrestored",
120 gMap.handleContextRestored, false);
122 gTrackCanvas = document.getElementById("track");
123 gTrackContext = gTrackCanvas.getContext("2d");
127 gGeolocation = geofake;
128 var hiddenList = document.getElementsByClassName("debugHide");
129 // last to first - list of elements with that class is changing!
130 for (var i = hiddenList.length - 1; i >= 0; i--) {
131 hiddenList[i].classList.remove("debugHide");
135 gAction.addEventListener("prefload-done", gMap.initGL, false);
137 console.log("map vars set, loading prefs...");
141 function loadPrefs(aEvent) {
142 if (aEvent && aEvent.type == "prefs-step") {
143 console.log("wait: " + gWaitCounter);
144 if (gWaitCounter == 0) {
145 gAction.removeEventListener(aEvent.type, loadPrefs, false);
146 gMapPrefsLoaded = true;
147 console.log("prefs loaded.");
149 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
150 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
151 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
152 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
154 gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
155 gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
156 gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
157 gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
158 gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
160 gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
162 document.getElementById("body").addEventListener("keydown", mapEvHandler, false);
164 document.addEventListener("visibilitychange", visibilityEvHandler, false);
166 console.log("Events added.");
168 console.log("Init loading tile...");
169 gLoadingTile = new Image();
170 gLoadingTile.onload = function() {
171 console.log("Loading tile loaded.");
172 var throwEv = new CustomEvent("prefload-done");
173 gAction.dispatchEvent(throwEv);
175 console.log("Set loading tile...");
176 gLoadingTile.src = "style/loading.png";
181 gAction.removeEventListener(aEvent.type, loadPrefs, false);
182 gAction.addEventListener("prefs-step", loadPrefs, false);
184 gPrefs.get("active_map_style", function(aValue) {
185 if (aValue && gMapStyles[aValue]) {
186 gMap.activeMap = aValue;
189 gMap.activeMap = "osm_mapnik";
191 document.getElementById("mapSelector").value = gMap.activeMap;
192 document.getElementById("copyright").innerHTML =
193 gMapStyles[gMap.activeMap].copyright;
195 var throwEv = new CustomEvent("prefs-step");
196 gAction.dispatchEvent(throwEv);
199 gPrefs.get("position", function(aValue) {
200 if (aValue && aValue.x && aValue.y && aValue.z) {
204 var throwEv = new CustomEvent("prefs-step");
205 gAction.dispatchEvent(throwEv);
208 gPrefs.get("center_map", function(aValue) {
209 if (aValue === undefined) {
210 document.getElementById("centerCheckbox").checked = true;
213 document.getElementById("centerCheckbox").checked = aValue;
215 setCentering(document.getElementById("centerCheckbox"));
217 var throwEv = new CustomEvent("prefs-step");
218 gAction.dispatchEvent(throwEv);
221 gPrefs.get("tracking_enabled", function(aValue) {
222 if (aValue === undefined) {
223 document.getElementById("trackCheckbox").checked = true;
226 document.getElementById("trackCheckbox").checked = aValue;
229 var throwEv = new CustomEvent("prefs-step");
230 gAction.dispatchEvent(throwEv);
233 var trackLoadStarted = false;
234 var redrawBase = 100;
235 gTrackStore.getListStepped(function(aTPoint) {
237 // Add in front and return new length.
238 var tracklen = gTrack.unshift(aTPoint);
239 // Redraw track periodically, larger distance the longer it gets
240 // (but clamped to the first value over a certain limit).
241 // Initial paint will do initial track drawing.
242 if (tracklen % redrawBase == 0) {
244 if (redrawBase < 1000) {
245 redrawBase = tracklen;
250 // Last point received.
253 if (!trackLoadStarted) {
254 // We have the most recent point, if present, rest will load async.
255 trackLoadStarted = true;
257 var throwEv = new CustomEvent("prefs-step");
258 gAction.dispatchEvent(throwEv);
266 glShaderProgram: null,
267 glVertexPositionAttr: null,
268 glTextureCoordAttr: null,
269 glResolutionAttr: null,
272 glTxCleanIntervalID: null,
273 glTexturesPerZoomLevel: 0,
275 activeMap: "osm_mapnik",
277 maxZoom: 18, // The minimum is 0.
280 x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
281 y: 23670000.0, // The range is 0-67108864 (2^gMap.maxZoom * gMap.tileSize)
282 z: 5 // This could be fractional if supported being between zoom levels.
284 baseDim: { // Map width, height and tile size in level 18 pixels.
290 get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; },
291 get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; },
293 getVertShaderSource: function() {
294 return 'attribute vec2 aVertexPosition;\n' +
295 'attribute vec2 aTextureCoord;\n\n' +
296 'uniform vec2 uResolution;\n\n' +
297 'varying highp vec2 vTextureCoord;\n\n' +
298 'void main(void) {\n' +
299 // convert the rectangle from pixels to -1.0 to +1.0 (clipspace) 0.0 to 1.0
300 ' vec2 clipSpace = aVertexPosition * 2.0 / uResolution - 1.0;\n' +
301 ' gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' +
302 ' vTextureCoord = aTextureCoord;\n' +
304 getFragShaderSource: function() {
305 return 'varying highp vec2 vTextureCoord;\n\n' +
306 'uniform sampler2D uImage;\n\n' +
307 'void main(void) {\n' +
308 ' gl_FragColor = texture2D(uImage, vTextureCoord);\n' +
312 // When called from the event listener, the "this" reference doesn't work, so use the object name.
313 console.log("Initializing WebGL...");
315 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
316 gMap.gl.clearColor(0.0, 0.0, 0.0, 0.5); // Set clear color to black, fully opaque.
317 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT|gMap.gl.DEPTH_BUFFER_BIT); // Clear the color.
319 // Create and initialize the shaders.
320 console.log("Create and compile shaders...");
321 var vertShader = gMap.gl.createShader(gMap.gl.VERTEX_SHADER);
322 var fragShader = gMap.gl.createShader(gMap.gl.FRAGMENT_SHADER);
323 gMap.gl.shaderSource(vertShader, gMap.getVertShaderSource());
324 // Compile the shader program.
325 gMap.gl.compileShader(vertShader);
326 // See if it compiled successfully.
327 if (!gMap.gl.getShaderParameter(vertShader, gMap.gl.COMPILE_STATUS)) {
328 console.log("An error occurred compiling the vertex shader: " + gMap.gl.getShaderInfoLog(vertShader));
331 gMap.gl.shaderSource(fragShader, gMap.getFragShaderSource());
332 // Compile the shader program.
333 gMap.gl.compileShader(fragShader);
334 // See if it compiled successfully.
335 if (!gMap.gl.getShaderParameter(fragShader, gMap.gl.COMPILE_STATUS)) {
336 console.log("An error occurred compiling the fragment shader: " + gMap.gl.getShaderInfoLog(fragShader));
340 console.log("Create and link shader program...");
341 gMap.glShaderProgram = gMap.gl.createProgram();
342 gMap.gl.attachShader(gMap.glShaderProgram, vertShader);
343 gMap.gl.attachShader(gMap.glShaderProgram, fragShader);
344 gMap.gl.linkProgram(gMap.glShaderProgram);
345 // If creating the shader program failed, alert
346 if (!gMap.gl.getProgramParameter(gMap.glShaderProgram, gMap.gl.LINK_STATUS)) {
347 alert("Unable to initialize the shader program.");
349 gMap.gl.useProgram(gMap.glShaderProgram);
350 // Get locations of the attributes.
351 gMap.glVertexPositionAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aVertexPosition");
352 gMap.glTextureCoordAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aTextureCoord");
353 gMap.glResolutionAttr = gMap.gl.getUniformLocation(gMap.glShaderProgram, "uResolution");
355 console.log("Set up vertex buffer...");
356 var tileVerticesBuffer = gMap.gl.createBuffer();
357 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, tileVerticesBuffer);
358 // The vertices are the coordinates of the corner points of the square.
367 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(vertices), gMap.gl.STATIC_DRAW);
368 gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr);
369 gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0);
371 gMap.loadImageToTexture(gLoadingTile, getTileKey("loading", {x: 0, y: 0, z: 0}));
373 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
375 // Create a buffer for the position of the rectangle corners.
376 console.log("Set up coord buffer...");
377 var mapVerticesTextureCoordBuffer = gMap.gl.createBuffer();
378 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer);
379 gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr);
380 gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0);
382 // Call texture cleaning every 30 seconds, for now (is 60 better?).
383 gMap.glTxCleanIntervalID = window.setInterval(gMap.cleanTextures, 30 * 1000);
387 // We may be called when context was lost and destroyed,
388 // only send event when we are in app startup
389 // (gAppInitDone is set to true right after we return this event).
390 var throwEv = new CustomEvent("mapinit-done");
391 gAction.dispatchEvent(throwEv);
400 assembleGL: function() {
401 if (!gMap.gl) { return; }
403 document.getElementById("zoomLevel").textContent = gMap.pos.z;
404 gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
405 gMap.baseDim.wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor;
406 gMap.baseDim.ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor;
407 gMap.baseDim.tsize = gMap.tileSize * gMap.zoomFactor;
409 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
410 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
411 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
412 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
414 if (gMapPrefsLoaded && mainDB)
415 gPrefs.set("position", gMap.pos);
417 // Go through all the tiles in the map, find out if to draw them and do so.
418 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
419 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
420 // Only go to loading step if we haven't loaded the texture.
421 var coords = {x: x, y: y, z: gMap.pos.z};
422 var tileKey = getTileKey(gMap.activeMap, normalizeCoords(coords));
423 if (!gMap.glTextures[tileKey]) {
424 // Initiate loading/drawing of the actual tile.
425 gTileService.get(gMap.activeMap, coords,
426 function(aImage, aStyle, aCoords, aTileKey) {
427 // Only actually load if this still applies for the current view.
428 if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) {
429 var URL = window.URL;
430 var imgURL = URL.createObjectURL(aImage);
431 var imgObj = new Image();
432 imgObj.onload = function() {
433 gMap.loadImageToTexture(imgObj, aTileKey);
434 if (document.hidden != true) { // Only draw if we're actually visible.
435 window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
437 URL.revokeObjectURL(imgURL);
445 if (document.hidden != true) { // Only draw if we're actually visible.
446 window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
451 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
452 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
453 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
454 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
456 // Go through all the tiles in the map, find out if to draw them and do so.
457 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
458 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
459 // Rounding the pixel offsets ensures we position the tiles precisely.
460 var xoff = Math.round((x * gMap.baseDim.tsize - xMin) / gMap.zoomFactor);
461 var yoff = Math.round((y * gMap.baseDim.tsize - yMin) / gMap.zoomFactor);
462 // Draw the tile, first find out the actual texture to use.
463 var norm = normalizeCoords({x: x, y: y, z: gMap.pos.z});
464 var tileKey = getTileKey(gMap.activeMap, norm);
465 if (!gMap.glTextures[tileKey]) {
466 tileKey = getTileKey("loading", {x: 0, y: 0, z: 0});
468 gMap.drawTileGL(xoff, yoff, tileKey);
473 resizeAndDraw: function() {
474 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
475 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
476 if (gGLMapCanvas && gTrackCanvas) {
477 gGLMapCanvas.width = viewportWidth;
478 gGLMapCanvas.height = viewportHeight;
479 gTrackCanvas.width = viewportWidth;
480 gTrackCanvas.height = viewportHeight;
482 // Size viewport to canvas size.
483 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
485 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT);
486 // Make sure the vertex shader get the right resolution.
487 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
488 // Prepare recalculation of textures to keep for one zoom level.
489 gMap.glTexturesPerZoomLevel = 0;
496 drawTileGL: function(aLeft, aRight, aTileKey) {
497 gMap.gl.activeTexture(gMap.gl.TEXTURE0);
498 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
499 // Set uImage to refer to TEXTURE0
500 gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0);
502 var i_width = gMap.tileSize;
503 var y_start = aRight;
504 var i_height = gMap.tileSize;
505 var textureCoordinates = [
507 x_start + i_width, y_start,
508 x_start, y_start + i_height,
509 x_start, y_start + i_height,
510 x_start + i_width, y_start,
511 x_start + i_width, y_start + i_height,
513 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW);
515 // There are 6 indices in textureCoordinates.
516 gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
519 loadImageToTexture: function(aImage, aTileKey) {
520 // Create and bind texture.
521 gMap.glTextures[aTileKey] = gMap.gl.createTexture();
522 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
523 // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two).
524 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST);
525 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST);
526 // Upload the image into the texture.
527 gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage);
530 cleanTextures: function() {
531 // Get rid of unneeded textures to save memory.
532 // TODO: Be less aggressive, maybe keep neighboring zoom levels (but x/y coords there are zoom-specific).
533 if (!gMap.glTexturesPerZoomLevel) {
534 // Calculate how many textures we need to keep for one zoom level.
535 // ceil(width/size) gives us the minimum, keep one on either side as well.
536 gMap.glTexturesPerZoomLevel =
537 Math.ceil(gMap.gl.drawingBufferWidth / gMap.tileSize + 2) *
538 Math.ceil(gMap.gl.drawingBufferHeight / gMap.tileSize + 2);
539 console.log("Keeping " + gMap.glTexturesPerZoomLevel + " textures per level");
541 if (Object.keys(gMap.glTextures).length > gMap.glTexturesPerZoomLevel) {
542 console.log("Cleaning textures... (have " + Object.keys(gMap.glTextures).length + " atm)");
544 // Find coordinate ranges for tiles to keep.
545 var tMin = normalizeCoords({x: Math.floor((gMap.pos.x - gMap.baseDim.wid / 2) / gMap.baseDim.tsize) - 1,
546 y: Math.floor((gMap.pos.y - gMap.baseDim.ht / 2) / gMap.baseDim.tsize) - 1,
548 var tMax = normalizeCoords({x: Math.ceil((gMap.pos.x + gMap.baseDim.wid / 2) / gMap.baseDim.tsize) + 1,
549 y: Math.ceil((gMap.pos.y + gMap.baseDim.ht / 2) / gMap.baseDim.tsize) + 1,
551 console.log("In range: " + tMin.x + "," + tMin.y + "," + tMin.z + " - " + tMax.x + "," + tMax.y + "," + tMax.z);
552 for (var tileKey in gMap.glTextures) {
553 var keyMatches = tileKey.match(/([^:]+)::(\d+),(\d+),(\d+)/);
554 if (keyMatches && keyMatches[1] != "loading") {
556 style: keyMatches[1],
562 if (txData.style != gMap.activeMap) { delTx = true; console.log("Different map style: " + txData.style); }
563 if (!delTx && (txData.z < tMin.z || txData.z > tMax.z)) { delTx = true; console.log("Out-of-range zoom: " + txData.z); }
564 if (tMin.x < tMax.x) {
565 if (!delTx && (txData.x < tMin.x || txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
568 // We are crossing over the 0 coordinate!
569 if (!delTx && (txData.x < tMin.x && txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
571 if (tMin.y < tMax.y) {
572 if (!delTx && (txData.y < tMin.y || txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
575 // We are crossing over the 0 coordinate!
576 if (!delTx && (txData.y < tMin.y && txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
579 // Delete texture from GL and from the array we are holding.
580 gMap.gl.deleteTexture(gMap.glTextures[tileKey]);
581 delete gMap.glTextures[tileKey];
585 console.log("Cleaning complete, " + Object.keys(gMap.glTextures).length + " textures left");
589 handleContextLost: function(event) {
590 event.preventDefault();
591 // GL context is gone, let's reset everything that depends on it.
592 clearInterval(gMap.glTxCleanIntervalID);
593 gMap.glTextures = {};
596 handleContextRestored: function(event) {
597 // When GL context is back, init GL again and draw.
603 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
604 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
607 if (gMap.pos.z < gMap.maxZoom) {
614 if (gMap.pos.z > 0) {
620 function zoomTo(aTargetLevel) {
621 aTargetLevel = parseInt(aTargetLevel);
622 if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) {
623 gMap.pos.z = aTargetLevel;
628 function gps2xy(aLatitude, aLongitude) {
629 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
630 var convLat = aLatitude * Math.PI / 180;
631 var rawY = (1 - Math.log(Math.tan(convLat) +
632 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
633 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
634 return {x: Math.round(rawX),
635 y: Math.round(rawY)};
638 function xy2gps(aX, aY) {
639 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
640 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
641 return {latitude: 180 / Math.PI *
642 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
643 longitude: aX / maxZoomFactor * 360 - 180};
646 function setMapStyle() {
647 var mapSel = document.getElementById("mapSelector");
648 if (mapSel.selectedIndex >= 0 && gMap.activeMap != mapSel.value) {
649 gMap.activeMap = mapSel.value;
650 gPrefs.set("active_map_style", gMap.activeMap);
651 document.getElementById("copyright").innerHTML =
652 gMapStyles[gMap.activeMap].copyright;
653 if (!gWaitCounter) { // Only do this when prefs are loaded already.
660 // A sane mod function that works for negative numbers.
663 return ((a % b) + b) % b;
666 function normalizeCoords(aCoords) {
667 var zoomFactor = Math.pow(2, aCoords.z);
668 return {x: mod(aCoords.x, zoomFactor),
669 y: mod(aCoords.y, zoomFactor),
673 function getTileKey(aStyle, aNormalizedCoords) {
674 return aStyle + "::" +
675 aNormalizedCoords.x + "," +
676 aNormalizedCoords.y + "," +
680 // Returns true if the tile is outside the current view.
681 function isOutsideWindow(t) {
682 var pos = decodeIndex(t);
684 var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z);
685 var wid = gMap.width * zoomFactor;
686 var ht = gMap.height * zoomFactor;
691 var sz = gMap.tileSize * zoomFactor;
692 if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 ||
693 pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2)
698 function encodeIndex(x, y, z) {
699 var norm = normalizeCoords({x: x, y: y, z: z});
700 return norm.x + "," + norm.y + "," + norm.z;
703 function decodeIndex(encodedIdx) {
704 var ind = encodedIdx.split(",", 3);
705 return {x: ind[0], y: ind[1], z: ind[2]};
708 function drawTrack() {
709 if (gTrackContext && (document.hidden != true)) { // Only draw if we're actually visible.
710 gLastDrawnPoint = null;
711 gCurPosMapCache = undefined;
712 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
714 for (var i = 0; i < gTrack.length; i++) {
715 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
716 (i + 1 >= gTrack.length || gTrack[i+1].beginSegment));
722 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
723 var trackpoint = gps2xy(aLatitude, aLongitude);
724 // lastPoint is for optimizing (not actually executing the draw until the last)
725 trackpoint.optimized = (lastPoint === false);
726 var mappos = {x: Math.round((trackpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
727 y: Math.round((trackpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
729 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
730 gTrackContext.strokeStyle = gTrackColor;
731 gTrackContext.fillStyle = gTrackContext.strokeStyle;
732 gTrackContext.lineWidth = gTrackWidth;
733 gTrackContext.lineCap = "round";
734 gTrackContext.lineJoin = "round";
736 // This breaks optimiziation, so make sure to reset optimization.
737 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
738 trackpoint.optimized = false;
739 // Close path if one was open.
740 if (gLastDrawnPoint && gLastDrawnPoint.optimized) {
741 gTrackContext.stroke();
744 if (!gLastDrawnPoint || (gLastDrawnPoint == trackpoint) || !gLastDrawnPoint.optimized) {
745 // Start drawing a segment.
746 gTrackContext.beginPath();
747 gTrackContext.arc(mappos.x, mappos.y,
748 gTrackContext.lineWidth, 0, Math.PI * 2, false);
749 gTrackContext.fill();
752 // Continue drawing segment, close if needed.
753 gTrackContext.lineTo(mappos.x, mappos.y);
754 if (!trackpoint.optimized)
755 gTrackContext.stroke();
757 gLastDrawnPoint = trackpoint;
760 function drawCurrentLocation(trackPoint) {
761 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
762 var circleRadius = Math.round(gCurLocSize / 2);
763 var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
764 y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
766 undrawCurrentLocation();
768 // Cache overdrawn area.
771 radius: circleRadius,
772 data: gTrackContext.getImageData(mappos.x - circleRadius,
773 mappos.y - circleRadius,
774 circleRadius * 2, circleRadius * 2)};
776 gTrackContext.strokeStyle = gCurLocColor;
777 gTrackContext.fillStyle = gTrackContext.strokeStyle;
778 gTrackContext.beginPath();
779 gTrackContext.arc(mappos.x, mappos.y,
780 circleRadius, 0, Math.PI * 2, false);
781 gTrackContext.fill();
784 function undrawCurrentLocation() {
785 if (gCurPosMapCache) {
786 var oldpoint = gCurPosMapCache.point;
787 var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
788 y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
789 gTrackContext.putImageData(gCurPosMapCache.data,
790 oldmp.x - gCurPosMapCache.radius,
791 oldmp.y - gCurPosMapCache.radius);
792 gCurPosMapCache = undefined;
796 function calcTrackDuration() {
797 // Get the duration of the track in s.
799 if (gTrack.length > 1) {
800 for (var i = 1; i < gTrack.length; i++) {
801 if (!gTrack[i].beginSegment) {
802 tDuration += (gTrack[i].time - gTrack[i-1].time);
806 return Math.round(tDuration / 1000); // The timestamps are in ms but we return seconds.
809 function calcTrackLength() {
810 // Get the length of the track in km.
812 if (gTrack.length > 1) {
813 for (var i = 1; i < gTrack.length; i++) {
814 if (!gTrack[i].beginSegment) {
815 tLength += getPointDistance(gTrack[i-1].coords, gTrack[i].coords);
822 function getPointDistance(aGPSPoint1, aGPSPoint2) {
823 // Get the distance in km between the two given GPS points.
824 // See http://stackoverflow.com/questions/365826/calculate-distance-between-2-gps-coordinates
825 // Earth is almost exactly a sphere and we calculate small distances on the surface, so we can do spherical great-circle math.
826 // Also see http://en.wikipedia.org/wiki/Great-circle_distance
828 var dLat = deg2rad(aGPSPoint2.latitude - aGPSPoint1.latitude);
829 var dLon = deg2rad(aGPSPoint2.longitude - aGPSPoint1.longitude);
830 var lat1 = deg2rad(aGPSPoint1.latitude);
831 var lat2 = deg2rad(aGPSPoint2.latitude);
833 var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
834 Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
835 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
839 function deg2rad(aDegreeValue) {
840 // Convert an angle in degrees to radiants.
841 return aDegreeValue * (Math.PI / 180);
845 handleEvent: function(aEvent) {
846 var touchEvent = aEvent.type.indexOf('touch') != -1;
849 aEvent.stopPropagation();
852 // Bail out if the event is happening on an input.
853 if (aEvent.target.tagName.toLowerCase() == "input")
856 // Bail out on unwanted map moves, but not zoom or keyboard events.
857 if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
858 // Bail out if this is neither a touch nor left-click.
859 if (!touchEvent && aEvent.button != 0)
862 // Bail out if the started touch can't be found.
863 if (touchEvent && gDragging &&
864 !aEvent.targetTouches.item(0))
868 var coordObj = touchEvent ?
869 aEvent.targetTouches.item(0) :
872 switch (aEvent.type) {
876 if (aEvent.targetTouches.length == 2) {
877 gPinchStartWidth = Math.sqrt(
878 Math.pow(aEvent.targetTouches.item(1).clientX -
879 aEvent.targetTouches.item(0).clientX, 2) +
880 Math.pow(aEvent.targetTouches.item(1).clientY -
881 aEvent.targetTouches.item(0).clientY, 2)
884 coordObj = aEvent.targetTouches.item(0);
886 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
887 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
889 if (touchEvent || aEvent.button === 0) {
898 if (touchEvent && aEvent.targetTouches.length == 2) {
899 curPinchStartWidth = Math.sqrt(
900 Math.pow(aEvent.targetTouches.item(1).clientX -
901 aEvent.targetTouches.item(0).clientX, 2) +
902 Math.pow(aEvent.targetTouches.item(1).clientY -
903 aEvent.targetTouches.item(0).clientY, 2)
905 if (!gPinchStartWidth)
906 gPinchStartWidth = curPinchStartWidth;
908 if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
909 gPinchStartWidth / curPinchStartWidth < 0.6) {
910 var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
911 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
912 // Calculate new center of the map - preserve middle of pinch.
913 // This means that pixel distance between old center and middle
914 // must equal pixel distance of new center and middle.
915 var x = (aEvent.targetTouches.item(1).clientX +
916 aEvent.targetTouches.item(0).clientX) / 2 -
917 gGLMapCanvas.offsetLeft;
918 var y = (aEvent.targetTouches.item(1).clientY +
919 aEvent.targetTouches.item(0).clientY) / 2 -
920 gGLMapCanvas.offsetTop;
922 // Zoom factor after this action.
923 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
924 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
925 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
927 if (gPinchStartWidth < curPinchStartWidth)
932 // Reset pinch start width and start another pinch gesture.
933 gPinchStartWidth = null;
936 // If we are in a pinch, do not drag.
939 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
940 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
941 if (gDragging === true) {
942 var dX = x - gLastMouseX;
943 var dY = y - gLastMouseY;
944 gMap.pos.x -= dX * gMap.zoomFactor;
945 gMap.pos.y -= dY * gMap.zoomFactor;
954 gPinchStartWidth = null;
964 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
965 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
967 // Only accept (non-null) deltaY values
971 // Debug output: "coordinates" of the point the mouse was over.
973 var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor,
974 y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor};
975 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
976 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
977 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
978 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
979 pt2Coord.x + "/" + pt2Coord.y);
982 var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1);
983 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
984 // Calculate new center of the map - same point stays under the mouse.
985 // This means that the pixel distance between the old center and point
986 // must equal the pixel distance of the new center and that point.
987 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
988 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
990 // Zoom factor after this action.
991 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
992 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
993 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
995 if (aEvent.deltaY < 0)
1002 // Allow keyboard control to move and zoom the map.
1003 // Should use aEvent.key instead of aEvent.which but needs bug 680830.
1004 // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
1007 switch (aEvent.which) {
1009 dX = -gMap.tileSize / 2;
1012 dX = gMap.tileSize / 2;
1015 dY = gMap.tileSize / 2;
1018 dY = -gMap.tileSize / 2;
1021 case 107: // + (numpad)
1022 case 171: // + (normal key)
1026 case 109: // - (numpad)
1027 case 173: // - (normal key)
1039 zoomTo(aEvent.which - 38);
1044 case 96: // 0 (numpad)
1045 case 97: // 1 (numpad)
1046 case 98: // 2 (numpad)
1047 case 99: // 3 (numpad)
1048 case 100: // 4 (numpad)
1049 case 101: // 5 (numpad)
1050 case 102: // 6 (numpad)
1051 case 103: // 7 (numpad)
1052 case 104: // 8 (numpad)
1053 zoomTo(aEvent.which - 86);
1055 case 105: // 9 (numpad)
1058 default: // not supported
1059 console.log("key not supported: " + aEvent.which);
1065 gMap.pos.x -= dX * gMap.zoomFactor;
1066 gMap.pos.y -= dY * gMap.zoomFactor;
1074 function visibilityEvHandler() {
1075 // Immediately draw if we just got visible.
1076 if (document.hidden != true) {
1079 // No need to handle the event where we become invisible as we care only draw
1080 // when we are visible anyhow.
1085 lastPos: {x: undefined, y: undefined},
1086 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
1087 this.tracking = true;
1088 var watchCall = function() {
1089 // calc new position in lat/lon degrees
1090 // 90° on Earth surface are ~10,000 km at the equator,
1091 // so try moving at most 10m at a time
1092 if (geofake.lastPos.x)
1093 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
1095 geofake.lastPos.x = 48.208174
1096 if (geofake.lastPos.y)
1097 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
1099 geofake.lastPos.y = 16.373819
1100 aSuccessCallback({timestamp: Date.now(),
1101 coords: {latitude: geofake.lastPos.x,
1102 longitude: geofake.lastPos.y,
1104 if (geofake.tracking)
1105 setTimeout(watchCall, 1000);
1107 setTimeout(watchCall, 1000);
1110 clearWatch: function(aID) {
1111 this.tracking = false;
1115 function setCentering(aCheckbox) {
1116 if (gMapPrefsLoaded && mainDB)
1117 gPrefs.set("center_map", aCheckbox.checked);
1118 gCenterPosition = aCheckbox.checked;
1121 function setTracking(aCheckbox) {
1122 if (gMapPrefsLoaded && mainDB)
1123 gPrefs.set("tracking_enabled", aCheckbox.checked);
1124 if (aCheckbox.checked)
1130 function startTracking() {
1132 gActionLabel.textContent = "Establishing Position";
1133 gAction.style.display = "block";
1134 if (navigator.requestWakeLock) {
1135 gGPSWakeLock = navigator.requestWakeLock("gps");
1137 gGeoWatchID = gGeolocation.watchPosition(
1138 function(position) {
1139 if (gActionLabel.textContent) {
1140 gActionLabel.textContent = "";
1141 gAction.style.display = "none";
1143 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
1144 var tPoint = {time: position.timestamp,
1145 coords: {latitude: position.coords.latitude,
1146 longitude: position.coords.longitude,
1147 altitude: position.coords.altitude,
1148 accuracy: position.coords.accuracy,
1149 altitudeAccuracy: position.coords.altitudeAccuracy,
1150 heading: position.coords.heading,
1151 speed: position.coords.speed},
1152 beginSegment: !gLastTrackPoint};
1153 // Only add point to track is accuracy is good enough.
1154 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
1155 gLastTrackPoint = tPoint;
1156 gTrack.push(tPoint);
1157 try { gTrackStore.push(tPoint); } catch(e) {}
1158 var redrawn = false;
1159 if (gCenterPosition) {
1160 var posCoord = gps2xy(position.coords.latitude,
1161 position.coords.longitude);
1162 if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 ||
1163 Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) {
1164 gMap.pos.x = posCoord.x;
1165 gMap.pos.y = posCoord.y;
1166 gMap.draw(); // This draws the current point as well.
1171 undrawCurrentLocation();
1172 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
1174 drawCurrentLocation(tPoint);
1177 // Ignore erros for the moment, but this is good for debugging.
1178 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
1180 console.log(error.message);
1182 {enableHighAccuracy: true}
1187 function endTracking() {
1188 if (gActionLabel.textContent) {
1189 gActionLabel.textContent = "";
1190 gAction.style.display = "none";
1192 if (navigator.requestWakeLock && gGPSWakeLock) {
1193 console.log("releasing WakeLock");
1194 gGPSWakeLock.unlock();
1197 gGeolocation.clearWatch(gGeoWatchID);
1201 function clearTrack() {
1203 gTrackStore.clear();
1207 var gTileService = {
1208 objStore: "tilecache",
1210 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
1212 get: function(aStyle, aCoords, aCallback) {
1213 var norm = normalizeCoords(aCoords);
1214 var dbkey = getTileKey(aStyle, norm);
1215 this.getDBCache(dbkey, function(aResult, aEvent) {
1217 // We did get a cached object.
1218 aCallback(aResult.image, aStyle, aCoords, dbkey);
1219 // Look at the timestamp and return if it's not too old.
1220 if (aResult.timestamp + gTileService.ageLimit > Date.now())
1222 // Reload cached tile otherwise.
1223 var oldDate = new Date(aResult.timestamp);
1224 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
1226 // Retrieve image from the web and store it in the cache.
1227 var XHR = new XMLHttpRequest();
1229 gMapStyles[aStyle].url
1230 .replace("{x}", norm.x)
1231 .replace("{y}", norm.y)
1232 .replace("{z}", norm.z)
1233 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 3)))
1234 .replace("[a-d]", String.fromCharCode(97 + Math.floor(Math.random() * 4)))
1235 .replace("[1-4]", 1 + Math.floor(Math.random() * 4)),
1237 XHR.responseType = "blob";
1238 XHR.addEventListener("load", function () {
1239 if (XHR.status === 200) {
1240 var blob = XHR.response;
1241 aCallback(blob, aStyle, aCoords, dbkey);
1242 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
1249 getDBCache: function(aKey, aCallback) {
1252 var transaction = mainDB.transaction([this.objStore]);
1253 var request = transaction.objectStore(this.objStore).get(aKey);
1254 request.onsuccess = function(event) {
1255 aCallback(request.result, event);
1257 request.onerror = function(event) {
1258 // Errors can be handled here.
1259 aCallback(undefined, event);
1263 setDBCache: function(aKey, aValue, aCallback) {
1266 var success = false;
1267 var transaction = mainDB.transaction([this.objStore], "readwrite");
1268 var objStore = transaction.objectStore(this.objStore);
1269 var request = objStore.put(aValue, 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 unsetDBCache: function(aKey, aCallback) {
1285 var success = false;
1286 var transaction = mainDB.transaction([this.objStore], "readwrite");
1287 var request = transaction.objectStore(this.objStore).delete(aKey);
1288 request.onsuccess = function(event) {
1291 aCallback(success, event);
1293 request.onerror = function(event) {
1294 // Errors can be handled here.
1296 aCallback(success, event);
1300 clearDB: function(aCallback) {
1303 var success = false;
1304 var transaction = mainDB.transaction([this.objStore], "readwrite");
1305 var request = transaction.objectStore(this.objStore).clear();
1306 request.onsuccess = function(event) {
1308 console.log("Cache cleared.");
1310 aCallback(success, event);
1312 request.onerror = function(event) {
1313 // Errors can be handled here.
1314 console.log("Error clearing cache!");
1316 aCallback(success, event);