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: "ArcGIS World Imagery", // see https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer
49 url: "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
50 copyright: 'Source: Esri, Maxar, GeoEye, Earthstar Geographics, CNES/Airbus DS, USDA, USGS, AeroGRID, IGN, and the GIS User Community.'},
52 {name: "OSM HOT style",
53 url: "https://tilecache[1-4].kairo.at/osmhot/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
54 //url: "http://[a-c].tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", // https has CAcert which doesn't work in browsers
55 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>'},
58 //url: "https://tilecache[1-4].kairo.at/opentopomap/{z}/{x}/{y}.png", // route through tilecache @ kairo.at
59 url: "https://[a-c].tile.opentopomap.org/{z}/{x}/{y}.png",
60 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>)'},
62 {name: "Hike and Bike (OSM)",
63 url: "https://tilecache[1-4].kairo.at/hikebike/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
64 //url: "http://toolserver.org/tiles/hikebike/{z}/{x}/{y}.png", // toolserver.org does not support CORS at this time :(
65 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>'},
67 {name: "Outdoors (OSM)",
68 url: "https://[a-c].tile.thunderforest.com/outdoors/{z}/{x}/{y}.png", // url: "http://[a-c].tile.opencyclemap.org/outdoors/{z}/{x}/{y}.png",
69 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>.'},
71 {name: "Stamen Toner (B+W)",
72 url: "https://tilecache[1-4].kairo.at/toner/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
73 //url: "http://[a-c].tile.stamen.com/toner/{z}/{x}/{y}.jpg", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
74 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>.'},
76 {name: "Stamen Terrain (USA only)",
77 url: "https://tilecache[1-4].kairo.at/terrain/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
78 //url: "http://[a-c].tile.stamen.com/terrain/{z}/{x}/{y}.jpg", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
79 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>.'},
81 {name: "Stamen Watercolor (artistic)",
82 url: "https://tilecache[1-4].kairo.at/watercolor/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
83 //url: "http://[a-c].tile.stamen.com/watercolor/{z}/{x}/{y}.jpg", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
84 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>.'},
92 var gMapPrefsLoaded = false;
94 var gDragging = false;
95 var gDragTouchID, gPinchStartWidth;
97 var gGeoWatchID, gGPSWakeLock;
100 var gCenterPosition = true;
101 var gLastMoveAction = null;
104 gGeolocation = navigator.geolocation;
105 // Set up canvas context.
106 gGLMapCanvas = document.getElementById("map");
108 // Try to grab the standard context. If it fails, fallback to experimental.
109 // We also try to tell it we do not need a depth buffer.
110 gMap.gl = gGLMapCanvas.getContext("webgl", {depth: false}) ||
111 gGLMapCanvas.getContext("experimental-webgl", {depth: false});
115 // If we don't have a GL context, give up now
116 showGLWarningDialog();
120 // GL context can be lost at any time, handle that.
121 // See http://www.khronos.org/webgl/wiki/HandlingContextLost
122 gGLMapCanvas.addEventListener("webglcontextlost",
123 gMap.handleContextLost, false);
124 gGLMapCanvas.addEventListener("webglcontextrestored",
125 gMap.handleContextRestored, false);
127 gTrackCanvas = document.getElementById("track");
128 gTrackLayer.context = gTrackCanvas.getContext("2d");
132 gGeolocation = geofake;
133 var hiddenList = document.getElementsByClassName("debugHide");
134 // last to first - list of elements with that class is changing!
135 for (var i = hiddenList.length - 1; i >= 0; i--) {
136 hiddenList[i].classList.remove("debugHide");
140 gAction.addEventListener("prefload-done", gMap.initGL, false);
142 console.log("map vars set, loading prefs...");
146 function loadPrefs(aEvent) {
147 if (aEvent && aEvent.type == "prefs-step") {
148 console.log("wait: " + gWaitCounter);
149 if (gWaitCounter == 0) {
150 gAction.removeEventListener(aEvent.type, loadPrefs, false);
151 gMapPrefsLoaded = true;
152 console.log("prefs loaded.");
154 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
155 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
156 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
157 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
159 gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
160 gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
161 gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
162 gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
163 gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
165 gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
167 document.getElementById("body").addEventListener("keydown", mapEvHandler, false);
169 document.addEventListener("visibilitychange", visibilityEvHandler, false);
171 console.log("Events added.");
173 console.log("Init loading tile...");
174 gLoadingTile = new Image();
175 gLoadingTile.onload = function() {
176 console.log("Loading tile loaded.");
177 var throwEv = new CustomEvent("prefload-done");
178 gAction.dispatchEvent(throwEv);
180 console.log("Set loading tile...");
181 gLoadingTile.src = "style/loading.png";
186 gAction.removeEventListener(aEvent.type, loadPrefs, false);
187 gAction.addEventListener("prefs-step", loadPrefs, false);
189 gPrefs.get("active_map_style", function(aValue) {
190 if (aValue && gMapStyles[aValue]) {
191 gMap.activeMap = aValue;
194 gMap.activeMap = "osm_mapnik";
196 document.getElementById("mapSelector").value = gMap.activeMap;
197 document.getElementById("copyright").innerHTML =
198 gMapStyles[gMap.activeMap].copyright;
200 var throwEv = new CustomEvent("prefs-step");
201 gAction.dispatchEvent(throwEv);
204 gPrefs.get("position", function(aValue) {
205 if (aValue && aValue.x && aValue.y && aValue.z) {
209 var throwEv = new CustomEvent("prefs-step");
210 gAction.dispatchEvent(throwEv);
213 gPrefs.get("center_map", function(aValue) {
214 if (aValue === undefined) {
215 document.getElementById("centerCheckbox").checked = true;
218 document.getElementById("centerCheckbox").checked = aValue;
220 setCentering(document.getElementById("centerCheckbox"));
222 var throwEv = new CustomEvent("prefs-step");
223 gAction.dispatchEvent(throwEv);
226 gPrefs.get("tracking_enabled", function(aValue) {
227 if (aValue === undefined) {
228 document.getElementById("trackCheckbox").checked = true;
231 document.getElementById("trackCheckbox").checked = aValue;
234 var throwEv = new CustomEvent("prefs-step");
235 gAction.dispatchEvent(throwEv);
238 var trackLoadStarted = false;
239 var redrawBase = 100;
240 gTrackStore.getListStepped(function(aTPoint) {
242 // Add in front and return new length.
243 var tracklen = gTrack.unshift(aTPoint);
244 // Redraw track periodically, larger distance the longer it gets
245 // (but clamped to the first value over a certain limit).
246 // Initial paint will do initial track drawing.
247 if (tracklen % redrawBase == 0) {
248 gTrackLayer.drawTrack(); // TODO: we could draw incremmentally if we would support reverse-direction drawing...
249 if (redrawBase < 1000) {
250 redrawBase = tracklen;
255 // Last point received.
256 gTrackLayer.drawTrack(); // TODO: we could draw incremmentally if we would support reverse-direction drawing...
258 if (!trackLoadStarted) {
259 // We have the most recent point, if present, rest will load async.
260 trackLoadStarted = true;
262 var throwEv = new CustomEvent("prefs-step");
263 gAction.dispatchEvent(throwEv);
271 glShaderProgram: null,
272 glVertexPositionAttr: null,
273 glTextureCoordAttr: null,
274 glResolutionAttr: null,
277 glTxCleanIntervalID: null,
278 glTexturesPerZoomLevel: 0,
280 activeMap: "osm_mapnik",
282 maxZoom: 18, // The minimum is 0.
285 x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
286 y: 23670000.0, // The range is 0-67108864 (2^gMap.maxZoom * gMap.tileSize)
287 z: 5 // This could be fractional if supported being between zoom levels.
289 baseDim: { // Map width, height and tile size in level 18 pixels.
294 glDrawRequested: false, // To avoid parallel calls to drawGL().
296 get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; },
297 get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; },
299 getVertShaderSource: function() {
300 return 'attribute vec2 aVertexPosition;\n' +
301 'attribute vec2 aTextureCoord;\n\n' +
302 'uniform vec2 uResolution;\n\n' +
303 'varying highp vec2 vTextureCoord;\n\n' +
304 'void main(void) {\n' +
305 // convert the rectangle from pixels to -1.0 to +1.0 (clipspace) 0.0 to 1.0
306 ' vec2 clipSpace = aVertexPosition * 2.0 / uResolution - 1.0;\n' +
307 ' gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' +
308 ' vTextureCoord = aTextureCoord;\n' +
310 getFragShaderSource: function() {
311 return 'varying highp vec2 vTextureCoord;\n\n' +
312 'uniform sampler2D uImage;\n\n' +
313 'void main(void) {\n' +
314 ' gl_FragColor = texture2D(uImage, vTextureCoord);\n' +
318 // When called from the event listener, the "this" reference doesn't work, so use the object name.
319 console.log("Initializing WebGL...");
321 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
322 gMap.gl.clearColor(0.0, 0.0, 0.0, 0.5); // Set clear color to black, fully opaque.
323 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT|gMap.gl.DEPTH_BUFFER_BIT); // Clear the color.
325 // Create and initialize the shaders.
326 console.log("Create and compile shaders...");
327 var vertShader = gMap.gl.createShader(gMap.gl.VERTEX_SHADER);
328 var fragShader = gMap.gl.createShader(gMap.gl.FRAGMENT_SHADER);
329 gMap.gl.shaderSource(vertShader, gMap.getVertShaderSource());
330 // Compile the shader program.
331 gMap.gl.compileShader(vertShader);
332 // See if it compiled successfully.
333 if (!gMap.gl.getShaderParameter(vertShader, gMap.gl.COMPILE_STATUS)) {
334 console.log("An error occurred compiling the vertex shader: " + gMap.gl.getShaderInfoLog(vertShader));
337 gMap.gl.shaderSource(fragShader, gMap.getFragShaderSource());
338 // Compile the shader program.
339 gMap.gl.compileShader(fragShader);
340 // See if it compiled successfully.
341 if (!gMap.gl.getShaderParameter(fragShader, gMap.gl.COMPILE_STATUS)) {
342 console.log("An error occurred compiling the fragment shader: " + gMap.gl.getShaderInfoLog(fragShader));
346 console.log("Create and link shader program...");
347 gMap.glShaderProgram = gMap.gl.createProgram();
348 gMap.gl.attachShader(gMap.glShaderProgram, vertShader);
349 gMap.gl.attachShader(gMap.glShaderProgram, fragShader);
350 gMap.gl.linkProgram(gMap.glShaderProgram);
351 // If creating the shader program failed, alert
352 if (!gMap.gl.getProgramParameter(gMap.glShaderProgram, gMap.gl.LINK_STATUS)) {
353 alert("Unable to initialize the shader program.");
355 gMap.gl.useProgram(gMap.glShaderProgram);
356 // Get locations of the attributes.
357 gMap.glVertexPositionAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aVertexPosition");
358 gMap.glTextureCoordAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aTextureCoord");
359 gMap.glResolutionAttr = gMap.gl.getUniformLocation(gMap.glShaderProgram, "uResolution");
361 console.log("Set up vertex buffer...");
362 var tileVerticesBuffer = gMap.gl.createBuffer();
363 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, tileVerticesBuffer);
364 // The vertices are the coordinates of the corner points of the square.
373 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(vertices), gMap.gl.STATIC_DRAW);
374 gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr);
375 gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0);
377 gMap.loadImageToTexture(gLoadingTile, getTileKey("loading", {x: 0, y: 0, z: 0}));
379 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
381 // Create a buffer for the position of the rectangle corners.
382 console.log("Set up coord buffer...");
383 var mapVerticesTextureCoordBuffer = gMap.gl.createBuffer();
384 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer);
385 gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr);
386 gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0);
388 // Call texture cleaning every 30 seconds, for now (is 60 better?).
389 gMap.glTxCleanIntervalID = window.setInterval(gMap.cleanTextures, 30 * 1000);
393 // We may be called when context was lost and destroyed,
394 // only send event when we are in app startup
395 // (gAppInitDone is set to true right after we return this event).
396 var throwEv = new CustomEvent("mapinit-done");
397 gAction.dispatchEvent(throwEv);
403 gTrackLayer.drawTrack();
406 assembleGL: function() {
407 if (!gMap.gl) { return; }
409 document.getElementById("zoomLevel").textContent = gMap.pos.z;
410 gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
411 gMap.baseDim.wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor;
412 gMap.baseDim.ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor;
413 gMap.baseDim.tsize = gMap.tileSize * gMap.zoomFactor;
415 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
416 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
417 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
418 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
420 if (gMapPrefsLoaded && mainDB)
421 gPrefs.set("position", gMap.pos);
423 // Go through all the tiles in the map, find out if to draw them and do so.
424 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
425 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
426 // Only go to loading step if we haven't loaded the texture.
427 var coords = {x: x, y: y, z: gMap.pos.z};
428 var tileKey = getTileKey(gMap.activeMap, normalizeCoords(coords));
429 if (!gMap.glTextures[tileKey]) {
430 // Initiate loading/drawing of the actual tile.
431 gTileService.get(gMap.activeMap, coords,
432 function(aImage, aStyle, aCoords, aTileKey) {
433 // Only actually load if this still applies for the current view.
434 if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) {
435 var URL = window.URL;
436 var imgURL = URL.createObjectURL(aImage);
437 var imgObj = new Image();
438 imgObj.onload = function() {
439 gMap.loadImageToTexture(imgObj, aTileKey);
440 gMap.requestDrawGL();
441 URL.revokeObjectURL(imgURL);
449 gMap.requestDrawGL();
452 requestDrawGL: function() {
453 // Only draw if we're actually visible.
454 // Also, avoid running this multiple times when it could not complete yet.
455 if (document.hidden != true && !gMap.glDrawRequested) {
456 gMap.glDrawRequested = true;
457 window.requestAnimationFrame(gMap.drawGL);
461 drawGL: function(aTimestamp) {
462 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
463 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
464 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
465 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
467 // Go through all the tiles in the map, find out if to draw them and do so.
468 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
469 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
470 // Rounding the pixel offsets ensures we position the tiles precisely.
471 var xoff = Math.round((x * gMap.baseDim.tsize - xMin) / gMap.zoomFactor);
472 var yoff = Math.round((y * gMap.baseDim.tsize - yMin) / gMap.zoomFactor);
473 // Draw the tile, first find out the actual texture to use.
474 var norm = normalizeCoords({x: x, y: y, z: gMap.pos.z});
475 var tileKey = getTileKey(gMap.activeMap, norm);
476 if (!gMap.glTextures[tileKey]) {
477 tileKey = getTileKey("loading", {x: 0, y: 0, z: 0});
479 gMap.drawTileGL(xoff, yoff, tileKey);
482 gMap.glDrawRequested = false;
485 resizeAndDraw: function() {
486 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
487 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
488 if (gGLMapCanvas && gTrackCanvas) {
489 gGLMapCanvas.width = viewportWidth;
490 gGLMapCanvas.height = viewportHeight;
491 gTrackCanvas.width = viewportWidth;
492 gTrackCanvas.height = viewportHeight;
494 // Size viewport to canvas size.
495 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
497 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT);
498 // Make sure the vertex shader get the right resolution.
499 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
500 // Prepare recalculation of textures to keep for one zoom level.
501 gMap.glTexturesPerZoomLevel = 0;
508 drawTileGL: function(aLeft, aRight, aTileKey) {
509 gMap.gl.activeTexture(gMap.gl.TEXTURE0);
510 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
511 // Set uImage to refer to TEXTURE0
512 gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0);
514 var i_width = gMap.tileSize;
515 var y_start = aRight;
516 var i_height = gMap.tileSize;
517 var textureCoordinates = [
519 x_start + i_width, y_start,
520 x_start, y_start + i_height,
521 x_start, y_start + i_height,
522 x_start + i_width, y_start,
523 x_start + i_width, y_start + i_height,
525 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW);
527 // There are 6 indices in textureCoordinates.
528 gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
531 loadImageToTexture: function(aImage, aTileKey) {
532 // Create and bind texture.
533 gMap.glTextures[aTileKey] = gMap.gl.createTexture();
534 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
535 // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two).
536 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST);
537 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST);
538 // Upload the image into the texture.
539 gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage);
542 cleanTextures: function() {
543 // Get rid of unneeded textures to save memory.
544 // TODO: Be less aggressive, maybe keep neighboring zoom levels (but x/y coords there are zoom-specific).
545 if (!gMap.glTexturesPerZoomLevel) {
546 // Calculate how many textures we need to keep for one zoom level.
547 // ceil(width/size) gives us the minimum, keep one on either side as well.
548 gMap.glTexturesPerZoomLevel =
549 Math.ceil(gMap.gl.drawingBufferWidth / gMap.tileSize + 2) *
550 Math.ceil(gMap.gl.drawingBufferHeight / gMap.tileSize + 2);
551 console.log("Keeping " + gMap.glTexturesPerZoomLevel + " textures per level");
553 if (Object.keys(gMap.glTextures).length > gMap.glTexturesPerZoomLevel) {
554 console.log("Cleaning textures... (have " + Object.keys(gMap.glTextures).length + " atm)");
556 // Find coordinate ranges for tiles to keep.
557 var tMin = normalizeCoords({x: Math.floor((gMap.pos.x - gMap.baseDim.wid / 2) / gMap.baseDim.tsize) - 1,
558 y: Math.floor((gMap.pos.y - gMap.baseDim.ht / 2) / gMap.baseDim.tsize) - 1,
560 var tMax = normalizeCoords({x: Math.ceil((gMap.pos.x + gMap.baseDim.wid / 2) / gMap.baseDim.tsize) + 1,
561 y: Math.ceil((gMap.pos.y + gMap.baseDim.ht / 2) / gMap.baseDim.tsize) + 1,
563 console.log("In range: " + tMin.x + "," + tMin.y + "," + tMin.z + " - " + tMax.x + "," + tMax.y + "," + tMax.z);
564 for (var tileKey in gMap.glTextures) {
565 var keyMatches = tileKey.match(/([^:]+)::(\d+),(\d+),(\d+)/);
566 if (keyMatches && keyMatches[1] != "loading") {
568 style: keyMatches[1],
574 if (txData.style != gMap.activeMap) { delTx = true; console.log("Different map style: " + txData.style); }
575 if (!delTx && (txData.z < tMin.z || txData.z > tMax.z)) { delTx = true; console.log("Out-of-range zoom: " + txData.z); }
576 if (tMin.x < tMax.x) {
577 if (!delTx && (txData.x < tMin.x || txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
580 // We are crossing over the 0 coordinate!
581 if (!delTx && (txData.x < tMin.x && txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
583 if (tMin.y < tMax.y) {
584 if (!delTx && (txData.y < tMin.y || txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
587 // We are crossing over the 0 coordinate!
588 if (!delTx && (txData.y < tMin.y && txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
591 // Delete texture from GL and from the array we are holding.
592 gMap.gl.deleteTexture(gMap.glTextures[tileKey]);
593 delete gMap.glTextures[tileKey];
597 console.log("Cleaning complete, " + Object.keys(gMap.glTextures).length + " textures left");
601 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
602 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
605 if (gMap.pos.z < gMap.maxZoom) {
611 zoomOut: function() {
612 if (gMap.pos.z > 0) {
618 zoomTo: function(aTargetLevel) {
619 aTargetLevel = parseInt(aTargetLevel);
620 if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) {
621 gMap.pos.z = aTargetLevel;
626 setActiveMap: function(aStyle) {
627 gMap.activeMap = aStyle;
628 gPrefs.set("active_map_style", gMap.activeMap);
629 document.getElementById("copyright").innerHTML =
630 gMapStyles[gMap.activeMap].copyright;
631 if (!gWaitCounter) { // Only do this when prefs are loaded already.
637 handleContextLost: function(event) {
638 event.preventDefault();
639 // GL context is gone, let's reset everything that depends on it.
640 clearInterval(gMap.glTxCleanIntervalID);
641 gMap.glTextures = {};
644 handleContextRestored: function(event) {
645 // When GL context is back, init GL again and draw.
653 curPosMapCache: undefined,
654 lastDrawnPoint: null,
655 lastRequestedIndex: null, // may not have been actually drawn...
656 drawRequested: false,
657 restartDrawing: true,
659 maxDrawTime: 10, // max time allowed for drawing a section, in ms - 10 means we can do 100 fps smoothly
660 trackWidth: 2, // pixels
661 trackColor: "#FF0000",
662 curLocSize: 6, // pixels
663 curLocColor: "#A00000",
665 drawTrack: function(needRestart = true) {
666 // TODO: figure out if we can support reverse drawing while initially loading the track.
667 // Only draw if we're actually visible.
668 // Also, avoid running this multiple times when it could not complete yet.
669 if (needRestart) { gTrackLayer.restartDrawing = true; }
670 if (gTrackLayer.context && document.hidden != true && !gTrackLayer.drawRequested) {
671 gTrackLayer.drawRequested = true;
672 window.requestAnimationFrame(gTrackLayer.drawTrackSection);
676 drawTrackSection: function(aTimestamp) {
677 var start = performance.now();
678 if (gTrackLayer.restartDrawing) {
679 gTrackLayer.lastRequestedIndex = 0;
680 gTrackLayer.lastDrawnPoint = null;
681 gTrackLayer.restartDrawing = false;
682 gTrackLayer.curPosMapCache = undefined;
683 gTrackLayer.context.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
685 if (gTrack.length && (performance.now() < start + gTrackLayer.maxDrawTime)) {
686 for (; gTrackLayer.lastRequestedIndex < gTrack.length; gTrackLayer.lastRequestedIndex++) {
687 gTrackLayer.drawTrackPoint(gTrackLayer.lastRequestedIndex);
688 if (performance.now() >= start + gTrackLayer.maxDrawTime) {
689 // Break out of the loop if we are over the max allowed time, we'll continue in the next rAF (see below).
690 gTrackLayer.drawTrackPoint(null);
695 // If we still have work to do and we're still visible, continue drawing.
696 if ((gTrackLayer.lastRequestedIndex + 1 < gTrack.length) && gTrackLayer.context && (document.hidden != true)) {
697 window.requestAnimationFrame(gTrackLayer.drawTrackSection);
699 gTrackLayer.drawRequested = false;
702 drawTrackPoint: function(aIndex) {
703 gTrackLayer.running = true;
704 if (!aIndex && aIndex !== 0) {
705 // We can be called this way to make sure we draw an actual line up to where we are right now.
706 if (gTrackLayer.lastDrawnPoint && gTrackLayer.lastDrawnPoint.optimized) {
707 gTrackLayer.context.stroke();
708 gTrackLayer.lastDrawnPoint.optimized = false;
712 var trackpoint = {"worldpos": gps2xy(gTrack[aIndex].coords.latitude, gTrack[aIndex].coords.longitude)};
713 var isLastPoint = (aIndex + 1 >= gTrack.length || gTrack[aIndex+1].beginSegment);
714 var update_drawnpoint = true;
715 // lastPoint is for optimizing (not actually executing the draw until the last)
716 trackpoint.segmentEnd = (isLastPoint === true);
717 trackpoint.optimized = (isLastPoint === false);
718 trackpoint.mappos = {x: Math.round((trackpoint.worldpos.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
719 y: Math.round((trackpoint.worldpos.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
720 trackpoint.skip_drawing = false;
721 if (gTrackLayer.lastDrawnPoint) {
722 // Lines completely outside the current display should not be drawn.
723 if ((trackpoint.mappos.x < 0 && gTrackLayer.lastDrawnPoint.mappos.x < 0) ||
724 (trackpoint.mappos.x > gMap.width && gTrackLayer.lastDrawnPoint.mappos.x > gMap.width) ||
725 (trackpoint.mappos.y < 0 && gTrackLayer.lastDrawnPoint.mappos.y < 0) ||
726 (trackpoint.mappos.y > gMap.height && gTrackLayer.lastDrawnPoint.mappos.y > gMap.height)) {
727 trackpoint.skip_drawing = true;
730 if (!gTrackLayer.lastDrawnPoint || !gTrackLayer.lastDrawnPoint.optimized) {
731 gTrackLayer.context.strokeStyle = gTrackLayer.trackColor;
732 gTrackLayer.context.fillStyle = gTrackLayer.context.strokeStyle;
733 gTrackLayer.context.lineWidth = gTrackLayer.trackWidth;
734 gTrackLayer.context.lineCap = "round";
735 gTrackLayer.context.lineJoin = "round";
737 // This breaks optimiziation, so make sure to reset optimization.
738 if (trackpoint.skip_drawing || !gTrackLayer.lastDrawnPoint) {
739 trackpoint.optimized = false;
740 // Close path if one was open.
741 if (gTrackLayer.lastDrawnPoint && gTrackLayer.lastDrawnPoint.optimized) {
742 gTrackLayer.context.stroke();
745 if (!trackpoint.skip_drawing) {
746 if (gTrackLayer.lastDrawnPoint && gTrackLayer.lastDrawnPoint.skip_drawing && !gTrackLayer.lastDrawnPoint.segmentEnd) {
747 // If the last point was skipped but the current one isn't, draw a segment start
748 // for the off-screen previous one as well as a connection line.
749 gTrackLayer.context.beginPath();
750 gTrackLayer.context.arc(gTrackLayer.lastDrawnPoint.mappos.x, gTrackLayer.lastDrawnPoint.mappos.y,
751 gTrackLayer.context.lineWidth, 0, Math.PI * 2, false);
752 gTrackLayer.context.fill();
753 gTrackLayer.context.lineTo(trackpoint.mappos.x, trackpoint.mappos.y);
755 else if (!gTrackLayer.lastDrawnPoint || !gTrackLayer.lastDrawnPoint.optimized) {
756 // Start drawing a segment with the current point.
757 gTrackLayer.context.beginPath();
758 gTrackLayer.context.arc(trackpoint.mappos.x, trackpoint.mappos.y,
759 gTrackLayer.context.lineWidth, 0, Math.PI * 2, false);
760 gTrackLayer.context.fill();
762 else if (!trackpoint.segmentEnd && gTrackLayer.lastDrawnPoint &&
763 (Math.abs(gTrackLayer.lastDrawnPoint.mappos.x - trackpoint.mappos.x) <= 1) &&
764 (Math.abs(gTrackLayer.lastDrawnPoint.mappos.y - trackpoint.mappos.y) <= 1)) {
765 // We would draw the same or almost the same point, don't do any actual drawing.
766 update_drawnpoint = false;
769 // Continue drawing segment, close if needed.
770 gTrackLayer.context.lineTo(trackpoint.mappos.x, trackpoint.mappos.y);
771 if (!trackpoint.optimized)
772 gTrackLayer.context.stroke();
775 if (update_drawnpoint) {
776 gTrackLayer.lastDrawnPoint = trackpoint;
780 drawCurrentLocation: function(trackPoint) {
781 // Only run this when visible and we are not drawing a track right now.
782 if (gTrackLayer.context && document.hidden != true && !gTrackLayer.drawRequested) {
783 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
784 var circleRadius = Math.round(gTrackLayer.curLocSize / 2);
785 var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
786 y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
788 gTrackLayer.undrawCurrentLocation();
790 // Cache overdrawn area.
791 gTrackLayer.curPosMapCache =
793 radius: circleRadius,
794 data: gTrackLayer.context.getImageData(mappos.x - circleRadius,
795 mappos.y - circleRadius,
796 circleRadius * 2, circleRadius * 2)};
798 gTrackLayer.context.strokeStyle = gTrackLayer.curLocColor;
799 gTrackLayer.context.fillStyle = gTrackLayer.context.strokeStyle;
800 gTrackLayer.context.beginPath();
801 gTrackLayer.context.arc(mappos.x, mappos.y,
802 circleRadius, 0, Math.PI * 2, false);
803 gTrackLayer.context.fill();
807 undrawCurrentLocation: function() {
808 // Only run this when visible and we are not drawing a track right now.
809 if (gTrackLayer.context && document.hidden != true && !gTrackLayer.drawRequested) {
810 if (gTrackLayer.curPosMapCache) {
811 var oldpoint = gTrackLayer.curPosMapCache.point;
812 var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
813 y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
814 gTrackLayer.context.putImageData(gTrackLayer.curPosMapCache.data,
815 oldmp.x - gTrackLayer.curPosMapCache.radius,
816 oldmp.y - gTrackLayer.curPosMapCache.radius);
817 gTrackLayer.curPosMapCache = undefined;
823 function gps2xy(aLatitude, aLongitude) {
824 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
825 var convLat = aLatitude * Math.PI / 180;
826 var rawY = (1 - Math.log(Math.tan(convLat) +
827 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
828 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
829 return {x: Math.round(rawX),
830 y: Math.round(rawY)};
833 function xy2gps(aX, aY) {
834 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
835 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
836 return {latitude: 180 / Math.PI *
837 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
838 longitude: aX / maxZoomFactor * 360 - 180};
841 // A sane mod function that works for negative numbers.
844 return ((a % b) + b) % b;
847 function normalizeCoords(aCoords) {
848 var zoomFactor = Math.pow(2, aCoords.z);
849 return {x: mod(aCoords.x, zoomFactor),
850 y: mod(aCoords.y, zoomFactor),
854 function getTileKey(aStyle, aNormalizedCoords) {
855 return aStyle + "::" +
856 aNormalizedCoords.x + "," +
857 aNormalizedCoords.y + "," +
861 // Returns true if the tile is outside the current view.
862 function isOutsideWindow(t) {
863 var pos = decodeIndex(t);
865 var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z);
866 var wid = gMap.width * zoomFactor;
867 var ht = gMap.height * zoomFactor;
872 var sz = gMap.tileSize * zoomFactor;
873 if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 ||
874 pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2)
879 function encodeIndex(x, y, z) {
880 var norm = normalizeCoords({x: x, y: y, z: z});
881 return norm.x + "," + norm.y + "," + norm.z;
884 function decodeIndex(encodedIdx) {
885 var ind = encodedIdx.split(",", 3);
886 return {x: ind[0], y: ind[1], z: ind[2]};
889 function calcTrackDuration() {
890 // Get the duration of the track in s.
892 if (gTrack.length > 1) {
893 for (var i = 1; i < gTrack.length; i++) {
894 if (!gTrack[i].beginSegment) {
895 tDuration += (gTrack[i].time - gTrack[i-1].time);
899 return Math.round(tDuration / 1000); // The timestamps are in ms but we return seconds.
902 function calcTrackLength() {
903 // Get the length of the track in km.
905 if (gTrack.length > 1) {
906 for (var i = 1; i < gTrack.length; i++) {
907 if (!gTrack[i].beginSegment) {
908 tLength += getPointDistance(gTrack[i-1].coords, gTrack[i].coords);
915 function getPointDistance(aGPSPoint1, aGPSPoint2) {
916 // Get the distance in km between the two given GPS points.
917 // See http://stackoverflow.com/questions/365826/calculate-distance-between-2-gps-coordinates
918 // Earth is almost exactly a sphere and we calculate small distances on the surface, so we can do spherical great-circle math.
919 // Also see http://en.wikipedia.org/wiki/Great-circle_distance
921 var dLat = deg2rad(aGPSPoint2.latitude - aGPSPoint1.latitude);
922 var dLon = deg2rad(aGPSPoint2.longitude - aGPSPoint1.longitude);
923 var lat1 = deg2rad(aGPSPoint1.latitude);
924 var lat2 = deg2rad(aGPSPoint2.latitude);
926 var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
927 Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
928 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
932 function deg2rad(aDegreeValue) {
933 // Convert an angle in degrees to radiants.
934 return aDegreeValue * (Math.PI / 180);
938 handleEvent: function(aEvent) {
939 var touchEvent = aEvent.type.indexOf('touch') != -1;
942 aEvent.stopPropagation();
945 // Bail out if the event is happening on an input.
946 if (aEvent.target.tagName.toLowerCase() == "input")
949 // Bail out on unwanted map moves, but not zoom or keyboard events.
950 if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
951 // Bail out if this is neither a touch nor left-click.
952 if (!touchEvent && aEvent.button != 0)
955 // Bail out if the started touch can't be found.
956 if (touchEvent && gDragging &&
957 !aEvent.targetTouches.item(0))
961 var coordObj = touchEvent ?
962 aEvent.targetTouches.item(0) :
965 switch (aEvent.type) {
969 if (aEvent.targetTouches.length == 2) {
970 gPinchStartWidth = Math.sqrt(
971 Math.pow(aEvent.targetTouches.item(1).clientX -
972 aEvent.targetTouches.item(0).clientX, 2) +
973 Math.pow(aEvent.targetTouches.item(1).clientY -
974 aEvent.targetTouches.item(0).clientY, 2)
977 coordObj = aEvent.targetTouches.item(0);
979 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
980 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
982 if (touchEvent || aEvent.button === 0) {
988 gLastMoveAction = performance.now();
992 if (touchEvent && aEvent.targetTouches.length == 2) {
993 curPinchStartWidth = Math.sqrt(
994 Math.pow(aEvent.targetTouches.item(1).clientX -
995 aEvent.targetTouches.item(0).clientX, 2) +
996 Math.pow(aEvent.targetTouches.item(1).clientY -
997 aEvent.targetTouches.item(0).clientY, 2)
999 if (!gPinchStartWidth)
1000 gPinchStartWidth = curPinchStartWidth;
1002 if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
1003 gPinchStartWidth / curPinchStartWidth < 0.6) {
1004 var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
1005 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
1006 // Calculate new center of the map - preserve middle of pinch.
1007 // This means that pixel distance between old center and middle
1008 // must equal pixel distance of new center and middle.
1009 var x = (aEvent.targetTouches.item(1).clientX +
1010 aEvent.targetTouches.item(0).clientX) / 2 -
1011 gGLMapCanvas.offsetLeft;
1012 var y = (aEvent.targetTouches.item(1).clientY +
1013 aEvent.targetTouches.item(0).clientY) / 2 -
1014 gGLMapCanvas.offsetTop;
1016 // Zoom factor after this action.
1017 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
1018 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
1019 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
1021 if (gPinchStartWidth < curPinchStartWidth)
1026 // Reset pinch start width and start another pinch gesture.
1027 gPinchStartWidth = null;
1030 // If we are in a pinch, do not drag.
1033 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
1034 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
1035 if (gDragging === true) {
1036 var dX = x - gLastMouseX;
1037 var dY = y - gLastMouseY;
1038 gMap.pos.x -= dX * gMap.zoomFactor;
1039 gMap.pos.y -= dY * gMap.zoomFactor;
1045 gLastMoveAction = performance.now();
1049 gPinchStartWidth = null;
1056 //gDragging = false;
1059 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
1060 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
1062 // Only accept (non-null) deltaY values
1066 // Debug output: "coordinates" of the point the mouse was over.
1068 var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor,
1069 y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor};
1070 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
1071 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
1072 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
1073 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
1074 pt2Coord.x + "/" + pt2Coord.y);
1077 var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1);
1078 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
1079 // Calculate new center of the map - same point stays under the mouse.
1080 // This means that the pixel distance between the old center and point
1081 // must equal the pixel distance of the new center and that point.
1082 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
1083 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
1085 // Zoom factor after this action.
1086 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
1087 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
1088 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
1090 if (aEvent.deltaY < 0)
1097 // Allow keyboard control to move and zoom the map.
1098 // Should use aEvent.key instead of aEvent.which but needs bug 680830.
1099 // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
1102 switch (aEvent.which) {
1104 dX = -gMap.tileSize / 2;
1107 dX = gMap.tileSize / 2;
1110 dY = gMap.tileSize / 2;
1113 dY = -gMap.tileSize / 2;
1116 case 107: // + (numpad)
1117 case 171: // + (normal key)
1121 case 109: // - (numpad)
1122 case 173: // - (normal key)
1134 gMap.zoomTo(aEvent.which - 38);
1139 case 96: // 0 (numpad)
1140 case 97: // 1 (numpad)
1141 case 98: // 2 (numpad)
1142 case 99: // 3 (numpad)
1143 case 100: // 4 (numpad)
1144 case 101: // 5 (numpad)
1145 case 102: // 6 (numpad)
1146 case 103: // 7 (numpad)
1147 case 104: // 8 (numpad)
1148 gMap.zoomTo(aEvent.which - 86);
1150 case 105: // 9 (numpad)
1153 default: // not supported
1154 console.log("key not supported: " + aEvent.which);
1160 gMap.pos.x -= dX * gMap.zoomFactor;
1161 gMap.pos.y -= dY * gMap.zoomFactor;
1163 gLastMoveAction = performance.now();
1170 function visibilityEvHandler() {
1171 // Immediately draw if we just got visible.
1172 if (document.hidden != true) {
1175 // No need to handle the event where we become invisible as we care only draw
1176 // when we are visible anyhow.
1181 lastPos: {x: undefined, y: undefined},
1182 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
1183 this.tracking = true;
1184 var watchCall = function() {
1185 // calc new position in lat/lon degrees
1186 // 90° on Earth surface are ~10,000 km at the equator,
1187 // so try moving at most 10m at a time
1188 if (geofake.lastPos.x)
1189 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
1191 geofake.lastPos.x = 48.208174
1192 if (geofake.lastPos.y)
1193 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
1195 geofake.lastPos.y = 16.373819
1196 aSuccessCallback({timestamp: Date.now(),
1197 coords: {latitude: geofake.lastPos.x,
1198 longitude: geofake.lastPos.y,
1200 if (geofake.tracking)
1201 setTimeout(watchCall, 1000);
1203 setTimeout(watchCall, 1000);
1206 clearWatch: function(aID) {
1207 this.tracking = false;
1211 function setCentering(aCheckbox) {
1212 if (gMapPrefsLoaded && mainDB)
1213 gPrefs.set("center_map", aCheckbox.checked);
1214 gCenterPosition = aCheckbox.checked;
1217 function setTracking(aCheckbox) {
1218 if (gMapPrefsLoaded && mainDB)
1219 gPrefs.set("tracking_enabled", aCheckbox.checked);
1220 if (aCheckbox.checked)
1226 function startTracking() {
1228 gActionLabel.textContent = "Establishing Position";
1229 gAction.style.display = "block";
1230 if (navigator.requestWakeLock) {
1231 gGPSWakeLock = navigator.requestWakeLock("gps");
1233 gGeoWatchID = gGeolocation.watchPosition(
1234 function(position) {
1235 if (gActionLabel.textContent) {
1236 gActionLabel.textContent = "";
1237 gAction.style.display = "none";
1239 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
1240 var tPoint = {time: position.timestamp,
1241 coords: {latitude: position.coords.latitude,
1242 longitude: position.coords.longitude,
1243 altitude: position.coords.altitude,
1244 accuracy: position.coords.accuracy,
1245 altitudeAccuracy: position.coords.altitudeAccuracy,
1246 heading: position.coords.heading,
1247 speed: position.coords.speed},
1248 beginSegment: !gLastTrackPoint};
1249 // Only add point to track is accuracy is good enough.
1250 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
1251 gLastTrackPoint = tPoint;
1252 gTrack.push(tPoint);
1253 try { gTrackStore.push(tPoint); } catch(e) {}
1254 var redrawn = false;
1255 if (gCenterPosition && (!gLastMoveAction || performance.now() > gLastMoveAction + gCenterDelayAfterMove)) {
1256 var posCoord = gps2xy(position.coords.latitude,
1257 position.coords.longitude);
1258 if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 ||
1259 Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) {
1260 gMap.pos.x = posCoord.x;
1261 gMap.pos.y = posCoord.y;
1262 gMap.draw(); // This draws the current point as well.
1267 gTrackLayer.undrawCurrentLocation();
1268 gTrackLayer.drawTrackPoint(gTrack.length-1);
1270 gTrackLayer.drawCurrentLocation(tPoint);
1273 // Ignore erros for the moment, but this is good for debugging.
1274 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
1276 console.log(error.message);
1278 {enableHighAccuracy: true}
1283 function endTracking() {
1284 if (gActionLabel.textContent) {
1285 gActionLabel.textContent = "";
1286 gAction.style.display = "none";
1288 if (navigator.requestWakeLock && gGPSWakeLock) {
1289 console.log("releasing WakeLock");
1290 gGPSWakeLock.unlock();
1293 gGeolocation.clearWatch(gGeoWatchID);
1297 function clearTrack() {
1299 gTrackStore.clear();
1300 gTrackLayer.drawTrack();
1303 function loadTrackFromBackend(aTrackId, aFeedbackElement, aSuccessCallback) {
1304 if (aFeedbackElement) {
1305 aFeedbackElement.textContent = "Loading...";
1306 // If someone loads without pointing to UI (e.g. for debugging), we just overwrite whatever's loaded.
1307 if (calcTrackLength() > 1) {
1308 aFeedbackElement.textContent = "Track >1km loaded, please save/clear.";
1309 aFeedbackElement.classList.add("error");
1313 fetchBackend("track_json?id=" + encodeURIComponent(aTrackId), "GET", null,
1314 function(aResult, aStatusCode) {
1315 if (aStatusCode >= 400) {
1316 console.log("loading track failed: " + aStatusCode + ", result: " + aResult.message);
1317 if (aFeedbackElement) {
1318 aFeedbackElement.textContent = "Error: " + aResult;
1319 aFeedbackElement.classList.add("error");
1324 if (aSuccessCallback) {
1328 else { // If no result is returned, we assume a general error.
1329 console.log("Error getting track with ID " + aTrackId + " from backend.");
1330 if (aFeedbackElement) {
1331 aFeedbackElement.textContent = "Error fetching track from backend.";
1332 aFeedbackElement.classList.add("error");
1339 function loadTrack(aTrack) {
1340 console.log("Loading track with " + aTrack.length + " points.");
1342 gTrackStore.clear(function(aSuccess, aEvent) {
1343 for (var i = 0; i < gTrack.length; i++) {
1344 try { gTrackStore.push(gTrack[i]); } catch(e) {}
1347 gTrackLayer.drawTrack(); // Draws from gTrack, so not problem that gTrackStore is filled async.
1350 var gTileService = {
1351 objStore: "tilecache",
1353 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
1355 get: function(aStyle, aCoords, aCallback) {
1356 var norm = normalizeCoords(aCoords);
1357 var dbkey = getTileKey(aStyle, norm);
1358 this.getDBCache(dbkey, function(aResult, aEvent) {
1360 // We did get a cached object.
1361 aCallback(aResult.image, aStyle, aCoords, dbkey);
1362 // Look at the timestamp and return if it's not too old.
1363 if (aResult.timestamp + gTileService.ageLimit > Date.now())
1365 // Reload cached tile otherwise.
1366 var oldDate = new Date(aResult.timestamp);
1367 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
1369 // Retrieve image from the web and store it in the cache.
1370 var XHR = new XMLHttpRequest();
1372 gMapStyles[aStyle].url
1373 .replace("{x}", norm.x)
1374 .replace("{y}", norm.y)
1375 .replace("{z}", norm.z)
1376 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 3)))
1377 .replace("[a-d]", String.fromCharCode(97 + Math.floor(Math.random() * 4)))
1378 .replace("[1-4]", 1 + Math.floor(Math.random() * 4)),
1380 XHR.responseType = "blob";
1381 XHR.addEventListener("load", function () {
1382 if (XHR.status === 200) {
1383 var blob = XHR.response;
1384 aCallback(blob, aStyle, aCoords, dbkey);
1385 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
1392 getDBCache: function(aKey, aCallback) {
1395 var transaction = mainDB.transaction([this.objStore]);
1396 var request = transaction.objectStore(this.objStore).get(aKey);
1397 request.onsuccess = function(event) {
1398 aCallback(request.result, event);
1400 request.onerror = function(event) {
1401 // Errors can be handled here.
1402 aCallback(undefined, event);
1406 setDBCache: function(aKey, aValue, aCallback) {
1409 var success = false;
1410 var transaction = mainDB.transaction([this.objStore], "readwrite");
1411 var objStore = transaction.objectStore(this.objStore);
1412 var request = objStore.put(aValue, aKey);
1413 request.onsuccess = function(event) {
1416 aCallback(success, event);
1418 request.onerror = function(event) {
1419 // Errors can be handled here.
1421 aCallback(success, event);
1425 unsetDBCache: function(aKey, aCallback) {
1428 var success = false;
1429 var transaction = mainDB.transaction([this.objStore], "readwrite");
1430 var request = transaction.objectStore(this.objStore).delete(aKey);
1431 request.onsuccess = function(event) {
1434 aCallback(success, event);
1436 request.onerror = function(event) {
1437 // Errors can be handled here.
1439 aCallback(success, event);
1443 clearDB: function(aCallback) {
1446 var success = false;
1447 var transaction = mainDB.transaction([this.objStore], "readwrite");
1448 var request = transaction.objectStore(this.objStore).clear();
1449 request.onsuccess = function(event) {
1451 console.log("Cache cleared.");
1453 aCallback(success, event);
1455 request.onerror = function(event) {
1456 // Errors can be handled here.
1457 console.log("Error clearing cache!");
1459 aCallback(success, event);