1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3 * You can obtain one at http://mozilla.org/MPL/2.0/. */
5 var gGLMapCanvas, gTrackCanvas, gTrackContext, gGeolocation;
8 var gMinTrackAccuracy = 1000; // meters
9 var gTrackWidth = 2; // pixels
10 var gTrackColor = "#FF0000";
11 var gCurLocSize = 6; // pixels
12 var gCurLocColor = "#A00000";
15 // OSM tile usage policy: http://wiki.openstreetmap.org/wiki/Tile_usage_policy
16 // Find some more OSM ones at http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers
17 // and http://wiki.openstreetmap.org/wiki/Tiles or http://wiki.openstreetmap.org/wiki/TMS
19 {name: "OpenStreetMap (Mapnik)",
20 url: "https://[a-c].tile.openstreetmap.org/{z}/{x}/{y}.png",
21 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
23 {name: "Cycle Map (OSM)",
24 url: "https://[a-c].tile.thunderforest.com/cycle/{z}/{x}/{y}.png", // "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
25 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
27 {name: "Transport Map (OSM)",
28 url: "https://[a-c].tile.thunderforest.com/transport/{z}/{x}/{y}.png", // "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png",
29 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
31 {name: "OSM German Style",
32 url: "https://tilecache[1-4].kairo.at/osmde/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
33 //url: "http://[a-d].tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png", // https is not supported at all
34 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
36 {name: "ÖPNV-Karte (OSM)",
37 url: "https://tilecache[1-4].kairo.at/oepnv/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
38 //url: "http://tileserver.memomaps.de/tilegen/{z}/{x}/{y}.png", // memomaps.de does not support CORS or https at this time :(
39 copyright: 'Map data © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://memomaps.de">MeMoMaps</a> under <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>.'},
41 {name: "MapQuest OSM",
42 url: "https://tilecache[1-4].kairo.at/mapqosm/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
43 //url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png", // https has wrong cert, akamai instead of mqcdn
44 copyright: 'Map data © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> and contributors (<a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>), tiles courtesy of <a href="http://www.mapquest.com/">MapQuest</a>.'},
46 {name: "MapQuest Open Aerial",
47 url: "https://tilecache[1-4].kairo.at/mapqsat/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
48 //url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg",
49 copyright: 'Tiles Courtesy of <a href="http://www.mapquest.com/">MapQuest</a>, portions Courtesy NASA/JPL-Caltech and U.S. Depart. of Agriculture, Farm Service Agency.'},
51 {name: "OSM HOT style",
52 url: "https://tilecache[1-4].kairo.at/osmhot/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
53 //url: "http://[a-c].tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", // https has CAcert which doesn't work in browsers
54 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
56 {name: "Hike and Bike (OSM)",
57 url: "https://tilecache[1-4].kairo.at/hikebike/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
58 //url: "http://toolserver.org/tiles/hikebike/{z}/{x}/{y}.png", // toolserver.org does not support CORS at this time :(
59 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
61 {name: "Outdoors (OSM)",
62 url: "https://[a-c].tile.thunderforest.com/outdoors/{z}/{x}/{y}.png", // url: "http://[a-c].tile.opencyclemap.org/outdoors/{z}/{x}/{y}.png",
63 copyright: 'Map data © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> and contributors (<a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>), tiles by <a href="http://www.thunderforest.com/">Thunderforest</a>.'},
65 {name: "Stamen Toner (B+W)",
66 url: "https://tilecache[1-4].kairo.at/toner/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
67 //url: "http://[a-c].tile.stamen.com/toner/{z}/{x}/{y}.jpg", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
68 copyright: 'Map data © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>.'},
70 {name: "Stamen Terrain (USA only)",
71 url: "https://tilecache[1-4].kairo.at/terrain/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
72 //url: "http://[a-c].tile.stamen.com/terrain/{z}/{x}/{y}.jpg", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
73 copyright: 'Map data © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>.'},
75 {name: "Stamen Watercolor (artistic)",
76 url: "https://tilecache[1-4].kairo.at/watercolor/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
77 //url: "http://[a-c].tile.stamen.com/watercolor/{z}/{x}/{y}.jpg", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
78 copyright: 'Map data © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>.'},
86 var gMapPrefsLoaded = false;
88 var gDragging = false;
89 var gDragTouchID, gPinchStartWidth;
91 var gGeoWatchID, gGPSWakeLock;
93 var gLastTrackPoint, gLastDrawnPoint;
95 var gCenterPosition = true;
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 gTrackContext = 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) {
245 if (redrawBase < 1000) {
246 redrawBase = tracklen;
251 // Last point received.
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.
291 get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; },
292 get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; },
294 getVertShaderSource: function() {
295 return 'attribute vec2 aVertexPosition;\n' +
296 'attribute vec2 aTextureCoord;\n\n' +
297 'uniform vec2 uResolution;\n\n' +
298 'varying highp vec2 vTextureCoord;\n\n' +
299 'void main(void) {\n' +
300 // convert the rectangle from pixels to -1.0 to +1.0 (clipspace) 0.0 to 1.0
301 ' vec2 clipSpace = aVertexPosition * 2.0 / uResolution - 1.0;\n' +
302 ' gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' +
303 ' vTextureCoord = aTextureCoord;\n' +
305 getFragShaderSource: function() {
306 return 'varying highp vec2 vTextureCoord;\n\n' +
307 'uniform sampler2D uImage;\n\n' +
308 'void main(void) {\n' +
309 ' gl_FragColor = texture2D(uImage, vTextureCoord);\n' +
313 // When called from the event listener, the "this" reference doesn't work, so use the object name.
314 console.log("Initializing WebGL...");
316 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
317 gMap.gl.clearColor(0.0, 0.0, 0.0, 0.5); // Set clear color to black, fully opaque.
318 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT|gMap.gl.DEPTH_BUFFER_BIT); // Clear the color.
320 // Create and initialize the shaders.
321 console.log("Create and compile shaders...");
322 var vertShader = gMap.gl.createShader(gMap.gl.VERTEX_SHADER);
323 var fragShader = gMap.gl.createShader(gMap.gl.FRAGMENT_SHADER);
324 gMap.gl.shaderSource(vertShader, gMap.getVertShaderSource());
325 // Compile the shader program.
326 gMap.gl.compileShader(vertShader);
327 // See if it compiled successfully.
328 if (!gMap.gl.getShaderParameter(vertShader, gMap.gl.COMPILE_STATUS)) {
329 console.log("An error occurred compiling the vertex shader: " + gMap.gl.getShaderInfoLog(vertShader));
332 gMap.gl.shaderSource(fragShader, gMap.getFragShaderSource());
333 // Compile the shader program.
334 gMap.gl.compileShader(fragShader);
335 // See if it compiled successfully.
336 if (!gMap.gl.getShaderParameter(fragShader, gMap.gl.COMPILE_STATUS)) {
337 console.log("An error occurred compiling the fragment shader: " + gMap.gl.getShaderInfoLog(fragShader));
341 console.log("Create and link shader program...");
342 gMap.glShaderProgram = gMap.gl.createProgram();
343 gMap.gl.attachShader(gMap.glShaderProgram, vertShader);
344 gMap.gl.attachShader(gMap.glShaderProgram, fragShader);
345 gMap.gl.linkProgram(gMap.glShaderProgram);
346 // If creating the shader program failed, alert
347 if (!gMap.gl.getProgramParameter(gMap.glShaderProgram, gMap.gl.LINK_STATUS)) {
348 alert("Unable to initialize the shader program.");
350 gMap.gl.useProgram(gMap.glShaderProgram);
351 // Get locations of the attributes.
352 gMap.glVertexPositionAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aVertexPosition");
353 gMap.glTextureCoordAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aTextureCoord");
354 gMap.glResolutionAttr = gMap.gl.getUniformLocation(gMap.glShaderProgram, "uResolution");
356 console.log("Set up vertex buffer...");
357 var tileVerticesBuffer = gMap.gl.createBuffer();
358 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, tileVerticesBuffer);
359 // The vertices are the coordinates of the corner points of the square.
368 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(vertices), gMap.gl.STATIC_DRAW);
369 gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr);
370 gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0);
372 gMap.loadImageToTexture(gLoadingTile, getTileKey("loading", {x: 0, y: 0, z: 0}));
374 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
376 // Create a buffer for the position of the rectangle corners.
377 console.log("Set up coord buffer...");
378 var mapVerticesTextureCoordBuffer = gMap.gl.createBuffer();
379 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer);
380 gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr);
381 gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0);
383 // Call texture cleaning every 30 seconds, for now (is 60 better?).
384 gMap.glTxCleanIntervalID = window.setInterval(gMap.cleanTextures, 30 * 1000);
388 // We may be called when context was lost and destroyed,
389 // only send event when we are in app startup
390 // (gAppInitDone is set to true right after we return this event).
391 var throwEv = new CustomEvent("mapinit-done");
392 gAction.dispatchEvent(throwEv);
401 assembleGL: function() {
402 if (!gMap.gl) { return; }
404 document.getElementById("zoomLevel").textContent = gMap.pos.z;
405 gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
406 gMap.baseDim.wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor;
407 gMap.baseDim.ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor;
408 gMap.baseDim.tsize = gMap.tileSize * gMap.zoomFactor;
410 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
411 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
412 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
413 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
415 if (gMapPrefsLoaded && mainDB)
416 gPrefs.set("position", gMap.pos);
418 // Go through all the tiles in the map, find out if to draw them and do so.
419 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
420 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
421 // Only go to loading step if we haven't loaded the texture.
422 var coords = {x: x, y: y, z: gMap.pos.z};
423 var tileKey = getTileKey(gMap.activeMap, normalizeCoords(coords));
424 if (!gMap.glTextures[tileKey]) {
425 // Initiate loading/drawing of the actual tile.
426 gTileService.get(gMap.activeMap, coords,
427 function(aImage, aStyle, aCoords, aTileKey) {
428 // Only actually load if this still applies for the current view.
429 if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) {
430 var URL = window.URL;
431 var imgURL = URL.createObjectURL(aImage);
432 var imgObj = new Image();
433 imgObj.onload = function() {
434 gMap.loadImageToTexture(imgObj, aTileKey);
435 if (document.hidden != true) { // Only draw if we're actually visible.
436 window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
438 URL.revokeObjectURL(imgURL);
446 if (document.hidden != true) { // Only draw if we're actually visible.
447 window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
452 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
453 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
454 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
455 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
457 // Go through all the tiles in the map, find out if to draw them and do so.
458 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
459 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
460 // Rounding the pixel offsets ensures we position the tiles precisely.
461 var xoff = Math.round((x * gMap.baseDim.tsize - xMin) / gMap.zoomFactor);
462 var yoff = Math.round((y * gMap.baseDim.tsize - yMin) / gMap.zoomFactor);
463 // Draw the tile, first find out the actual texture to use.
464 var norm = normalizeCoords({x: x, y: y, z: gMap.pos.z});
465 var tileKey = getTileKey(gMap.activeMap, norm);
466 if (!gMap.glTextures[tileKey]) {
467 tileKey = getTileKey("loading", {x: 0, y: 0, z: 0});
469 gMap.drawTileGL(xoff, yoff, tileKey);
474 resizeAndDraw: function() {
475 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
476 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
477 if (gGLMapCanvas && gTrackCanvas) {
478 gGLMapCanvas.width = viewportWidth;
479 gGLMapCanvas.height = viewportHeight;
480 gTrackCanvas.width = viewportWidth;
481 gTrackCanvas.height = viewportHeight;
483 // Size viewport to canvas size.
484 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
486 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT);
487 // Make sure the vertex shader get the right resolution.
488 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
489 // Prepare recalculation of textures to keep for one zoom level.
490 gMap.glTexturesPerZoomLevel = 0;
497 drawTileGL: function(aLeft, aRight, aTileKey) {
498 gMap.gl.activeTexture(gMap.gl.TEXTURE0);
499 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
500 // Set uImage to refer to TEXTURE0
501 gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0);
503 var i_width = gMap.tileSize;
504 var y_start = aRight;
505 var i_height = gMap.tileSize;
506 var textureCoordinates = [
508 x_start + i_width, y_start,
509 x_start, y_start + i_height,
510 x_start, y_start + i_height,
511 x_start + i_width, y_start,
512 x_start + i_width, y_start + i_height,
514 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW);
516 // There are 6 indices in textureCoordinates.
517 gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
520 loadImageToTexture: function(aImage, aTileKey) {
521 // Create and bind texture.
522 gMap.glTextures[aTileKey] = gMap.gl.createTexture();
523 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
524 // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two).
525 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST);
526 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST);
527 // Upload the image into the texture.
528 gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage);
531 cleanTextures: function() {
532 // Get rid of unneeded textures to save memory.
533 // TODO: Be less aggressive, maybe keep neighboring zoom levels (but x/y coords there are zoom-specific).
534 if (!gMap.glTexturesPerZoomLevel) {
535 // Calculate how many textures we need to keep for one zoom level.
536 // ceil(width/size) gives us the minimum, keep one on either side as well.
537 gMap.glTexturesPerZoomLevel =
538 Math.ceil(gMap.gl.drawingBufferWidth / gMap.tileSize + 2) *
539 Math.ceil(gMap.gl.drawingBufferHeight / gMap.tileSize + 2);
540 console.log("Keeping " + gMap.glTexturesPerZoomLevel + " textures per level");
542 if (Object.keys(gMap.glTextures).length > gMap.glTexturesPerZoomLevel) {
543 console.log("Cleaning textures... (have " + Object.keys(gMap.glTextures).length + " atm)");
545 // Find coordinate ranges for tiles to keep.
546 var tMin = normalizeCoords({x: Math.floor((gMap.pos.x - gMap.baseDim.wid / 2) / gMap.baseDim.tsize) - 1,
547 y: Math.floor((gMap.pos.y - gMap.baseDim.ht / 2) / gMap.baseDim.tsize) - 1,
549 var tMax = normalizeCoords({x: Math.ceil((gMap.pos.x + gMap.baseDim.wid / 2) / gMap.baseDim.tsize) + 1,
550 y: Math.ceil((gMap.pos.y + gMap.baseDim.ht / 2) / gMap.baseDim.tsize) + 1,
552 console.log("In range: " + tMin.x + "," + tMin.y + "," + tMin.z + " - " + tMax.x + "," + tMax.y + "," + tMax.z);
553 for (var tileKey in gMap.glTextures) {
554 var keyMatches = tileKey.match(/([^:]+)::(\d+),(\d+),(\d+)/);
555 if (keyMatches && keyMatches[1] != "loading") {
557 style: keyMatches[1],
563 if (txData.style != gMap.activeMap) { delTx = true; console.log("Different map style: " + txData.style); }
564 if (!delTx && (txData.z < tMin.z || txData.z > tMax.z)) { delTx = true; console.log("Out-of-range zoom: " + txData.z); }
565 if (tMin.x < tMax.x) {
566 if (!delTx && (txData.x < tMin.x || txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
569 // We are crossing over the 0 coordinate!
570 if (!delTx && (txData.x < tMin.x && txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
572 if (tMin.y < tMax.y) {
573 if (!delTx && (txData.y < tMin.y || txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
576 // We are crossing over the 0 coordinate!
577 if (!delTx && (txData.y < tMin.y && txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
580 // Delete texture from GL and from the array we are holding.
581 gMap.gl.deleteTexture(gMap.glTextures[tileKey]);
582 delete gMap.glTextures[tileKey];
586 console.log("Cleaning complete, " + Object.keys(gMap.glTextures).length + " textures left");
590 handleContextLost: function(event) {
591 event.preventDefault();
592 // GL context is gone, let's reset everything that depends on it.
593 clearInterval(gMap.glTxCleanIntervalID);
594 gMap.glTextures = {};
597 handleContextRestored: function(event) {
598 // When GL context is back, init GL again and draw.
604 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
605 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
608 if (gMap.pos.z < gMap.maxZoom) {
615 if (gMap.pos.z > 0) {
621 function zoomTo(aTargetLevel) {
622 aTargetLevel = parseInt(aTargetLevel);
623 if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) {
624 gMap.pos.z = aTargetLevel;
629 function gps2xy(aLatitude, aLongitude) {
630 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
631 var convLat = aLatitude * Math.PI / 180;
632 var rawY = (1 - Math.log(Math.tan(convLat) +
633 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
634 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
635 return {x: Math.round(rawX),
636 y: Math.round(rawY)};
639 function xy2gps(aX, aY) {
640 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
641 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
642 return {latitude: 180 / Math.PI *
643 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
644 longitude: aX / maxZoomFactor * 360 - 180};
647 function setMapStyle() {
648 var mapSel = document.getElementById("mapSelector");
649 if (mapSel.selectedIndex >= 0 && gMap.activeMap != mapSel.value) {
650 gMap.activeMap = mapSel.value;
651 gPrefs.set("active_map_style", gMap.activeMap);
652 document.getElementById("copyright").innerHTML =
653 gMapStyles[gMap.activeMap].copyright;
654 if (!gWaitCounter) { // Only do this when prefs are loaded already.
661 // A sane mod function that works for negative numbers.
664 return ((a % b) + b) % b;
667 function normalizeCoords(aCoords) {
668 var zoomFactor = Math.pow(2, aCoords.z);
669 return {x: mod(aCoords.x, zoomFactor),
670 y: mod(aCoords.y, zoomFactor),
674 function getTileKey(aStyle, aNormalizedCoords) {
675 return aStyle + "::" +
676 aNormalizedCoords.x + "," +
677 aNormalizedCoords.y + "," +
681 // Returns true if the tile is outside the current view.
682 function isOutsideWindow(t) {
683 var pos = decodeIndex(t);
685 var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z);
686 var wid = gMap.width * zoomFactor;
687 var ht = gMap.height * zoomFactor;
692 var sz = gMap.tileSize * zoomFactor;
693 if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 ||
694 pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2)
699 function encodeIndex(x, y, z) {
700 var norm = normalizeCoords({x: x, y: y, z: z});
701 return norm.x + "," + norm.y + "," + norm.z;
704 function decodeIndex(encodedIdx) {
705 var ind = encodedIdx.split(",", 3);
706 return {x: ind[0], y: ind[1], z: ind[2]};
709 function drawTrack() {
710 if (gDrawing) { return; }
712 if (gTrackContext && (document.hidden != true)) { // Only draw if we're actually visible.
713 gLastDrawnPoint = null;
714 gCurPosMapCache = undefined;
715 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
717 for (var i = 0; i < gTrack.length; i++) {
718 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
719 (i + 1 >= gTrack.length || gTrack[i+1].beginSegment));
726 function drawTrackPoint(aLatitude, aLongitude, aLastPoint) {
727 var trackpoint = {"worldpos": gps2xy(aLatitude, aLongitude)};
728 var update_drawnpoint = true;
729 // lastPoint is for optimizing (not actually executing the draw until the last)
730 trackpoint.segmentEnd = (aLastPoint === true);
731 trackpoint.optimized = (aLastPoint === false);
732 trackpoint.mappos = {x: Math.round((trackpoint.worldpos.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
733 y: Math.round((trackpoint.worldpos.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
734 trackpoint.skip_drawing = false;
735 if (gLastDrawnPoint) {
736 // Lines completely outside the current display should not be drawn.
737 if ((trackpoint.mappos.x < 0 && gLastDrawnPoint.mappos.x < 0) ||
738 (trackpoint.mappos.x > gMap.width && gLastDrawnPoint.mappos.x > gMap.width) ||
739 (trackpoint.mappos.y < 0 && gLastDrawnPoint.mappos.y < 0) ||
740 (trackpoint.mappos.y > gMap.height && gLastDrawnPoint.mappos.y > gMap.height)) {
741 trackpoint.skip_drawing = true;
744 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
745 gTrackContext.strokeStyle = gTrackColor;
746 gTrackContext.fillStyle = gTrackContext.strokeStyle;
747 gTrackContext.lineWidth = gTrackWidth;
748 gTrackContext.lineCap = "round";
749 gTrackContext.lineJoin = "round";
751 // This breaks optimiziation, so make sure to reset optimization.
752 if (trackpoint.skip_drawing || !gLastDrawnPoint) {
753 trackpoint.optimized = false;
754 // Close path if one was open.
755 if (gLastDrawnPoint && gLastDrawnPoint.optimized) {
756 gTrackContext.stroke();
759 if (!trackpoint.skip_drawing) {
760 if (gLastDrawnPoint && gLastDrawnPoint.skip_drawing && !gLastDrawnPoint.segmentEnd) {
761 // If the last point was skipped but the current one isn't, draw a segment start
762 // for the off-screen previous one as well as a connection line.
763 gTrackContext.beginPath();
764 gTrackContext.arc(gLastDrawnPoint.mappos.x, gLastDrawnPoint.mappos.y,
765 gTrackContext.lineWidth, 0, Math.PI * 2, false);
766 gTrackContext.fill();
767 gTrackContext.lineTo(trackpoint.mappos.x, trackpoint.mappos.y);
769 else if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
770 // Start drawing a segment with the current point.
771 gTrackContext.beginPath();
772 gTrackContext.arc(trackpoint.mappos.x, trackpoint.mappos.y,
773 gTrackContext.lineWidth, 0, Math.PI * 2, false);
774 gTrackContext.fill();
776 else if (!trackpoint.segmentEnd && gLastDrawnPoint &&
777 (Math.abs(gLastDrawnPoint.mappos.x - trackpoint.mappos.x) <= 1) &&
778 (Math.abs(gLastDrawnPoint.mappos.y - trackpoint.mappos.y) <= 1)) {
779 // We would draw the same or almost the same point, don't do any actual drawing.
780 update_drawnpoint = false;
783 // Continue drawing segment, close if needed.
784 gTrackContext.lineTo(trackpoint.mappos.x, trackpoint.mappos.y);
785 if (!trackpoint.optimized)
786 gTrackContext.stroke();
789 if (update_drawnpoint) {
790 gLastDrawnPoint = trackpoint;
794 function drawCurrentLocation(trackPoint) {
795 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
796 var circleRadius = Math.round(gCurLocSize / 2);
797 var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
798 y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
800 undrawCurrentLocation();
802 // Cache overdrawn area.
805 radius: circleRadius,
806 data: gTrackContext.getImageData(mappos.x - circleRadius,
807 mappos.y - circleRadius,
808 circleRadius * 2, circleRadius * 2)};
810 gTrackContext.strokeStyle = gCurLocColor;
811 gTrackContext.fillStyle = gTrackContext.strokeStyle;
812 gTrackContext.beginPath();
813 gTrackContext.arc(mappos.x, mappos.y,
814 circleRadius, 0, Math.PI * 2, false);
815 gTrackContext.fill();
818 function undrawCurrentLocation() {
819 if (gCurPosMapCache) {
820 var oldpoint = gCurPosMapCache.point;
821 var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
822 y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
823 gTrackContext.putImageData(gCurPosMapCache.data,
824 oldmp.x - gCurPosMapCache.radius,
825 oldmp.y - gCurPosMapCache.radius);
826 gCurPosMapCache = undefined;
830 function calcTrackDuration() {
831 // Get the duration of the track in s.
833 if (gTrack.length > 1) {
834 for (var i = 1; i < gTrack.length; i++) {
835 if (!gTrack[i].beginSegment) {
836 tDuration += (gTrack[i].time - gTrack[i-1].time);
840 return Math.round(tDuration / 1000); // The timestamps are in ms but we return seconds.
843 function calcTrackLength() {
844 // Get the length of the track in km.
846 if (gTrack.length > 1) {
847 for (var i = 1; i < gTrack.length; i++) {
848 if (!gTrack[i].beginSegment) {
849 tLength += getPointDistance(gTrack[i-1].coords, gTrack[i].coords);
856 function getPointDistance(aGPSPoint1, aGPSPoint2) {
857 // Get the distance in km between the two given GPS points.
858 // See http://stackoverflow.com/questions/365826/calculate-distance-between-2-gps-coordinates
859 // Earth is almost exactly a sphere and we calculate small distances on the surface, so we can do spherical great-circle math.
860 // Also see http://en.wikipedia.org/wiki/Great-circle_distance
862 var dLat = deg2rad(aGPSPoint2.latitude - aGPSPoint1.latitude);
863 var dLon = deg2rad(aGPSPoint2.longitude - aGPSPoint1.longitude);
864 var lat1 = deg2rad(aGPSPoint1.latitude);
865 var lat2 = deg2rad(aGPSPoint2.latitude);
867 var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
868 Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
869 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
873 function deg2rad(aDegreeValue) {
874 // Convert an angle in degrees to radiants.
875 return aDegreeValue * (Math.PI / 180);
879 handleEvent: function(aEvent) {
880 var touchEvent = aEvent.type.indexOf('touch') != -1;
883 aEvent.stopPropagation();
886 // Bail out if the event is happening on an input.
887 if (aEvent.target.tagName.toLowerCase() == "input")
890 // Bail out on unwanted map moves, but not zoom or keyboard events.
891 if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
892 // Bail out if this is neither a touch nor left-click.
893 if (!touchEvent && aEvent.button != 0)
896 // Bail out if the started touch can't be found.
897 if (touchEvent && gDragging &&
898 !aEvent.targetTouches.item(0))
902 var coordObj = touchEvent ?
903 aEvent.targetTouches.item(0) :
906 switch (aEvent.type) {
910 if (aEvent.targetTouches.length == 2) {
911 gPinchStartWidth = Math.sqrt(
912 Math.pow(aEvent.targetTouches.item(1).clientX -
913 aEvent.targetTouches.item(0).clientX, 2) +
914 Math.pow(aEvent.targetTouches.item(1).clientY -
915 aEvent.targetTouches.item(0).clientY, 2)
918 coordObj = aEvent.targetTouches.item(0);
920 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
921 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
923 if (touchEvent || aEvent.button === 0) {
932 if (touchEvent && aEvent.targetTouches.length == 2) {
933 curPinchStartWidth = Math.sqrt(
934 Math.pow(aEvent.targetTouches.item(1).clientX -
935 aEvent.targetTouches.item(0).clientX, 2) +
936 Math.pow(aEvent.targetTouches.item(1).clientY -
937 aEvent.targetTouches.item(0).clientY, 2)
939 if (!gPinchStartWidth)
940 gPinchStartWidth = curPinchStartWidth;
942 if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
943 gPinchStartWidth / curPinchStartWidth < 0.6) {
944 var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
945 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
946 // Calculate new center of the map - preserve middle of pinch.
947 // This means that pixel distance between old center and middle
948 // must equal pixel distance of new center and middle.
949 var x = (aEvent.targetTouches.item(1).clientX +
950 aEvent.targetTouches.item(0).clientX) / 2 -
951 gGLMapCanvas.offsetLeft;
952 var y = (aEvent.targetTouches.item(1).clientY +
953 aEvent.targetTouches.item(0).clientY) / 2 -
954 gGLMapCanvas.offsetTop;
956 // Zoom factor after this action.
957 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
958 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
959 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
961 if (gPinchStartWidth < curPinchStartWidth)
966 // Reset pinch start width and start another pinch gesture.
967 gPinchStartWidth = null;
970 // If we are in a pinch, do not drag.
973 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
974 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
975 if (gDragging === true) {
976 var dX = x - gLastMouseX;
977 var dY = y - gLastMouseY;
978 gMap.pos.x -= dX * gMap.zoomFactor;
979 gMap.pos.y -= dY * gMap.zoomFactor;
988 gPinchStartWidth = null;
998 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
999 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
1001 // Only accept (non-null) deltaY values
1005 // Debug output: "coordinates" of the point the mouse was over.
1007 var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor,
1008 y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor};
1009 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
1010 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
1011 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
1012 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
1013 pt2Coord.x + "/" + pt2Coord.y);
1016 var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1);
1017 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
1018 // Calculate new center of the map - same point stays under the mouse.
1019 // This means that the pixel distance between the old center and point
1020 // must equal the pixel distance of the new center and that point.
1021 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
1022 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
1024 // Zoom factor after this action.
1025 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
1026 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
1027 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
1029 if (aEvent.deltaY < 0)
1036 // Allow keyboard control to move and zoom the map.
1037 // Should use aEvent.key instead of aEvent.which but needs bug 680830.
1038 // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
1041 switch (aEvent.which) {
1043 dX = -gMap.tileSize / 2;
1046 dX = gMap.tileSize / 2;
1049 dY = gMap.tileSize / 2;
1052 dY = -gMap.tileSize / 2;
1055 case 107: // + (numpad)
1056 case 171: // + (normal key)
1060 case 109: // - (numpad)
1061 case 173: // - (normal key)
1073 zoomTo(aEvent.which - 38);
1078 case 96: // 0 (numpad)
1079 case 97: // 1 (numpad)
1080 case 98: // 2 (numpad)
1081 case 99: // 3 (numpad)
1082 case 100: // 4 (numpad)
1083 case 101: // 5 (numpad)
1084 case 102: // 6 (numpad)
1085 case 103: // 7 (numpad)
1086 case 104: // 8 (numpad)
1087 zoomTo(aEvent.which - 86);
1089 case 105: // 9 (numpad)
1092 default: // not supported
1093 console.log("key not supported: " + aEvent.which);
1099 gMap.pos.x -= dX * gMap.zoomFactor;
1100 gMap.pos.y -= dY * gMap.zoomFactor;
1108 function visibilityEvHandler() {
1109 // Immediately draw if we just got visible.
1110 if (document.hidden != true) {
1113 // No need to handle the event where we become invisible as we care only draw
1114 // when we are visible anyhow.
1119 lastPos: {x: undefined, y: undefined},
1120 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
1121 this.tracking = true;
1122 var watchCall = function() {
1123 // calc new position in lat/lon degrees
1124 // 90° on Earth surface are ~10,000 km at the equator,
1125 // so try moving at most 10m at a time
1126 if (geofake.lastPos.x)
1127 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
1129 geofake.lastPos.x = 48.208174
1130 if (geofake.lastPos.y)
1131 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
1133 geofake.lastPos.y = 16.373819
1134 aSuccessCallback({timestamp: Date.now(),
1135 coords: {latitude: geofake.lastPos.x,
1136 longitude: geofake.lastPos.y,
1138 if (geofake.tracking)
1139 setTimeout(watchCall, 1000);
1141 setTimeout(watchCall, 1000);
1144 clearWatch: function(aID) {
1145 this.tracking = false;
1149 function setCentering(aCheckbox) {
1150 if (gMapPrefsLoaded && mainDB)
1151 gPrefs.set("center_map", aCheckbox.checked);
1152 gCenterPosition = aCheckbox.checked;
1155 function setTracking(aCheckbox) {
1156 if (gMapPrefsLoaded && mainDB)
1157 gPrefs.set("tracking_enabled", aCheckbox.checked);
1158 if (aCheckbox.checked)
1164 function startTracking() {
1166 gActionLabel.textContent = "Establishing Position";
1167 gAction.style.display = "block";
1168 if (navigator.requestWakeLock) {
1169 gGPSWakeLock = navigator.requestWakeLock("gps");
1171 gGeoWatchID = gGeolocation.watchPosition(
1172 function(position) {
1173 if (gActionLabel.textContent) {
1174 gActionLabel.textContent = "";
1175 gAction.style.display = "none";
1177 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
1178 var tPoint = {time: position.timestamp,
1179 coords: {latitude: position.coords.latitude,
1180 longitude: position.coords.longitude,
1181 altitude: position.coords.altitude,
1182 accuracy: position.coords.accuracy,
1183 altitudeAccuracy: position.coords.altitudeAccuracy,
1184 heading: position.coords.heading,
1185 speed: position.coords.speed},
1186 beginSegment: !gLastTrackPoint};
1187 // Only add point to track is accuracy is good enough.
1188 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
1189 gLastTrackPoint = tPoint;
1190 gTrack.push(tPoint);
1191 try { gTrackStore.push(tPoint); } catch(e) {}
1192 var redrawn = false;
1193 if (gCenterPosition) {
1194 var posCoord = gps2xy(position.coords.latitude,
1195 position.coords.longitude);
1196 if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 ||
1197 Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) {
1198 gMap.pos.x = posCoord.x;
1199 gMap.pos.y = posCoord.y;
1200 gMap.draw(); // This draws the current point as well.
1205 undrawCurrentLocation();
1206 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
1208 drawCurrentLocation(tPoint);
1211 // Ignore erros for the moment, but this is good for debugging.
1212 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
1214 console.log(error.message);
1216 {enableHighAccuracy: true}
1221 function endTracking() {
1222 if (gActionLabel.textContent) {
1223 gActionLabel.textContent = "";
1224 gAction.style.display = "none";
1226 if (navigator.requestWakeLock && gGPSWakeLock) {
1227 console.log("releasing WakeLock");
1228 gGPSWakeLock.unlock();
1231 gGeolocation.clearWatch(gGeoWatchID);
1235 function clearTrack() {
1237 gTrackStore.clear();
1241 function loadTrack(aTrackId) {
1242 fetchBackend("track_json?id=" + encodeURIComponent(aTrackId), "GET", null,
1243 function(aResult, aStatusCode) {
1244 if (aStatusCode >= 400 || !aResult) {
1245 console.log("loading track failed: " + aStatusCode + ", result: " + aResult.message);
1248 console.log("loading track with " + aResult.length + " points.");
1250 for (var i = 0; i < gTrack.length; i++) {
1251 try { gTrackStore.push(gTrack[i]); } catch(e) {}
1259 var gTileService = {
1260 objStore: "tilecache",
1262 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
1264 get: function(aStyle, aCoords, aCallback) {
1265 var norm = normalizeCoords(aCoords);
1266 var dbkey = getTileKey(aStyle, norm);
1267 this.getDBCache(dbkey, function(aResult, aEvent) {
1269 // We did get a cached object.
1270 aCallback(aResult.image, aStyle, aCoords, dbkey);
1271 // Look at the timestamp and return if it's not too old.
1272 if (aResult.timestamp + gTileService.ageLimit > Date.now())
1274 // Reload cached tile otherwise.
1275 var oldDate = new Date(aResult.timestamp);
1276 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
1278 // Retrieve image from the web and store it in the cache.
1279 var XHR = new XMLHttpRequest();
1281 gMapStyles[aStyle].url
1282 .replace("{x}", norm.x)
1283 .replace("{y}", norm.y)
1284 .replace("{z}", norm.z)
1285 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 3)))
1286 .replace("[a-d]", String.fromCharCode(97 + Math.floor(Math.random() * 4)))
1287 .replace("[1-4]", 1 + Math.floor(Math.random() * 4)),
1289 XHR.responseType = "blob";
1290 XHR.addEventListener("load", function () {
1291 if (XHR.status === 200) {
1292 var blob = XHR.response;
1293 aCallback(blob, aStyle, aCoords, dbkey);
1294 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
1301 getDBCache: function(aKey, aCallback) {
1304 var transaction = mainDB.transaction([this.objStore]);
1305 var request = transaction.objectStore(this.objStore).get(aKey);
1306 request.onsuccess = function(event) {
1307 aCallback(request.result, event);
1309 request.onerror = function(event) {
1310 // Errors can be handled here.
1311 aCallback(undefined, event);
1315 setDBCache: function(aKey, aValue, aCallback) {
1318 var success = false;
1319 var transaction = mainDB.transaction([this.objStore], "readwrite");
1320 var objStore = transaction.objectStore(this.objStore);
1321 var request = objStore.put(aValue, aKey);
1322 request.onsuccess = function(event) {
1325 aCallback(success, event);
1327 request.onerror = function(event) {
1328 // Errors can be handled here.
1330 aCallback(success, event);
1334 unsetDBCache: function(aKey, aCallback) {
1337 var success = false;
1338 var transaction = mainDB.transaction([this.objStore], "readwrite");
1339 var request = transaction.objectStore(this.objStore).delete(aKey);
1340 request.onsuccess = function(event) {
1343 aCallback(success, event);
1345 request.onerror = function(event) {
1346 // Errors can be handled here.
1348 aCallback(success, event);
1352 clearDB: function(aCallback) {
1355 var success = false;
1356 var transaction = mainDB.transaction([this.objStore], "readwrite");
1357 var request = transaction.objectStore(this.objStore).clear();
1358 request.onsuccess = function(event) {
1360 console.log("Cache cleared.");
1362 aCallback(success, event);
1364 request.onerror = function(event) {
1365 // Errors can be handled here.
1366 console.log("Error clearing cache!");
1368 aCallback(success, event);