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, gGeolocation;
8 var gMinTrackAccuracy = 1000; // meters
9 var gCenterDelayAfterMove = 3000; // milliseconds
12 // OSM tile usage policy: http://wiki.openstreetmap.org/wiki/Tile_usage_policy
13 // Find some more OSM ones at http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers
14 // and http://wiki.openstreetmap.org/wiki/Tiles or http://wiki.openstreetmap.org/wiki/TMS
16 {name: "OpenStreetMap (Mapnik)",
17 url: "https://[a-c].tile.openstreetmap.org/{z}/{x}/{y}.png",
18 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>'},
20 {name: "Cycle Map (OSM)",
21 url: "https://[a-c].tile.thunderforest.com/cycle/{z}/{x}/{y}.png", // "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
22 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>'},
24 {name: "Transport Map (OSM)",
25 url: "https://[a-c].tile.thunderforest.com/transport/{z}/{x}/{y}.png", // "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png",
26 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>'},
28 {name: "OSM German Style",
29 url: "https://tilecache[1-4].kairo.at/osmde/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
30 //url: "http://[a-d].tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png", // https is not supported at all
31 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>'},
33 {name: "ÖPNV-Karte (OSM)",
34 url: "https://tilecache[1-4].kairo.at/oepnv/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
35 //url: "http://tileserver.memomaps.de/tilegen/{z}/{x}/{y}.png", // memomaps.de does not support CORS or https at this time :(
36 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>.'},
38 {name: "MapQuest OSM",
39 url: "https://tilecache[1-4].kairo.at/mapqosm/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
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: "https://tilecache[1-4].kairo.at/mapqsat/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
45 //url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg",
46 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.'},
48 {name: "OSM HOT style",
49 url: "https://tilecache[1-4].kairo.at/osmhot/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
50 //url: "http://[a-c].tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", // https has CAcert which doesn't work in browsers
51 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>'},
54 //url: "https://tilecache[1-4].kairo.at/opentopomap/{z}/{x}/{y}.png", // route through tilecache @ kairo.at
55 url: "https://[a-c].tile.opentopomap.org/{z}/{x}/{y}.png",
56 copyright: 'Map data: © <a href="https://openstreetmap.org/copyright">OpenStreetMap</a> contributors, <a href="http://viewfinderpanoramas.org">SRTM</a> | map style: © <a href="https://opentopomap.org">OpenTopoMap</a> (<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)'},
58 {name: "Hike and Bike (OSM)",
59 url: "https://tilecache[1-4].kairo.at/hikebike/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
60 //url: "http://toolserver.org/tiles/hikebike/{z}/{x}/{y}.png", // toolserver.org does not support CORS at this time :(
61 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>'},
63 {name: "Outdoors (OSM)",
64 url: "https://[a-c].tile.thunderforest.com/outdoors/{z}/{x}/{y}.png", // url: "http://[a-c].tile.opencyclemap.org/outdoors/{z}/{x}/{y}.png",
65 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>.'},
67 {name: "Stamen Toner (B+W)",
68 url: "https://tilecache[1-4].kairo.at/toner/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
69 //url: "http://[a-c].tile.stamen.com/toner/{z}/{x}/{y}.jpg", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
70 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>.'},
72 {name: "Stamen Terrain (USA only)",
73 url: "https://tilecache[1-4].kairo.at/terrain/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
74 //url: "http://[a-c].tile.stamen.com/terrain/{z}/{x}/{y}.jpg", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
75 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>.'},
77 {name: "Stamen Watercolor (artistic)",
78 url: "https://tilecache[1-4].kairo.at/watercolor/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
79 //url: "http://[a-c].tile.stamen.com/watercolor/{z}/{x}/{y}.jpg", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
80 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>.'},
88 var gMapPrefsLoaded = false;
90 var gDragging = false;
91 var gDragTouchID, gPinchStartWidth;
93 var gGeoWatchID, gGPSWakeLock;
96 var gCenterPosition = true;
97 var gLastMoveAction = null;
100 gGeolocation = navigator.geolocation;
101 // Set up canvas context.
102 gGLMapCanvas = document.getElementById("map");
104 // Try to grab the standard context. If it fails, fallback to experimental.
105 // We also try to tell it we do not need a depth buffer.
106 gMap.gl = gGLMapCanvas.getContext("webgl", {depth: false}) ||
107 gGLMapCanvas.getContext("experimental-webgl", {depth: false});
111 // If we don't have a GL context, give up now
112 showGLWarningDialog();
116 // GL context can be lost at any time, handle that.
117 // See http://www.khronos.org/webgl/wiki/HandlingContextLost
118 gGLMapCanvas.addEventListener("webglcontextlost",
119 gMap.handleContextLost, false);
120 gGLMapCanvas.addEventListener("webglcontextrestored",
121 gMap.handleContextRestored, false);
123 gTrackCanvas = document.getElementById("track");
124 gTrackLayer.context = gTrackCanvas.getContext("2d");
128 gGeolocation = geofake;
129 var hiddenList = document.getElementsByClassName("debugHide");
130 // last to first - list of elements with that class is changing!
131 for (var i = hiddenList.length - 1; i >= 0; i--) {
132 hiddenList[i].classList.remove("debugHide");
136 gAction.addEventListener("prefload-done", gMap.initGL, false);
138 console.log("map vars set, loading prefs...");
142 function loadPrefs(aEvent) {
143 if (aEvent && aEvent.type == "prefs-step") {
144 console.log("wait: " + gWaitCounter);
145 if (gWaitCounter == 0) {
146 gAction.removeEventListener(aEvent.type, loadPrefs, false);
147 gMapPrefsLoaded = true;
148 console.log("prefs loaded.");
150 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
151 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
152 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
153 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
155 gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
156 gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
157 gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
158 gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
159 gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
161 gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
163 document.getElementById("body").addEventListener("keydown", mapEvHandler, false);
165 document.addEventListener("visibilitychange", visibilityEvHandler, false);
167 console.log("Events added.");
169 console.log("Init loading tile...");
170 gLoadingTile = new Image();
171 gLoadingTile.onload = function() {
172 console.log("Loading tile loaded.");
173 var throwEv = new CustomEvent("prefload-done");
174 gAction.dispatchEvent(throwEv);
176 console.log("Set loading tile...");
177 gLoadingTile.src = "style/loading.png";
182 gAction.removeEventListener(aEvent.type, loadPrefs, false);
183 gAction.addEventListener("prefs-step", loadPrefs, false);
185 gPrefs.get("active_map_style", function(aValue) {
186 if (aValue && gMapStyles[aValue]) {
187 gMap.activeMap = aValue;
190 gMap.activeMap = "osm_mapnik";
192 document.getElementById("mapSelector").value = gMap.activeMap;
193 document.getElementById("copyright").innerHTML =
194 gMapStyles[gMap.activeMap].copyright;
196 var throwEv = new CustomEvent("prefs-step");
197 gAction.dispatchEvent(throwEv);
200 gPrefs.get("position", function(aValue) {
201 if (aValue && aValue.x && aValue.y && aValue.z) {
205 var throwEv = new CustomEvent("prefs-step");
206 gAction.dispatchEvent(throwEv);
209 gPrefs.get("center_map", function(aValue) {
210 if (aValue === undefined) {
211 document.getElementById("centerCheckbox").checked = true;
214 document.getElementById("centerCheckbox").checked = aValue;
216 setCentering(document.getElementById("centerCheckbox"));
218 var throwEv = new CustomEvent("prefs-step");
219 gAction.dispatchEvent(throwEv);
222 gPrefs.get("tracking_enabled", function(aValue) {
223 if (aValue === undefined) {
224 document.getElementById("trackCheckbox").checked = true;
227 document.getElementById("trackCheckbox").checked = aValue;
230 var throwEv = new CustomEvent("prefs-step");
231 gAction.dispatchEvent(throwEv);
234 var trackLoadStarted = false;
235 var redrawBase = 100;
236 gTrackStore.getListStepped(function(aTPoint) {
238 // Add in front and return new length.
239 var tracklen = gTrack.unshift(aTPoint);
240 // Redraw track periodically, larger distance the longer it gets
241 // (but clamped to the first value over a certain limit).
242 // Initial paint will do initial track drawing.
243 if (tracklen % redrawBase == 0) {
244 gTrackLayer.drawTrack(); // TODO: we could draw incremmentally if we would support reverse-direction drawing...
245 if (redrawBase < 1000) {
246 redrawBase = tracklen;
251 // Last point received.
252 gTrackLayer.drawTrack(); // TODO: we could draw incremmentally if we would support reverse-direction drawing...
254 if (!trackLoadStarted) {
255 // We have the most recent point, if present, rest will load async.
256 trackLoadStarted = true;
258 var throwEv = new CustomEvent("prefs-step");
259 gAction.dispatchEvent(throwEv);
267 glShaderProgram: null,
268 glVertexPositionAttr: null,
269 glTextureCoordAttr: null,
270 glResolutionAttr: null,
273 glTxCleanIntervalID: null,
274 glTexturesPerZoomLevel: 0,
276 activeMap: "osm_mapnik",
278 maxZoom: 18, // The minimum is 0.
281 x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
282 y: 23670000.0, // The range is 0-67108864 (2^gMap.maxZoom * gMap.tileSize)
283 z: 5 // This could be fractional if supported being between zoom levels.
285 baseDim: { // Map width, height and tile size in level 18 pixels.
290 glDrawRequested: false, // To avoid parallel calls to drawGL().
292 get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; },
293 get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; },
295 getVertShaderSource: function() {
296 return 'attribute vec2 aVertexPosition;\n' +
297 'attribute vec2 aTextureCoord;\n\n' +
298 'uniform vec2 uResolution;\n\n' +
299 'varying highp vec2 vTextureCoord;\n\n' +
300 'void main(void) {\n' +
301 // convert the rectangle from pixels to -1.0 to +1.0 (clipspace) 0.0 to 1.0
302 ' vec2 clipSpace = aVertexPosition * 2.0 / uResolution - 1.0;\n' +
303 ' gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' +
304 ' vTextureCoord = aTextureCoord;\n' +
306 getFragShaderSource: function() {
307 return 'varying highp vec2 vTextureCoord;\n\n' +
308 'uniform sampler2D uImage;\n\n' +
309 'void main(void) {\n' +
310 ' gl_FragColor = texture2D(uImage, vTextureCoord);\n' +
314 // When called from the event listener, the "this" reference doesn't work, so use the object name.
315 console.log("Initializing WebGL...");
317 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
318 gMap.gl.clearColor(0.0, 0.0, 0.0, 0.5); // Set clear color to black, fully opaque.
319 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT|gMap.gl.DEPTH_BUFFER_BIT); // Clear the color.
321 // Create and initialize the shaders.
322 console.log("Create and compile shaders...");
323 var vertShader = gMap.gl.createShader(gMap.gl.VERTEX_SHADER);
324 var fragShader = gMap.gl.createShader(gMap.gl.FRAGMENT_SHADER);
325 gMap.gl.shaderSource(vertShader, gMap.getVertShaderSource());
326 // Compile the shader program.
327 gMap.gl.compileShader(vertShader);
328 // See if it compiled successfully.
329 if (!gMap.gl.getShaderParameter(vertShader, gMap.gl.COMPILE_STATUS)) {
330 console.log("An error occurred compiling the vertex shader: " + gMap.gl.getShaderInfoLog(vertShader));
333 gMap.gl.shaderSource(fragShader, gMap.getFragShaderSource());
334 // Compile the shader program.
335 gMap.gl.compileShader(fragShader);
336 // See if it compiled successfully.
337 if (!gMap.gl.getShaderParameter(fragShader, gMap.gl.COMPILE_STATUS)) {
338 console.log("An error occurred compiling the fragment shader: " + gMap.gl.getShaderInfoLog(fragShader));
342 console.log("Create and link shader program...");
343 gMap.glShaderProgram = gMap.gl.createProgram();
344 gMap.gl.attachShader(gMap.glShaderProgram, vertShader);
345 gMap.gl.attachShader(gMap.glShaderProgram, fragShader);
346 gMap.gl.linkProgram(gMap.glShaderProgram);
347 // If creating the shader program failed, alert
348 if (!gMap.gl.getProgramParameter(gMap.glShaderProgram, gMap.gl.LINK_STATUS)) {
349 alert("Unable to initialize the shader program.");
351 gMap.gl.useProgram(gMap.glShaderProgram);
352 // Get locations of the attributes.
353 gMap.glVertexPositionAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aVertexPosition");
354 gMap.glTextureCoordAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aTextureCoord");
355 gMap.glResolutionAttr = gMap.gl.getUniformLocation(gMap.glShaderProgram, "uResolution");
357 console.log("Set up vertex buffer...");
358 var tileVerticesBuffer = gMap.gl.createBuffer();
359 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, tileVerticesBuffer);
360 // The vertices are the coordinates of the corner points of the square.
369 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(vertices), gMap.gl.STATIC_DRAW);
370 gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr);
371 gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0);
373 gMap.loadImageToTexture(gLoadingTile, getTileKey("loading", {x: 0, y: 0, z: 0}));
375 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
377 // Create a buffer for the position of the rectangle corners.
378 console.log("Set up coord buffer...");
379 var mapVerticesTextureCoordBuffer = gMap.gl.createBuffer();
380 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer);
381 gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr);
382 gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0);
384 // Call texture cleaning every 30 seconds, for now (is 60 better?).
385 gMap.glTxCleanIntervalID = window.setInterval(gMap.cleanTextures, 30 * 1000);
389 // We may be called when context was lost and destroyed,
390 // only send event when we are in app startup
391 // (gAppInitDone is set to true right after we return this event).
392 var throwEv = new CustomEvent("mapinit-done");
393 gAction.dispatchEvent(throwEv);
399 gTrackLayer.drawTrack();
402 assembleGL: function() {
403 if (!gMap.gl) { return; }
405 document.getElementById("zoomLevel").textContent = gMap.pos.z;
406 gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
407 gMap.baseDim.wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor;
408 gMap.baseDim.ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor;
409 gMap.baseDim.tsize = gMap.tileSize * gMap.zoomFactor;
411 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
412 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
413 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
414 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
416 if (gMapPrefsLoaded && mainDB)
417 gPrefs.set("position", gMap.pos);
419 // Go through all the tiles in the map, find out if to draw them and do so.
420 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
421 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
422 // Only go to loading step if we haven't loaded the texture.
423 var coords = {x: x, y: y, z: gMap.pos.z};
424 var tileKey = getTileKey(gMap.activeMap, normalizeCoords(coords));
425 if (!gMap.glTextures[tileKey]) {
426 // Initiate loading/drawing of the actual tile.
427 gTileService.get(gMap.activeMap, coords,
428 function(aImage, aStyle, aCoords, aTileKey) {
429 // Only actually load if this still applies for the current view.
430 if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) {
431 var URL = window.URL;
432 var imgURL = URL.createObjectURL(aImage);
433 var imgObj = new Image();
434 imgObj.onload = function() {
435 gMap.loadImageToTexture(imgObj, aTileKey);
436 gMap.requestDrawGL();
437 URL.revokeObjectURL(imgURL);
445 gMap.requestDrawGL();
448 requestDrawGL: function() {
449 // Only draw if we're actually visible.
450 // Also, avoid running this multiple times when it could not complete yet.
451 if (document.hidden != true && !gMap.glDrawRequested) {
452 gMap.glDrawRequested = true;
453 window.requestAnimationFrame(gMap.drawGL);
457 drawGL: function(aTimestamp) {
458 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
459 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
460 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
461 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
463 // Go through all the tiles in the map, find out if to draw them and do so.
464 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
465 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
466 // Rounding the pixel offsets ensures we position the tiles precisely.
467 var xoff = Math.round((x * gMap.baseDim.tsize - xMin) / gMap.zoomFactor);
468 var yoff = Math.round((y * gMap.baseDim.tsize - yMin) / gMap.zoomFactor);
469 // Draw the tile, first find out the actual texture to use.
470 var norm = normalizeCoords({x: x, y: y, z: gMap.pos.z});
471 var tileKey = getTileKey(gMap.activeMap, norm);
472 if (!gMap.glTextures[tileKey]) {
473 tileKey = getTileKey("loading", {x: 0, y: 0, z: 0});
475 gMap.drawTileGL(xoff, yoff, tileKey);
478 gMap.glDrawRequested = false;
481 resizeAndDraw: function() {
482 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
483 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
484 if (gGLMapCanvas && gTrackCanvas) {
485 gGLMapCanvas.width = viewportWidth;
486 gGLMapCanvas.height = viewportHeight;
487 gTrackCanvas.width = viewportWidth;
488 gTrackCanvas.height = viewportHeight;
490 // Size viewport to canvas size.
491 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
493 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT);
494 // Make sure the vertex shader get the right resolution.
495 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
496 // Prepare recalculation of textures to keep for one zoom level.
497 gMap.glTexturesPerZoomLevel = 0;
504 drawTileGL: function(aLeft, aRight, aTileKey) {
505 gMap.gl.activeTexture(gMap.gl.TEXTURE0);
506 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
507 // Set uImage to refer to TEXTURE0
508 gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0);
510 var i_width = gMap.tileSize;
511 var y_start = aRight;
512 var i_height = gMap.tileSize;
513 var textureCoordinates = [
515 x_start + i_width, y_start,
516 x_start, y_start + i_height,
517 x_start, y_start + i_height,
518 x_start + i_width, y_start,
519 x_start + i_width, y_start + i_height,
521 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW);
523 // There are 6 indices in textureCoordinates.
524 gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
527 loadImageToTexture: function(aImage, aTileKey) {
528 // Create and bind texture.
529 gMap.glTextures[aTileKey] = gMap.gl.createTexture();
530 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
531 // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two).
532 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST);
533 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST);
534 // Upload the image into the texture.
535 gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage);
538 cleanTextures: function() {
539 // Get rid of unneeded textures to save memory.
540 // TODO: Be less aggressive, maybe keep neighboring zoom levels (but x/y coords there are zoom-specific).
541 if (!gMap.glTexturesPerZoomLevel) {
542 // Calculate how many textures we need to keep for one zoom level.
543 // ceil(width/size) gives us the minimum, keep one on either side as well.
544 gMap.glTexturesPerZoomLevel =
545 Math.ceil(gMap.gl.drawingBufferWidth / gMap.tileSize + 2) *
546 Math.ceil(gMap.gl.drawingBufferHeight / gMap.tileSize + 2);
547 console.log("Keeping " + gMap.glTexturesPerZoomLevel + " textures per level");
549 if (Object.keys(gMap.glTextures).length > gMap.glTexturesPerZoomLevel) {
550 console.log("Cleaning textures... (have " + Object.keys(gMap.glTextures).length + " atm)");
552 // Find coordinate ranges for tiles to keep.
553 var tMin = normalizeCoords({x: Math.floor((gMap.pos.x - gMap.baseDim.wid / 2) / gMap.baseDim.tsize) - 1,
554 y: Math.floor((gMap.pos.y - gMap.baseDim.ht / 2) / gMap.baseDim.tsize) - 1,
556 var tMax = normalizeCoords({x: Math.ceil((gMap.pos.x + gMap.baseDim.wid / 2) / gMap.baseDim.tsize) + 1,
557 y: Math.ceil((gMap.pos.y + gMap.baseDim.ht / 2) / gMap.baseDim.tsize) + 1,
559 console.log("In range: " + tMin.x + "," + tMin.y + "," + tMin.z + " - " + tMax.x + "," + tMax.y + "," + tMax.z);
560 for (var tileKey in gMap.glTextures) {
561 var keyMatches = tileKey.match(/([^:]+)::(\d+),(\d+),(\d+)/);
562 if (keyMatches && keyMatches[1] != "loading") {
564 style: keyMatches[1],
570 if (txData.style != gMap.activeMap) { delTx = true; console.log("Different map style: " + txData.style); }
571 if (!delTx && (txData.z < tMin.z || txData.z > tMax.z)) { delTx = true; console.log("Out-of-range zoom: " + txData.z); }
572 if (tMin.x < tMax.x) {
573 if (!delTx && (txData.x < tMin.x || txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
576 // We are crossing over the 0 coordinate!
577 if (!delTx && (txData.x < tMin.x && txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
579 if (tMin.y < tMax.y) {
580 if (!delTx && (txData.y < tMin.y || txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
583 // We are crossing over the 0 coordinate!
584 if (!delTx && (txData.y < tMin.y && txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
587 // Delete texture from GL and from the array we are holding.
588 gMap.gl.deleteTexture(gMap.glTextures[tileKey]);
589 delete gMap.glTextures[tileKey];
593 console.log("Cleaning complete, " + Object.keys(gMap.glTextures).length + " textures left");
597 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
598 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
601 if (gMap.pos.z < gMap.maxZoom) {
607 zoomOut: function() {
608 if (gMap.pos.z > 0) {
614 zoomTo: function(aTargetLevel) {
615 aTargetLevel = parseInt(aTargetLevel);
616 if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) {
617 gMap.pos.z = aTargetLevel;
622 setActiveMap: function(aStyle) {
623 gMap.activeMap = aStyle;
624 gPrefs.set("active_map_style", gMap.activeMap);
625 document.getElementById("copyright").innerHTML =
626 gMapStyles[gMap.activeMap].copyright;
627 if (!gWaitCounter) { // Only do this when prefs are loaded already.
633 handleContextLost: function(event) {
634 event.preventDefault();
635 // GL context is gone, let's reset everything that depends on it.
636 clearInterval(gMap.glTxCleanIntervalID);
637 gMap.glTextures = {};
640 handleContextRestored: function(event) {
641 // When GL context is back, init GL again and draw.
649 curPosMapCache: undefined,
650 lastDrawnPoint: null,
651 lastRequestedIndex: null, // may not have been actually drawn...
652 drawRequested: false,
653 restartDrawing: true,
655 maxDrawTime: 10, // max time allowed for drawing a section, in ms - 10 means we can do 100 fps smoothly
656 trackWidth: 2, // pixels
657 trackColor: "#FF0000",
658 curLocSize: 6, // pixels
659 curLocColor: "#A00000",
661 drawTrack: function(needRestart = true) {
662 // TODO: figure out if we can support reverse drawing while initially loading the track.
663 // Only draw if we're actually visible.
664 // Also, avoid running this multiple times when it could not complete yet.
665 if (needRestart) { gTrackLayer.restartDrawing = true; }
666 if (gTrackLayer.context && document.hidden != true && !gTrackLayer.drawRequested) {
667 gTrackLayer.drawRequested = true;
668 window.requestAnimationFrame(gTrackLayer.drawTrackSection);
672 drawTrackSection: function(aTimestamp) {
673 var start = performance.now();
674 if (gTrackLayer.restartDrawing) {
675 gTrackLayer.lastRequestedIndex = 0;
676 gTrackLayer.lastDrawnPoint = null;
677 gTrackLayer.restartDrawing = false;
678 gTrackLayer.curPosMapCache = undefined;
679 gTrackLayer.context.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
681 if (gTrack.length && (performance.now() < start + gTrackLayer.maxDrawTime)) {
682 for (; gTrackLayer.lastRequestedIndex < gTrack.length; gTrackLayer.lastRequestedIndex++) {
683 gTrackLayer.drawTrackPoint(gTrackLayer.lastRequestedIndex);
684 if (performance.now() >= start + gTrackLayer.maxDrawTime) {
685 // Break out of the loop if we are over the max allowed time, we'll continue in the next rAF (see below).
686 gTrackLayer.drawTrackPoint(null);
691 // If we still have work to do and we're still visible, continue drawing.
692 if ((gTrackLayer.lastRequestedIndex + 1 < gTrack.length) && gTrackLayer.context && (document.hidden != true)) {
693 window.requestAnimationFrame(gTrackLayer.drawTrackSection);
695 gTrackLayer.drawRequested = false;
698 drawTrackPoint: function(aIndex) {
699 gTrackLayer.running = true;
700 if (!aIndex && aIndex !== 0) {
701 // We can be called this way to make sure we draw an actual line up to where we are right now.
702 if (gTrackLayer.lastDrawnPoint && gTrackLayer.lastDrawnPoint.optimized) {
703 gTrackLayer.context.stroke();
704 gTrackLayer.lastDrawnPoint.optimized = false;
708 var trackpoint = {"worldpos": gps2xy(gTrack[aIndex].coords.latitude, gTrack[aIndex].coords.longitude)};
709 var isLastPoint = (aIndex + 1 >= gTrack.length || gTrack[aIndex+1].beginSegment);
710 var update_drawnpoint = true;
711 // lastPoint is for optimizing (not actually executing the draw until the last)
712 trackpoint.segmentEnd = (isLastPoint === true);
713 trackpoint.optimized = (isLastPoint === false);
714 trackpoint.mappos = {x: Math.round((trackpoint.worldpos.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
715 y: Math.round((trackpoint.worldpos.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
716 trackpoint.skip_drawing = false;
717 if (gTrackLayer.lastDrawnPoint) {
718 // Lines completely outside the current display should not be drawn.
719 if ((trackpoint.mappos.x < 0 && gTrackLayer.lastDrawnPoint.mappos.x < 0) ||
720 (trackpoint.mappos.x > gMap.width && gTrackLayer.lastDrawnPoint.mappos.x > gMap.width) ||
721 (trackpoint.mappos.y < 0 && gTrackLayer.lastDrawnPoint.mappos.y < 0) ||
722 (trackpoint.mappos.y > gMap.height && gTrackLayer.lastDrawnPoint.mappos.y > gMap.height)) {
723 trackpoint.skip_drawing = true;
726 if (!gTrackLayer.lastDrawnPoint || !gTrackLayer.lastDrawnPoint.optimized) {
727 gTrackLayer.context.strokeStyle = gTrackLayer.trackColor;
728 gTrackLayer.context.fillStyle = gTrackLayer.context.strokeStyle;
729 gTrackLayer.context.lineWidth = gTrackLayer.trackWidth;
730 gTrackLayer.context.lineCap = "round";
731 gTrackLayer.context.lineJoin = "round";
733 // This breaks optimiziation, so make sure to reset optimization.
734 if (trackpoint.skip_drawing || !gTrackLayer.lastDrawnPoint) {
735 trackpoint.optimized = false;
736 // Close path if one was open.
737 if (gTrackLayer.lastDrawnPoint && gTrackLayer.lastDrawnPoint.optimized) {
738 gTrackLayer.context.stroke();
741 if (!trackpoint.skip_drawing) {
742 if (gTrackLayer.lastDrawnPoint && gTrackLayer.lastDrawnPoint.skip_drawing && !gTrackLayer.lastDrawnPoint.segmentEnd) {
743 // If the last point was skipped but the current one isn't, draw a segment start
744 // for the off-screen previous one as well as a connection line.
745 gTrackLayer.context.beginPath();
746 gTrackLayer.context.arc(gTrackLayer.lastDrawnPoint.mappos.x, gTrackLayer.lastDrawnPoint.mappos.y,
747 gTrackLayer.context.lineWidth, 0, Math.PI * 2, false);
748 gTrackLayer.context.fill();
749 gTrackLayer.context.lineTo(trackpoint.mappos.x, trackpoint.mappos.y);
751 else if (!gTrackLayer.lastDrawnPoint || !gTrackLayer.lastDrawnPoint.optimized) {
752 // Start drawing a segment with the current point.
753 gTrackLayer.context.beginPath();
754 gTrackLayer.context.arc(trackpoint.mappos.x, trackpoint.mappos.y,
755 gTrackLayer.context.lineWidth, 0, Math.PI * 2, false);
756 gTrackLayer.context.fill();
758 else if (!trackpoint.segmentEnd && gTrackLayer.lastDrawnPoint &&
759 (Math.abs(gTrackLayer.lastDrawnPoint.mappos.x - trackpoint.mappos.x) <= 1) &&
760 (Math.abs(gTrackLayer.lastDrawnPoint.mappos.y - trackpoint.mappos.y) <= 1)) {
761 // We would draw the same or almost the same point, don't do any actual drawing.
762 update_drawnpoint = false;
765 // Continue drawing segment, close if needed.
766 gTrackLayer.context.lineTo(trackpoint.mappos.x, trackpoint.mappos.y);
767 if (!trackpoint.optimized)
768 gTrackLayer.context.stroke();
771 if (update_drawnpoint) {
772 gTrackLayer.lastDrawnPoint = trackpoint;
776 drawCurrentLocation: function(trackPoint) {
777 // Only run this when visible and we are not drawing a track right now.
778 if (gTrackLayer.context && document.hidden != true && !gTrackLayer.drawRequested) {
779 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
780 var circleRadius = Math.round(gTrackLayer.curLocSize / 2);
781 var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
782 y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
784 gTrackLayer.undrawCurrentLocation();
786 // Cache overdrawn area.
787 gTrackLayer.curPosMapCache =
789 radius: circleRadius,
790 data: gTrackLayer.context.getImageData(mappos.x - circleRadius,
791 mappos.y - circleRadius,
792 circleRadius * 2, circleRadius * 2)};
794 gTrackLayer.context.strokeStyle = gTrackLayer.curLocColor;
795 gTrackLayer.context.fillStyle = gTrackLayer.context.strokeStyle;
796 gTrackLayer.context.beginPath();
797 gTrackLayer.context.arc(mappos.x, mappos.y,
798 circleRadius, 0, Math.PI * 2, false);
799 gTrackLayer.context.fill();
803 undrawCurrentLocation: function() {
804 // Only run this when visible and we are not drawing a track right now.
805 if (gTrackLayer.context && document.hidden != true && !gTrackLayer.drawRequested) {
806 if (gTrackLayer.curPosMapCache) {
807 var oldpoint = gTrackLayer.curPosMapCache.point;
808 var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
809 y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
810 gTrackLayer.context.putImageData(gTrackLayer.curPosMapCache.data,
811 oldmp.x - gTrackLayer.curPosMapCache.radius,
812 oldmp.y - gTrackLayer.curPosMapCache.radius);
813 gTrackLayer.curPosMapCache = undefined;
819 function gps2xy(aLatitude, aLongitude) {
820 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
821 var convLat = aLatitude * Math.PI / 180;
822 var rawY = (1 - Math.log(Math.tan(convLat) +
823 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
824 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
825 return {x: Math.round(rawX),
826 y: Math.round(rawY)};
829 function xy2gps(aX, aY) {
830 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
831 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
832 return {latitude: 180 / Math.PI *
833 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
834 longitude: aX / maxZoomFactor * 360 - 180};
837 // A sane mod function that works for negative numbers.
840 return ((a % b) + b) % b;
843 function normalizeCoords(aCoords) {
844 var zoomFactor = Math.pow(2, aCoords.z);
845 return {x: mod(aCoords.x, zoomFactor),
846 y: mod(aCoords.y, zoomFactor),
850 function getTileKey(aStyle, aNormalizedCoords) {
851 return aStyle + "::" +
852 aNormalizedCoords.x + "," +
853 aNormalizedCoords.y + "," +
857 // Returns true if the tile is outside the current view.
858 function isOutsideWindow(t) {
859 var pos = decodeIndex(t);
861 var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z);
862 var wid = gMap.width * zoomFactor;
863 var ht = gMap.height * zoomFactor;
868 var sz = gMap.tileSize * zoomFactor;
869 if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 ||
870 pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2)
875 function encodeIndex(x, y, z) {
876 var norm = normalizeCoords({x: x, y: y, z: z});
877 return norm.x + "," + norm.y + "," + norm.z;
880 function decodeIndex(encodedIdx) {
881 var ind = encodedIdx.split(",", 3);
882 return {x: ind[0], y: ind[1], z: ind[2]};
885 function calcTrackDuration() {
886 // Get the duration of the track in s.
888 if (gTrack.length > 1) {
889 for (var i = 1; i < gTrack.length; i++) {
890 if (!gTrack[i].beginSegment) {
891 tDuration += (gTrack[i].time - gTrack[i-1].time);
895 return Math.round(tDuration / 1000); // The timestamps are in ms but we return seconds.
898 function calcTrackLength() {
899 // Get the length of the track in km.
901 if (gTrack.length > 1) {
902 for (var i = 1; i < gTrack.length; i++) {
903 if (!gTrack[i].beginSegment) {
904 tLength += getPointDistance(gTrack[i-1].coords, gTrack[i].coords);
911 function getPointDistance(aGPSPoint1, aGPSPoint2) {
912 // Get the distance in km between the two given GPS points.
913 // See http://stackoverflow.com/questions/365826/calculate-distance-between-2-gps-coordinates
914 // Earth is almost exactly a sphere and we calculate small distances on the surface, so we can do spherical great-circle math.
915 // Also see http://en.wikipedia.org/wiki/Great-circle_distance
917 var dLat = deg2rad(aGPSPoint2.latitude - aGPSPoint1.latitude);
918 var dLon = deg2rad(aGPSPoint2.longitude - aGPSPoint1.longitude);
919 var lat1 = deg2rad(aGPSPoint1.latitude);
920 var lat2 = deg2rad(aGPSPoint2.latitude);
922 var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
923 Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
924 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
928 function deg2rad(aDegreeValue) {
929 // Convert an angle in degrees to radiants.
930 return aDegreeValue * (Math.PI / 180);
934 handleEvent: function(aEvent) {
935 var touchEvent = aEvent.type.indexOf('touch') != -1;
938 aEvent.stopPropagation();
941 // Bail out if the event is happening on an input.
942 if (aEvent.target.tagName.toLowerCase() == "input")
945 // Bail out on unwanted map moves, but not zoom or keyboard events.
946 if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
947 // Bail out if this is neither a touch nor left-click.
948 if (!touchEvent && aEvent.button != 0)
951 // Bail out if the started touch can't be found.
952 if (touchEvent && gDragging &&
953 !aEvent.targetTouches.item(0))
957 var coordObj = touchEvent ?
958 aEvent.targetTouches.item(0) :
961 switch (aEvent.type) {
965 if (aEvent.targetTouches.length == 2) {
966 gPinchStartWidth = Math.sqrt(
967 Math.pow(aEvent.targetTouches.item(1).clientX -
968 aEvent.targetTouches.item(0).clientX, 2) +
969 Math.pow(aEvent.targetTouches.item(1).clientY -
970 aEvent.targetTouches.item(0).clientY, 2)
973 coordObj = aEvent.targetTouches.item(0);
975 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
976 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
978 if (touchEvent || aEvent.button === 0) {
984 gLastMoveAction = performance.now();
988 if (touchEvent && aEvent.targetTouches.length == 2) {
989 curPinchStartWidth = Math.sqrt(
990 Math.pow(aEvent.targetTouches.item(1).clientX -
991 aEvent.targetTouches.item(0).clientX, 2) +
992 Math.pow(aEvent.targetTouches.item(1).clientY -
993 aEvent.targetTouches.item(0).clientY, 2)
995 if (!gPinchStartWidth)
996 gPinchStartWidth = curPinchStartWidth;
998 if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
999 gPinchStartWidth / curPinchStartWidth < 0.6) {
1000 var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
1001 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
1002 // Calculate new center of the map - preserve middle of pinch.
1003 // This means that pixel distance between old center and middle
1004 // must equal pixel distance of new center and middle.
1005 var x = (aEvent.targetTouches.item(1).clientX +
1006 aEvent.targetTouches.item(0).clientX) / 2 -
1007 gGLMapCanvas.offsetLeft;
1008 var y = (aEvent.targetTouches.item(1).clientY +
1009 aEvent.targetTouches.item(0).clientY) / 2 -
1010 gGLMapCanvas.offsetTop;
1012 // Zoom factor after this action.
1013 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
1014 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
1015 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
1017 if (gPinchStartWidth < curPinchStartWidth)
1022 // Reset pinch start width and start another pinch gesture.
1023 gPinchStartWidth = null;
1026 // If we are in a pinch, do not drag.
1029 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
1030 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
1031 if (gDragging === true) {
1032 var dX = x - gLastMouseX;
1033 var dY = y - gLastMouseY;
1034 gMap.pos.x -= dX * gMap.zoomFactor;
1035 gMap.pos.y -= dY * gMap.zoomFactor;
1041 gLastMoveAction = performance.now();
1045 gPinchStartWidth = null;
1052 //gDragging = false;
1055 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
1056 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
1058 // Only accept (non-null) deltaY values
1062 // Debug output: "coordinates" of the point the mouse was over.
1064 var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor,
1065 y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor};
1066 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
1067 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
1068 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
1069 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
1070 pt2Coord.x + "/" + pt2Coord.y);
1073 var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1);
1074 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
1075 // Calculate new center of the map - same point stays under the mouse.
1076 // This means that the pixel distance between the old center and point
1077 // must equal the pixel distance of the new center and that point.
1078 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
1079 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
1081 // Zoom factor after this action.
1082 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
1083 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
1084 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
1086 if (aEvent.deltaY < 0)
1093 // Allow keyboard control to move and zoom the map.
1094 // Should use aEvent.key instead of aEvent.which but needs bug 680830.
1095 // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
1098 switch (aEvent.which) {
1100 dX = -gMap.tileSize / 2;
1103 dX = gMap.tileSize / 2;
1106 dY = gMap.tileSize / 2;
1109 dY = -gMap.tileSize / 2;
1112 case 107: // + (numpad)
1113 case 171: // + (normal key)
1117 case 109: // - (numpad)
1118 case 173: // - (normal key)
1130 gMap.zoomTo(aEvent.which - 38);
1135 case 96: // 0 (numpad)
1136 case 97: // 1 (numpad)
1137 case 98: // 2 (numpad)
1138 case 99: // 3 (numpad)
1139 case 100: // 4 (numpad)
1140 case 101: // 5 (numpad)
1141 case 102: // 6 (numpad)
1142 case 103: // 7 (numpad)
1143 case 104: // 8 (numpad)
1144 gMap.zoomTo(aEvent.which - 86);
1146 case 105: // 9 (numpad)
1149 default: // not supported
1150 console.log("key not supported: " + aEvent.which);
1156 gMap.pos.x -= dX * gMap.zoomFactor;
1157 gMap.pos.y -= dY * gMap.zoomFactor;
1159 gLastMoveAction = performance.now();
1166 function visibilityEvHandler() {
1167 // Immediately draw if we just got visible.
1168 if (document.hidden != true) {
1171 // No need to handle the event where we become invisible as we care only draw
1172 // when we are visible anyhow.
1177 lastPos: {x: undefined, y: undefined},
1178 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
1179 this.tracking = true;
1180 var watchCall = function() {
1181 // calc new position in lat/lon degrees
1182 // 90° on Earth surface are ~10,000 km at the equator,
1183 // so try moving at most 10m at a time
1184 if (geofake.lastPos.x)
1185 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
1187 geofake.lastPos.x = 48.208174
1188 if (geofake.lastPos.y)
1189 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
1191 geofake.lastPos.y = 16.373819
1192 aSuccessCallback({timestamp: Date.now(),
1193 coords: {latitude: geofake.lastPos.x,
1194 longitude: geofake.lastPos.y,
1196 if (geofake.tracking)
1197 setTimeout(watchCall, 1000);
1199 setTimeout(watchCall, 1000);
1202 clearWatch: function(aID) {
1203 this.tracking = false;
1207 function setCentering(aCheckbox) {
1208 if (gMapPrefsLoaded && mainDB)
1209 gPrefs.set("center_map", aCheckbox.checked);
1210 gCenterPosition = aCheckbox.checked;
1213 function setTracking(aCheckbox) {
1214 if (gMapPrefsLoaded && mainDB)
1215 gPrefs.set("tracking_enabled", aCheckbox.checked);
1216 if (aCheckbox.checked)
1222 function startTracking() {
1224 gActionLabel.textContent = "Establishing Position";
1225 gAction.style.display = "block";
1226 if (navigator.requestWakeLock) {
1227 gGPSWakeLock = navigator.requestWakeLock("gps");
1229 gGeoWatchID = gGeolocation.watchPosition(
1230 function(position) {
1231 if (gActionLabel.textContent) {
1232 gActionLabel.textContent = "";
1233 gAction.style.display = "none";
1235 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
1236 var tPoint = {time: position.timestamp,
1237 coords: {latitude: position.coords.latitude,
1238 longitude: position.coords.longitude,
1239 altitude: position.coords.altitude,
1240 accuracy: position.coords.accuracy,
1241 altitudeAccuracy: position.coords.altitudeAccuracy,
1242 heading: position.coords.heading,
1243 speed: position.coords.speed},
1244 beginSegment: !gLastTrackPoint};
1245 // Only add point to track is accuracy is good enough.
1246 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
1247 gLastTrackPoint = tPoint;
1248 gTrack.push(tPoint);
1249 try { gTrackStore.push(tPoint); } catch(e) {}
1250 var redrawn = false;
1251 if (gCenterPosition && (!gLastMoveAction || performance.now() > gLastMoveAction + gCenterDelayAfterMove)) {
1252 var posCoord = gps2xy(position.coords.latitude,
1253 position.coords.longitude);
1254 if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 ||
1255 Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) {
1256 gMap.pos.x = posCoord.x;
1257 gMap.pos.y = posCoord.y;
1258 gMap.draw(); // This draws the current point as well.
1263 gTrackLayer.undrawCurrentLocation();
1264 gTrackLayer.drawTrackPoint(gTrack.length-1);
1266 gTrackLayer.drawCurrentLocation(tPoint);
1269 // Ignore erros for the moment, but this is good for debugging.
1270 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
1272 console.log(error.message);
1274 {enableHighAccuracy: true}
1279 function endTracking() {
1280 if (gActionLabel.textContent) {
1281 gActionLabel.textContent = "";
1282 gAction.style.display = "none";
1284 if (navigator.requestWakeLock && gGPSWakeLock) {
1285 console.log("releasing WakeLock");
1286 gGPSWakeLock.unlock();
1289 gGeolocation.clearWatch(gGeoWatchID);
1293 function clearTrack() {
1295 gTrackStore.clear();
1296 gTrackLayer.drawTrack();
1299 function loadTrackFromBackend(aTrackId, aFeedbackElement, aSuccessCallback) {
1300 if (aFeedbackElement) {
1301 aFeedbackElement.textContent = "Loading...";
1302 // If someone loads without pointing to UI (e.g. for debugging), we just overwrite whatever's loaded.
1303 if (calcTrackLength() > 1) {
1304 aFeedbackElement.textContent = "Track >1km loaded, please save/clear.";
1305 aFeedbackElement.classList.add("error");
1309 fetchBackend("track_json?id=" + encodeURIComponent(aTrackId), "GET", null,
1310 function(aResult, aStatusCode) {
1311 if (aStatusCode >= 400) {
1312 console.log("loading track failed: " + aStatusCode + ", result: " + aResult.message);
1313 if (aFeedbackElement) {
1314 aFeedbackElement.textContent = "Error: " + aResult;
1315 aFeedbackElement.classList.add("error");
1320 if (aSuccessCallback) {
1324 else { // If no result is returned, we assume a general error.
1325 console.log("Error getting track with ID " + aTrackId + " from backend.");
1326 if (aFeedbackElement) {
1327 aFeedbackElement.textContent = "Error fetching track from backend.";
1328 aFeedbackElement.classList.add("error");
1335 function loadTrack(aTrack) {
1336 console.log("Loading track with " + aTrack.length + " points.");
1338 gTrackStore.clear(function(aSuccess, aEvent) {
1339 for (var i = 0; i < gTrack.length; i++) {
1340 try { gTrackStore.push(gTrack[i]); } catch(e) {}
1343 gTrackLayer.drawTrack(); // Draws from gTrack, so not problem that gTrackStore is filled async.
1346 var gTileService = {
1347 objStore: "tilecache",
1349 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
1351 get: function(aStyle, aCoords, aCallback) {
1352 var norm = normalizeCoords(aCoords);
1353 var dbkey = getTileKey(aStyle, norm);
1354 this.getDBCache(dbkey, function(aResult, aEvent) {
1356 // We did get a cached object.
1357 aCallback(aResult.image, aStyle, aCoords, dbkey);
1358 // Look at the timestamp and return if it's not too old.
1359 if (aResult.timestamp + gTileService.ageLimit > Date.now())
1361 // Reload cached tile otherwise.
1362 var oldDate = new Date(aResult.timestamp);
1363 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
1365 // Retrieve image from the web and store it in the cache.
1366 var XHR = new XMLHttpRequest();
1368 gMapStyles[aStyle].url
1369 .replace("{x}", norm.x)
1370 .replace("{y}", norm.y)
1371 .replace("{z}", norm.z)
1372 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 3)))
1373 .replace("[a-d]", String.fromCharCode(97 + Math.floor(Math.random() * 4)))
1374 .replace("[1-4]", 1 + Math.floor(Math.random() * 4)),
1376 XHR.responseType = "blob";
1377 XHR.addEventListener("load", function () {
1378 if (XHR.status === 200) {
1379 var blob = XHR.response;
1380 aCallback(blob, aStyle, aCoords, dbkey);
1381 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
1388 getDBCache: function(aKey, aCallback) {
1391 var transaction = mainDB.transaction([this.objStore]);
1392 var request = transaction.objectStore(this.objStore).get(aKey);
1393 request.onsuccess = function(event) {
1394 aCallback(request.result, event);
1396 request.onerror = function(event) {
1397 // Errors can be handled here.
1398 aCallback(undefined, event);
1402 setDBCache: function(aKey, aValue, aCallback) {
1405 var success = false;
1406 var transaction = mainDB.transaction([this.objStore], "readwrite");
1407 var objStore = transaction.objectStore(this.objStore);
1408 var request = objStore.put(aValue, aKey);
1409 request.onsuccess = function(event) {
1412 aCallback(success, event);
1414 request.onerror = function(event) {
1415 // Errors can be handled here.
1417 aCallback(success, event);
1421 unsetDBCache: function(aKey, aCallback) {
1424 var success = false;
1425 var transaction = mainDB.transaction([this.objStore], "readwrite");
1426 var request = transaction.objectStore(this.objStore).delete(aKey);
1427 request.onsuccess = function(event) {
1430 aCallback(success, event);
1432 request.onerror = function(event) {
1433 // Errors can be handled here.
1435 aCallback(success, event);
1439 clearDB: function(aCallback) {
1442 var success = false;
1443 var transaction = mainDB.transaction([this.objStore], "readwrite");
1444 var request = transaction.objectStore(this.objStore).clear();
1445 request.onsuccess = function(event) {
1447 console.log("Cache cleared.");
1449 aCallback(success, event);
1451 request.onerror = function(event) {
1452 // Errors can be handled here.
1453 console.log("Error clearing cache!");
1455 aCallback(success, event);