switch URL to matomo
[lantea.git] / js / map.js
CommitLineData
a7393a71
RK
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/. */
23cd2dcc 4
aa45a91b 5var gGLMapCanvas, gTrackCanvas, gGeolocation;
0dc9cd0d 6var gDebug = false;
23cd2dcc 7
b054bd48 8var gMinTrackAccuracy = 1000; // meters
68ca4617 9var gCenterDelayAfterMove = 3000; // milliseconds
b054bd48 10
b47b4a65
RK
11var gMapStyles = {
12 // OSM tile usage policy: http://wiki.openstreetmap.org/wiki/Tile_usage_policy
55c4a0b7 13 // Find some more OSM ones at http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers
ca77d52d 14 // and http://wiki.openstreetmap.org/wiki/Tiles or http://wiki.openstreetmap.org/wiki/TMS
b47b4a65
RK
15 osm_mapnik:
16 {name: "OpenStreetMap (Mapnik)",
a40d8348 17 url: "https://[a-c].tile.openstreetmap.org/{z}/{x}/{y}.png",
5a19ec68 18 copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
14e6d3ad
RK
19 osm_cyclemap:
20 {name: "Cycle Map (OSM)",
a40d8348 21 url: "https://[a-c].tile.thunderforest.com/cycle/{z}/{x}/{y}.png", // "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
5a19ec68 22 copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
14e6d3ad
RK
23 osm_transmap:
24 {name: "Transport Map (OSM)",
a40d8348 25 url: "https://[a-c].tile.thunderforest.com/transport/{z}/{x}/{y}.png", // "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png",
5a19ec68 26 copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
ca77d52d
RK
27 osm_germany:
28 {name: "OSM German Style",
9e501811 29 url: "https://tilecache[1-4].kairo.at/osmde/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
e4840ddc 30 //url: "http://[a-d].tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png", // https is not supported at all
ca77d52d 31 copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
e4840ddc
RK
32 oepnvkarte:
33 {name: "ÖPNV-Karte (OSM)",
9e501811 34 url: "https://tilecache[1-4].kairo.at/oepnv/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
e4840ddc
RK
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 &copy; <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>.'},
b47b4a65 37 mapquest_open:
55c4a0b7 38 {name: "MapQuest OSM",
31011cc9 39 url: "https://tilecache[1-4].kairo.at/mapqosm/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
e4840ddc 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
ca77d52d 41 copyright: 'Map data &copy; <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>.'},
55c4a0b7
RK
42 mapquest_aerial:
43 {name: "MapQuest Open Aerial",
31011cc9 44 url: "https://tilecache[1-4].kairo.at/mapqsat/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
e4840ddc 45 //url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg",
5a19ec68 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.'},
ca77d52d
RK
47 osm_hot:
48 {name: "OSM HOT style",
31011cc9 49 url: "https://tilecache[1-4].kairo.at/osmhot/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
e4840ddc 50 //url: "http://[a-c].tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", // https has CAcert which doesn't work in browsers
ca77d52d 51 copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
e4840ddc
RK
52 hikebike:
53 {name: "Hike and Bike (OSM)",
31011cc9 54 url: "https://tilecache[1-4].kairo.at/hikebike/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
e4840ddc
RK
55 //url: "http://toolserver.org/tiles/hikebike/{z}/{x}/{y}.png", // toolserver.org does not support CORS at this time :(
56 copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
57 outdoors:
58 {name: "Outdoors (OSM)",
31011cc9 59 url: "https://[a-c].tile.thunderforest.com/outdoors/{z}/{x}/{y}.png", // url: "http://[a-c].tile.opencyclemap.org/outdoors/{z}/{x}/{y}.png",
e4840ddc 60 copyright: 'Map data &copy; <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>.'},
ca77d52d 61 stamen_toner:
e4840ddc 62 {name: "Stamen Toner (B+W)",
31011cc9 63 url: "https://tilecache[1-4].kairo.at/toner/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
e4840ddc 64 //url: "http://[a-c].tile.stamen.com/toner/{z}/{x}/{y}.jpg", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
ca77d52d
RK
65 copyright: 'Map data &copy; <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>.'},
66 stamen_terrain:
e4840ddc 67 {name: "Stamen Terrain (USA only)",
31011cc9 68 url: "https://tilecache[1-4].kairo.at/terrain/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
e4840ddc 69 //url: "http://[a-c].tile.stamen.com/terrain/{z}/{x}/{y}.jpg", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
ca77d52d
RK
70 copyright: 'Map data &copy; <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>.'},
71 stamen_watercolor:
e4840ddc 72 {name: "Stamen Watercolor (artistic)",
31011cc9 73 url: "https://tilecache[1-4].kairo.at/watercolor/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at
e4840ddc 74 //url: "http://[a-c].tile.stamen.com/watercolor/{z}/{x}/{y}.jpg", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com
ca77d52d 75 copyright: 'Map data &copy; <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>.'},
b47b4a65 76};
23cd2dcc
RK
77
78var gLastMouseX = 0;
79var gLastMouseY = 0;
80
b395419b 81var gLoadingTile;
23cd2dcc 82
3610c22d
RK
83var gMapPrefsLoaded = false;
84
23cd2dcc 85var gDragging = false;
517c0099 86var gDragTouchID, gPinchStartWidth;
23cd2dcc 87
d361104b 88var gGeoWatchID, gGPSWakeLock;
55c4a0b7 89var gTrack = [];
aa45a91b 90var gLastTrackPoint;
05c21757 91var gCenterPosition = true;
68ca4617 92var gLastMoveAction = null;
55c4a0b7 93
b47b4a65 94function initMap() {
4b12da3a 95 gGeolocation = navigator.geolocation;
ac6286bd
RK
96 // Set up canvas context.
97 gGLMapCanvas = document.getElementById("map");
ecde0af2
RK
98 try {
99 // Try to grab the standard context. If it fails, fallback to experimental.
100 // We also try to tell it we do not need a depth buffer.
edc3be71
RK
101 gMap.gl = gGLMapCanvas.getContext("webgl", {depth: false}) ||
102 gGLMapCanvas.getContext("experimental-webgl", {depth: false});
ecde0af2
RK
103 }
104 catch(e) {}
edc3be71 105 if (!gMap.gl) {
16e4f664 106 // If we don't have a GL context, give up now
ecde0af2 107 showGLWarningDialog();
edc3be71 108 gMap.gl = null;
ecde0af2 109 }
16e4f664
RK
110 else {
111 // GL context can be lost at any time, handle that.
112 // See http://www.khronos.org/webgl/wiki/HandlingContextLost
113 gGLMapCanvas.addEventListener("webglcontextlost",
114 gMap.handleContextLost, false);
115 gGLMapCanvas.addEventListener("webglcontextrestored",
116 gMap.handleContextRestored, false);
117 }
4b1d0915 118 gTrackCanvas = document.getElementById("track");
aa45a91b 119 gTrackLayer.context = gTrackCanvas.getContext("2d");
23cd2dcc 120
4b12da3a
RK
121 //gDebug = true;
122 if (gDebug) {
123 gGeolocation = geofake;
124 var hiddenList = document.getElementsByClassName("debugHide");
125 // last to first - list of elements with that class is changing!
126 for (var i = hiddenList.length - 1; i >= 0; i--) {
127 hiddenList[i].classList.remove("debugHide");
128 }
129 }
130
edc3be71 131 gAction.addEventListener("prefload-done", gMap.initGL, false);
ecde0af2 132
582d50fc
RK
133 console.log("map vars set, loading prefs...");
134 loadPrefs();
135}
b395419b 136
582d50fc
RK
137function loadPrefs(aEvent) {
138 if (aEvent && aEvent.type == "prefs-step") {
139 console.log("wait: " + gWaitCounter);
140 if (gWaitCounter == 0) {
141 gAction.removeEventListener(aEvent.type, loadPrefs, false);
142 gMapPrefsLoaded = true;
143 console.log("prefs loaded.");
144
145 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
146 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
147 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
148 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
149
150 gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
151 gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
152 gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
153 gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
154 gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
155
156 gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
157
158 document.getElementById("body").addEventListener("keydown", mapEvHandler, false);
159
5dd2ab70
RK
160 document.addEventListener("visibilitychange", visibilityEvHandler, false);
161
d7310ee2 162 console.log("Events added.");
582d50fc 163
decacd7f 164 console.log("Init loading tile...");
582d50fc 165 gLoadingTile = new Image();
582d50fc 166 gLoadingTile.onload = function() {
decacd7f 167 console.log("Loading tile loaded.");
ecde0af2 168 var throwEv = new CustomEvent("prefload-done");
582d50fc
RK
169 gAction.dispatchEvent(throwEv);
170 };
decacd7f
RK
171 console.log("Set loading tile...");
172 gLoadingTile.src = "style/loading.png";
582d50fc
RK
173 }
174 }
175 else {
176 if (aEvent)
177 gAction.removeEventListener(aEvent.type, loadPrefs, false);
178 gAction.addEventListener("prefs-step", loadPrefs, false);
179 gWaitCounter++;
ae9e33a2
RK
180 gPrefs.get("active_map_style", function(aValue) {
181 if (aValue && gMapStyles[aValue]) {
182 gMap.activeMap = aValue;
183 }
33a97b69
RK
184 else {
185 gMap.activeMap = "osm_mapnik";
186 }
187 document.getElementById("mapSelector").value = gMap.activeMap;
188 document.getElementById("copyright").innerHTML =
189 gMapStyles[gMap.activeMap].copyright;
ae9e33a2
RK
190 gWaitCounter--;
191 var throwEv = new CustomEvent("prefs-step");
192 gAction.dispatchEvent(throwEv);
193 });
194 gWaitCounter++;
582d50fc 195 gPrefs.get("position", function(aValue) {
ac6286bd 196 if (aValue && aValue.x && aValue.y && aValue.z) {
dda55132 197 gMap.pos = aValue;
582d50fc 198 }
df81068a
RK
199 gWaitCounter--;
200 var throwEv = new CustomEvent("prefs-step");
201 gAction.dispatchEvent(throwEv);
582d50fc
RK
202 });
203 gWaitCounter++;
204 gPrefs.get("center_map", function(aValue) {
ae9e33a2 205 if (aValue === undefined) {
582d50fc 206 document.getElementById("centerCheckbox").checked = true;
ae9e33a2
RK
207 }
208 else {
582d50fc 209 document.getElementById("centerCheckbox").checked = aValue;
ae9e33a2 210 }
582d50fc
RK
211 setCentering(document.getElementById("centerCheckbox"));
212 gWaitCounter--;
213 var throwEv = new CustomEvent("prefs-step");
214 gAction.dispatchEvent(throwEv);
215 });
216 gWaitCounter++;
217 gPrefs.get("tracking_enabled", function(aValue) {
ae9e33a2 218 if (aValue === undefined) {
582d50fc 219 document.getElementById("trackCheckbox").checked = true;
ae9e33a2
RK
220 }
221 else {
582d50fc 222 document.getElementById("trackCheckbox").checked = aValue;
ae9e33a2 223 }
582d50fc
RK
224 gWaitCounter--;
225 var throwEv = new CustomEvent("prefs-step");
226 gAction.dispatchEvent(throwEv);
227 });
228 gWaitCounter++;
cef88e12
RK
229 var trackLoadStarted = false;
230 var redrawBase = 100;
6ddefbf9
RK
231 gTrackStore.getListStepped(function(aTPoint) {
232 if (aTPoint) {
233 // Add in front and return new length.
234 var tracklen = gTrack.unshift(aTPoint);
7a076538
RK
235 // Redraw track periodically, larger distance the longer it gets
236 // (but clamped to the first value over a certain limit).
fdaf08db
RK
237 // Initial paint will do initial track drawing.
238 if (tracklen % redrawBase == 0) {
b4df67c9 239 gTrackLayer.drawTrack(); // TODO: we could draw incremmentally if we would support reverse-direction drawing...
7a076538
RK
240 if (redrawBase < 1000) {
241 redrawBase = tracklen;
242 }
fdaf08db 243 }
6ddefbf9
RK
244 }
245 else {
246 // Last point received.
b4df67c9 247 gTrackLayer.drawTrack(); // TODO: we could draw incremmentally if we would support reverse-direction drawing...
6ddefbf9
RK
248 }
249 if (!trackLoadStarted) {
250 // We have the most recent point, if present, rest will load async.
251 trackLoadStarted = true;
252 gWaitCounter--;
253 var throwEv = new CustomEvent("prefs-step");
254 gAction.dispatchEvent(throwEv);
582d50fc 255 }
582d50fc
RK
256 });
257 }
23cd2dcc
RK
258}
259
edc3be71
RK
260var gMap = {
261 gl: null,
262 glShaderProgram: null,
263 glVertexPositionAttr: null,
264 glTextureCoordAttr: null,
265 glResolutionAttr: null,
266 glMapTexture: null,
e8525b46 267 glTextures: {},
d6ff6891
RK
268 glTxCleanIntervalID: null,
269 glTexturesPerZoomLevel: 0,
edc3be71 270
dda55132
RK
271 activeMap: "osm_mapnik",
272 tileSize: 256,
273 maxZoom: 18, // The minimum is 0.
274 zoomFactor: null,
275 pos: {
276 x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
277 y: 23670000.0, // The range is 0-67108864 (2^gMap.maxZoom * gMap.tileSize)
278 z: 5 // This could be fractional if supported being between zoom levels.
279 },
d6ff6891
RK
280 baseDim: { // Map width, height and tile size in level 18 pixels.
281 wid: null,
282 ht: null,
283 tsize: null,
284 },
aa45a91b 285 glDrawRequested: false, // To avoid parallel calls to drawGL().
dda55132 286
ac6286bd
RK
287 get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; },
288 get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; },
289
edc3be71
RK
290 getVertShaderSource: function() {
291 return 'attribute vec2 aVertexPosition;\n' +
292 'attribute vec2 aTextureCoord;\n\n' +
293 'uniform vec2 uResolution;\n\n' +
294 'varying highp vec2 vTextureCoord;\n\n' +
295 'void main(void) {\n' +
296 // convert the rectangle from pixels to -1.0 to +1.0 (clipspace) 0.0 to 1.0
297 ' vec2 clipSpace = aVertexPosition * 2.0 / uResolution - 1.0;\n' +
298 ' gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' +
299 ' vTextureCoord = aTextureCoord;\n' +
300 '}'; },
d7310ee2 301 getFragShaderSource: function() {
edc3be71
RK
302 return 'varying highp vec2 vTextureCoord;\n\n' +
303 'uniform sampler2D uImage;\n\n' +
304 'void main(void) {\n' +
305 ' gl_FragColor = texture2D(uImage, vTextureCoord);\n' +
306 '}'; },
307
308 initGL: function() {
309 // When called from the event listener, the "this" reference doesn't work, so use the object name.
b3a9fc52 310 console.log("Initializing WebGL...");
edc3be71
RK
311 if (gMap.gl) {
312 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
313 gMap.gl.clearColor(0.0, 0.0, 0.0, 0.5); // Set clear color to black, fully opaque.
314 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT|gMap.gl.DEPTH_BUFFER_BIT); // Clear the color.
315
316 // Create and initialize the shaders.
b3a9fc52 317 console.log("Create and compile shaders...");
edc3be71
RK
318 var vertShader = gMap.gl.createShader(gMap.gl.VERTEX_SHADER);
319 var fragShader = gMap.gl.createShader(gMap.gl.FRAGMENT_SHADER);
320 gMap.gl.shaderSource(vertShader, gMap.getVertShaderSource());
321 // Compile the shader program.
322 gMap.gl.compileShader(vertShader);
323 // See if it compiled successfully.
324 if (!gMap.gl.getShaderParameter(vertShader, gMap.gl.COMPILE_STATUS)) {
325 console.log("An error occurred compiling the vertex shader: " + gMap.gl.getShaderInfoLog(vertShader));
326 return null;
327 }
328 gMap.gl.shaderSource(fragShader, gMap.getFragShaderSource());
329 // Compile the shader program.
330 gMap.gl.compileShader(fragShader);
331 // See if it compiled successfully.
332 if (!gMap.gl.getShaderParameter(fragShader, gMap.gl.COMPILE_STATUS)) {
333 console.log("An error occurred compiling the fragment shader: " + gMap.gl.getShaderInfoLog(fragShader));
334 return null;
335 }
ecde0af2 336
b3a9fc52 337 console.log("Create and link shader program...");
edc3be71
RK
338 gMap.glShaderProgram = gMap.gl.createProgram();
339 gMap.gl.attachShader(gMap.glShaderProgram, vertShader);
340 gMap.gl.attachShader(gMap.glShaderProgram, fragShader);
341 gMap.gl.linkProgram(gMap.glShaderProgram);
342 // If creating the shader program failed, alert
343 if (!gMap.gl.getProgramParameter(gMap.glShaderProgram, gMap.gl.LINK_STATUS)) {
344 alert("Unable to initialize the shader program.");
345 }
346 gMap.gl.useProgram(gMap.glShaderProgram);
347 // Get locations of the attributes.
348 gMap.glVertexPositionAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aVertexPosition");
349 gMap.glTextureCoordAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aTextureCoord");
350 gMap.glResolutionAttr = gMap.gl.getUniformLocation(gMap.glShaderProgram, "uResolution");
351
b3a9fc52 352 console.log("Set up vertex buffer...");
edc3be71
RK
353 var tileVerticesBuffer = gMap.gl.createBuffer();
354 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, tileVerticesBuffer);
355 // The vertices are the coordinates of the corner points of the square.
356 var vertices = [
357 0.0, 0.0,
358 1.0, 0.0,
359 0.0, 1.0,
360 0.0, 1.0,
361 1.0, 0.0,
362 1.0, 1.0,
363 ];
364 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(vertices), gMap.gl.STATIC_DRAW);
365 gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr);
366 gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0);
367
dc047338 368 gMap.loadImageToTexture(gLoadingTile, getTileKey("loading", {x: 0, y: 0, z: 0}));
edc3be71
RK
369
370 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
371
372 // Create a buffer for the position of the rectangle corners.
b3a9fc52 373 console.log("Set up coord buffer...");
edc3be71
RK
374 var mapVerticesTextureCoordBuffer = gMap.gl.createBuffer();
375 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer);
376 gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr);
377 gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0);
d6ff6891
RK
378
379 // Call texture cleaning every 30 seconds, for now (is 60 better?).
380 gMap.glTxCleanIntervalID = window.setInterval(gMap.cleanTextures, 30 * 1000);
ecde0af2 381 }
edc3be71 382
16e4f664
RK
383 if (!gAppInitDone) {
384 // We may be called when context was lost and destroyed,
385 // only send event when we are in app startup
386 // (gAppInitDone is set to true right after we return this event).
387 var throwEv = new CustomEvent("mapinit-done");
388 gAction.dispatchEvent(throwEv);
389 }
edc3be71
RK
390 },
391
0f6678fa
RK
392 draw: function() {
393 gMap.assembleGL();
aa45a91b 394 gTrackLayer.drawTrack();
dda55132 395 },
ecde0af2 396
0f6678fa 397 assembleGL: function() {
dda55132 398 if (!gMap.gl) { return; }
dda55132
RK
399
400 document.getElementById("zoomLevel").textContent = gMap.pos.z;
401 gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
d6ff6891
RK
402 gMap.baseDim.wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor;
403 gMap.baseDim.ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor;
404 gMap.baseDim.tsize = gMap.tileSize * gMap.zoomFactor;
dda55132 405
d6ff6891
RK
406 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
407 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
408 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
409 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
dda55132
RK
410
411 if (gMapPrefsLoaded && mainDB)
412 gPrefs.set("position", gMap.pos);
413
dda55132 414 // Go through all the tiles in the map, find out if to draw them and do so.
d6ff6891
RK
415 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
416 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
0f6678fa
RK
417 // Only go to loading step if we haven't loaded the texture.
418 var coords = {x: x, y: y, z: gMap.pos.z};
419 var tileKey = getTileKey(gMap.activeMap, normalizeCoords(coords));
dc047338 420 if (!gMap.glTextures[tileKey]) {
dda55132 421 // Initiate loading/drawing of the actual tile.
0f6678fa 422 gTileService.get(gMap.activeMap, coords,
b9707ee0 423 function(aImage, aStyle, aCoords, aTileKey) {
0f6678fa 424 // Only actually load if this still applies for the current view.
dda55132 425 if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) {
0f6678fa
RK
426 var URL = window.URL;
427 var imgURL = URL.createObjectURL(aImage);
428 var imgObj = new Image();
429 imgObj.onload = function() {
dc047338 430 gMap.loadImageToTexture(imgObj, aTileKey);
aa45a91b 431 gMap.requestDrawGL();
0f6678fa 432 URL.revokeObjectURL(imgURL);
dda55132 433 }
0f6678fa 434 imgObj.src = imgURL;
dda55132
RK
435 }
436 });
dda55132
RK
437 }
438 }
439 }
aa45a91b
RK
440 gMap.requestDrawGL();
441 },
442
443 requestDrawGL: function() {
444 // Only draw if we're actually visible.
445 // Also, avoid running this multiple times when it could not complete yet.
446 if (document.hidden != true && !gMap.glDrawRequested) {
447 gMap.glDrawRequested = true;
448 window.requestAnimationFrame(gMap.drawGL);
5dd2ab70 449 }
b9707ee0
RK
450 },
451
aa45a91b 452 drawGL: function(aTimestamp) {
d6ff6891
RK
453 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
454 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
455 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
456 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
b9707ee0 457
b9707ee0 458 // Go through all the tiles in the map, find out if to draw them and do so.
d6ff6891
RK
459 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
460 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
461 // Rounding the pixel offsets ensures we position the tiles precisely.
462 var xoff = Math.round((x * gMap.baseDim.tsize - xMin) / gMap.zoomFactor);
463 var yoff = Math.round((y * gMap.baseDim.tsize - yMin) / gMap.zoomFactor);
dc047338 464 // Draw the tile, first find out the actual texture to use.
b9707ee0
RK
465 var norm = normalizeCoords({x: x, y: y, z: gMap.pos.z});
466 var tileKey = getTileKey(gMap.activeMap, norm);
dc047338
RK
467 if (!gMap.glTextures[tileKey]) {
468 tileKey = getTileKey("loading", {x: 0, y: 0, z: 0});
469 }
470 gMap.drawTileGL(xoff, yoff, tileKey);
b9707ee0
RK
471 }
472 }
aa45a91b 473 gMap.glDrawRequested = false;
dda55132 474 },
edc3be71 475
ac6286bd
RK
476 resizeAndDraw: function() {
477 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
478 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
479 if (gGLMapCanvas && gTrackCanvas) {
480 gGLMapCanvas.width = viewportWidth;
481 gGLMapCanvas.height = viewportHeight;
482 gTrackCanvas.width = viewportWidth;
483 gTrackCanvas.height = viewportHeight;
484 if (gMap.gl) {
485 // Size viewport to canvas size.
486 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
487 // Clear the color.
488 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT);
489 // Make sure the vertex shader get the right resolution.
490 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
d6ff6891
RK
491 // Prepare recalculation of textures to keep for one zoom level.
492 gMap.glTexturesPerZoomLevel = 0;
ac6286bd
RK
493 }
494 gMap.draw();
495 showUI();
496 }
dda55132
RK
497 },
498
dc047338 499 drawTileGL: function(aLeft, aRight, aTileKey) {
b9707ee0 500 gMap.gl.activeTexture(gMap.gl.TEXTURE0);
dc047338 501 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
b9707ee0
RK
502 // Set uImage to refer to TEXTURE0
503 gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0);
dda55132
RK
504 var x_start = aLeft;
505 var i_width = gMap.tileSize;
506 var y_start = aRight;
507 var i_height = gMap.tileSize;
edc3be71
RK
508 var textureCoordinates = [
509 x_start, y_start,
510 x_start + i_width, y_start,
511 x_start, y_start + i_height,
512 x_start, y_start + i_height,
513 x_start + i_width, y_start,
514 x_start + i_width, y_start + i_height,
515 ];
516 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW);
edc3be71
RK
517
518 // There are 6 indices in textureCoordinates.
519 gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
e8525b46
RK
520 },
521
dc047338 522 loadImageToTexture: function(aImage, aTileKey) {
e8525b46 523 // Create and bind texture.
dc047338
RK
524 gMap.glTextures[aTileKey] = gMap.gl.createTexture();
525 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
e8525b46
RK
526 // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two).
527 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST);
528 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST);
529 // Upload the image into the texture.
530 gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage);
531 },
d6ff6891
RK
532
533 cleanTextures: function() {
534 // Get rid of unneeded textures to save memory.
535 // TODO: Be less aggressive, maybe keep neighboring zoom levels (but x/y coords there are zoom-specific).
536 if (!gMap.glTexturesPerZoomLevel) {
537 // Calculate how many textures we need to keep for one zoom level.
538 // ceil(width/size) gives us the minimum, keep one on either side as well.
539 gMap.glTexturesPerZoomLevel =
540 Math.ceil(gMap.gl.drawingBufferWidth / gMap.tileSize + 2) *
541 Math.ceil(gMap.gl.drawingBufferHeight / gMap.tileSize + 2);
542 console.log("Keeping " + gMap.glTexturesPerZoomLevel + " textures per level");
543 }
544 if (Object.keys(gMap.glTextures).length > gMap.glTexturesPerZoomLevel) {
545 console.log("Cleaning textures... (have " + Object.keys(gMap.glTextures).length + " atm)");
546
547 // Find coordinate ranges for tiles to keep.
548 var tMin = normalizeCoords({x: Math.floor((gMap.pos.x - gMap.baseDim.wid / 2) / gMap.baseDim.tsize) - 1,
549 y: Math.floor((gMap.pos.y - gMap.baseDim.ht / 2) / gMap.baseDim.tsize) - 1,
550 z: gMap.pos.z});
551 var tMax = normalizeCoords({x: Math.ceil((gMap.pos.x + gMap.baseDim.wid / 2) / gMap.baseDim.tsize) + 1,
552 y: Math.ceil((gMap.pos.y + gMap.baseDim.ht / 2) / gMap.baseDim.tsize) + 1,
553 z: gMap.pos.z});
554 console.log("In range: " + tMin.x + "," + tMin.y + "," + tMin.z + " - " + tMax.x + "," + tMax.y + "," + tMax.z);
bb752fc4
RK
555 for (var tileKey in gMap.glTextures) {
556 var keyMatches = tileKey.match(/([^:]+)::(\d+),(\d+),(\d+)/);
d6ff6891
RK
557 if (keyMatches && keyMatches[1] != "loading") {
558 var txData = {
559 style: keyMatches[1],
560 x: keyMatches[2],
561 y: keyMatches[3],
562 z: keyMatches[4],
563 }
564 var delTx = false;
565 if (txData.style != gMap.activeMap) { delTx = true; console.log("Different map style: " + txData.style); }
566 if (!delTx && (txData.z < tMin.z || txData.z > tMax.z)) { delTx = true; console.log("Out-of-range zoom: " + txData.z); }
567 if (tMin.x < tMax.x) {
568 if (!delTx && (txData.x < tMin.x || txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
569 }
570 else {
571 // We are crossing over the 0 coordinate!
572 if (!delTx && (txData.x < tMin.x && txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
573 }
574 if (tMin.y < tMax.y) {
575 if (!delTx && (txData.y < tMin.y || txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
576 }
577 else {
578 // We are crossing over the 0 coordinate!
579 if (!delTx && (txData.y < tMin.y && txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
580 }
581 if (delTx) {
582 // Delete texture from GL and from the array we are holding.
bb752fc4
RK
583 gMap.gl.deleteTexture(gMap.glTextures[tileKey]);
584 delete gMap.glTextures[tileKey];
d6ff6891
RK
585 }
586 }
587 }
e4840ddc 588 console.log("Cleaning complete, " + Object.keys(gMap.glTextures).length + " textures left");
d6ff6891
RK
589 }
590 },
16e4f664 591
aa45a91b
RK
592 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
593 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
594
595 zoomIn: function() {
596 if (gMap.pos.z < gMap.maxZoom) {
597 gMap.pos.z++;
598 gMap.draw();
599 }
600 },
601
602 zoomOut: function() {
603 if (gMap.pos.z > 0) {
604 gMap.pos.z--;
605 gMap.draw();
606 }
607 },
608
609 zoomTo: function(aTargetLevel) {
610 aTargetLevel = parseInt(aTargetLevel);
611 if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) {
612 gMap.pos.z = aTargetLevel;
613 gMap.draw();
614 }
615 },
616
617 setActiveMap: function(aStyle) {
618 gMap.activeMap = aStyle;
619 gPrefs.set("active_map_style", gMap.activeMap);
620 document.getElementById("copyright").innerHTML =
621 gMapStyles[gMap.activeMap].copyright;
622 if (!gWaitCounter) { // Only do this when prefs are loaded already.
623 showUI();
624 gMap.draw();
625 }
626 },
627
16e4f664
RK
628 handleContextLost: function(event) {
629 event.preventDefault();
630 // GL context is gone, let's reset everything that depends on it.
631 clearInterval(gMap.glTxCleanIntervalID);
632 gMap.glTextures = {};
633 },
634
635 handleContextRestored: function(event) {
636 // When GL context is back, init GL again and draw.
637 gMap.initGL();
638 gMap.draw();
639 },
ecde0af2
RK
640}
641
aa45a91b
RK
642var gTrackLayer = {
643 context: null,
644 curPosMapCache: undefined,
645 lastDrawnPoint: null,
b4df67c9
RK
646 lastRequestedIndex: null, // may not have been actually drawn...
647 drawRequested: false,
648 restartDrawing: true,
68ca4617 649
b4df67c9 650 maxDrawTime: 10, // max time allowed for drawing a section, in ms - 10 means we can do 100 fps smoothly
68ca4617
RK
651 trackWidth: 2, // pixels
652 trackColor: "#FF0000",
653 curLocSize: 6, // pixels
654 curLocColor: "#A00000",
aa45a91b 655
b4df67c9
RK
656 drawTrack: function(needRestart = true) {
657 // TODO: figure out if we can support reverse drawing while initially loading the track.
658 // Only draw if we're actually visible.
659 // Also, avoid running this multiple times when it could not complete yet.
660 if (needRestart) { gTrackLayer.restartDrawing = true; }
661 if (gTrackLayer.context && document.hidden != true && !gTrackLayer.drawRequested) {
662 gTrackLayer.drawRequested = true;
663 window.requestAnimationFrame(gTrackLayer.drawTrackSection);
664 }
665 },
666
667 drawTrackSection: function(aTimestamp) {
668 var start = performance.now();
669 if (gTrackLayer.restartDrawing) {
670 gTrackLayer.lastRequestedIndex = 0;
aa45a91b 671 gTrackLayer.lastDrawnPoint = null;
b4df67c9 672 gTrackLayer.restartDrawing = false;
aa45a91b
RK
673 gTrackLayer.curPosMapCache = undefined;
674 gTrackLayer.context.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
b4df67c9
RK
675 }
676 if (gTrack.length && (performance.now() < start + gTrackLayer.maxDrawTime)) {
677 for (; gTrackLayer.lastRequestedIndex < gTrack.length; gTrackLayer.lastRequestedIndex++) {
678 gTrackLayer.drawTrackPoint(gTrackLayer.lastRequestedIndex);
679 if (performance.now() >= start + gTrackLayer.maxDrawTime) {
680 // Break out of the loop if we are over the max allowed time, we'll continue in the next rAF (see below).
9292a1b7 681 gTrackLayer.drawTrackPoint(null);
b4df67c9 682 break;
aa45a91b
RK
683 }
684 }
685 }
b4df67c9
RK
686 // If we still have work to do and we're still visible, continue drawing.
687 if ((gTrackLayer.lastRequestedIndex + 1 < gTrack.length) && gTrackLayer.context && (document.hidden != true)) {
688 window.requestAnimationFrame(gTrackLayer.drawTrackSection);
689 }
690 gTrackLayer.drawRequested = false;
aa45a91b 691 },
b5e49b95 692
b4df67c9
RK
693 drawTrackPoint: function(aIndex) {
694 gTrackLayer.running = true;
9292a1b7
RK
695 if (!aIndex && aIndex !== 0) {
696 // We can be called this way to make sure we draw an actual line up to where we are right now.
697 if (gTrackLayer.lastDrawnPoint && gTrackLayer.lastDrawnPoint.optimized) {
698 gTrackLayer.context.stroke();
699 gTrackLayer.lastDrawnPoint.optimized = false;
700 }
701 return;
702 }
b4df67c9
RK
703 var trackpoint = {"worldpos": gps2xy(gTrack[aIndex].coords.latitude, gTrack[aIndex].coords.longitude)};
704 var isLastPoint = (aIndex + 1 >= gTrack.length || gTrack[aIndex+1].beginSegment);
aa45a91b
RK
705 var update_drawnpoint = true;
706 // lastPoint is for optimizing (not actually executing the draw until the last)
b4df67c9
RK
707 trackpoint.segmentEnd = (isLastPoint === true);
708 trackpoint.optimized = (isLastPoint === false);
aa45a91b
RK
709 trackpoint.mappos = {x: Math.round((trackpoint.worldpos.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
710 y: Math.round((trackpoint.worldpos.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
711 trackpoint.skip_drawing = false;
712 if (gTrackLayer.lastDrawnPoint) {
713 // Lines completely outside the current display should not be drawn.
714 if ((trackpoint.mappos.x < 0 && gTrackLayer.lastDrawnPoint.mappos.x < 0) ||
715 (trackpoint.mappos.x > gMap.width && gTrackLayer.lastDrawnPoint.mappos.x > gMap.width) ||
716 (trackpoint.mappos.y < 0 && gTrackLayer.lastDrawnPoint.mappos.y < 0) ||
717 (trackpoint.mappos.y > gMap.height && gTrackLayer.lastDrawnPoint.mappos.y > gMap.height)) {
718 trackpoint.skip_drawing = true;
719 }
720 }
721 if (!gTrackLayer.lastDrawnPoint || !gTrackLayer.lastDrawnPoint.optimized) {
68ca4617 722 gTrackLayer.context.strokeStyle = gTrackLayer.trackColor;
aa45a91b 723 gTrackLayer.context.fillStyle = gTrackLayer.context.strokeStyle;
68ca4617 724 gTrackLayer.context.lineWidth = gTrackLayer.trackWidth;
aa45a91b
RK
725 gTrackLayer.context.lineCap = "round";
726 gTrackLayer.context.lineJoin = "round";
727 }
728 // This breaks optimiziation, so make sure to reset optimization.
729 if (trackpoint.skip_drawing || !gTrackLayer.lastDrawnPoint) {
730 trackpoint.optimized = false;
731 // Close path if one was open.
732 if (gTrackLayer.lastDrawnPoint && gTrackLayer.lastDrawnPoint.optimized) {
733 gTrackLayer.context.stroke();
734 }
735 }
736 if (!trackpoint.skip_drawing) {
737 if (gTrackLayer.lastDrawnPoint && gTrackLayer.lastDrawnPoint.skip_drawing && !gTrackLayer.lastDrawnPoint.segmentEnd) {
738 // If the last point was skipped but the current one isn't, draw a segment start
739 // for the off-screen previous one as well as a connection line.
740 gTrackLayer.context.beginPath();
741 gTrackLayer.context.arc(gTrackLayer.lastDrawnPoint.mappos.x, gTrackLayer.lastDrawnPoint.mappos.y,
742 gTrackLayer.context.lineWidth, 0, Math.PI * 2, false);
743 gTrackLayer.context.fill();
744 gTrackLayer.context.lineTo(trackpoint.mappos.x, trackpoint.mappos.y);
745 }
746 else if (!gTrackLayer.lastDrawnPoint || !gTrackLayer.lastDrawnPoint.optimized) {
747 // Start drawing a segment with the current point.
748 gTrackLayer.context.beginPath();
749 gTrackLayer.context.arc(trackpoint.mappos.x, trackpoint.mappos.y,
750 gTrackLayer.context.lineWidth, 0, Math.PI * 2, false);
751 gTrackLayer.context.fill();
752 }
753 else if (!trackpoint.segmentEnd && gTrackLayer.lastDrawnPoint &&
754 (Math.abs(gTrackLayer.lastDrawnPoint.mappos.x - trackpoint.mappos.x) <= 1) &&
755 (Math.abs(gTrackLayer.lastDrawnPoint.mappos.y - trackpoint.mappos.y) <= 1)) {
756 // We would draw the same or almost the same point, don't do any actual drawing.
757 update_drawnpoint = false;
758 }
759 else {
760 // Continue drawing segment, close if needed.
761 gTrackLayer.context.lineTo(trackpoint.mappos.x, trackpoint.mappos.y);
762 if (!trackpoint.optimized)
763 gTrackLayer.context.stroke();
764 }
765 }
766 if (update_drawnpoint) {
767 gTrackLayer.lastDrawnPoint = trackpoint;
768 }
769 },
23cd2dcc 770
aa45a91b 771 drawCurrentLocation: function(trackPoint) {
b4df67c9
RK
772 // Only run this when visible and we are not drawing a track right now.
773 if (gTrackLayer.context && document.hidden != true && !gTrackLayer.drawRequested) {
774 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
68ca4617 775 var circleRadius = Math.round(gTrackLayer.curLocSize / 2);
b4df67c9
RK
776 var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
777 y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
778
779 gTrackLayer.undrawCurrentLocation();
780
781 // Cache overdrawn area.
782 gTrackLayer.curPosMapCache =
783 {point: locpoint,
784 radius: circleRadius,
785 data: gTrackLayer.context.getImageData(mappos.x - circleRadius,
786 mappos.y - circleRadius,
787 circleRadius * 2, circleRadius * 2)};
788
68ca4617 789 gTrackLayer.context.strokeStyle = gTrackLayer.curLocColor;
b4df67c9
RK
790 gTrackLayer.context.fillStyle = gTrackLayer.context.strokeStyle;
791 gTrackLayer.context.beginPath();
792 gTrackLayer.context.arc(mappos.x, mappos.y,
793 circleRadius, 0, Math.PI * 2, false);
794 gTrackLayer.context.fill();
795 }
aa45a91b 796 },
23cd2dcc 797
aa45a91b 798 undrawCurrentLocation: function() {
b4df67c9
RK
799 // Only run this when visible and we are not drawing a track right now.
800 if (gTrackLayer.context && document.hidden != true && !gTrackLayer.drawRequested) {
801 if (gTrackLayer.curPosMapCache) {
802 var oldpoint = gTrackLayer.curPosMapCache.point;
803 var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
804 y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
805 gTrackLayer.context.putImageData(gTrackLayer.curPosMapCache.data,
806 oldmp.x - gTrackLayer.curPosMapCache.radius,
807 oldmp.y - gTrackLayer.curPosMapCache.radius);
808 gTrackLayer.curPosMapCache = undefined;
809 }
aa45a91b 810 }
1222624d
RK
811 }
812}
813
55c4a0b7 814function gps2xy(aLatitude, aLongitude) {
dda55132 815 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
55c4a0b7
RK
816 var convLat = aLatitude * Math.PI / 180;
817 var rawY = (1 - Math.log(Math.tan(convLat) +
818 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
819 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
820 return {x: Math.round(rawX),
821 y: Math.round(rawY)};
822}
823
824function xy2gps(aX, aY) {
dda55132 825 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
55c4a0b7
RK
826 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
827 return {latitude: 180 / Math.PI *
828 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
829 longitude: aX / maxZoomFactor * 360 - 180};
830}
831
23cd2dcc
RK
832// A sane mod function that works for negative numbers.
833// Returns a % b.
834function mod(a, b) {
835 return ((a % b) + b) % b;
836}
837
a8634d37
RK
838function normalizeCoords(aCoords) {
839 var zoomFactor = Math.pow(2, aCoords.z);
840 return {x: mod(aCoords.x, zoomFactor),
841 y: mod(aCoords.y, zoomFactor),
842 z: aCoords.z};
23cd2dcc
RK
843}
844
b9707ee0
RK
845function getTileKey(aStyle, aNormalizedCoords) {
846 return aStyle + "::" +
847 aNormalizedCoords.x + "," +
848 aNormalizedCoords.y + "," +
849 aNormalizedCoords.z;
850}
851
23cd2dcc
RK
852// Returns true if the tile is outside the current view.
853function isOutsideWindow(t) {
854 var pos = decodeIndex(t);
23cd2dcc 855
dda55132 856 var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z);
ac6286bd
RK
857 var wid = gMap.width * zoomFactor;
858 var ht = gMap.height * zoomFactor;
23cd2dcc 859
4b1d0915
RK
860 pos.x *= zoomFactor;
861 pos.y *= zoomFactor;
23cd2dcc 862
dda55132
RK
863 var sz = gMap.tileSize * zoomFactor;
864 if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 ||
865 pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2)
23cd2dcc
RK
866 return true;
867 return false;
868}
869
870function encodeIndex(x, y, z) {
a8634d37 871 var norm = normalizeCoords({x: x, y: y, z: z});
23cd2dcc
RK
872 return norm.x + "," + norm.y + "," + norm.z;
873}
874
875function decodeIndex(encodedIdx) {
4b1d0915
RK
876 var ind = encodedIdx.split(",", 3);
877 return {x: ind[0], y: ind[1], z: ind[2]};
23cd2dcc
RK
878}
879
7a076538
RK
880function calcTrackDuration() {
881 // Get the duration of the track in s.
882 var tDuration = 0;
883 if (gTrack.length > 1) {
884 for (var i = 1; i < gTrack.length; i++) {
8f63227b
RK
885 if (!gTrack[i].beginSegment) {
886 tDuration += (gTrack[i].time - gTrack[i-1].time);
887 }
7a076538
RK
888 }
889 }
890 return Math.round(tDuration / 1000); // The timestamps are in ms but we return seconds.
891}
892
893function calcTrackLength() {
894 // Get the length of the track in km.
895 var tLength = 0;
896 if (gTrack.length > 1) {
897 for (var i = 1; i < gTrack.length; i++) {
8f63227b
RK
898 if (!gTrack[i].beginSegment) {
899 tLength += getPointDistance(gTrack[i-1].coords, gTrack[i].coords);
900 }
7a076538
RK
901 }
902 }
903 return tLength;
904}
905
906function getPointDistance(aGPSPoint1, aGPSPoint2) {
907 // Get the distance in km between the two given GPS points.
908 // See http://stackoverflow.com/questions/365826/calculate-distance-between-2-gps-coordinates
909 // Earth is almost exactly a sphere and we calculate small distances on the surface, so we can do spherical great-circle math.
910 // Also see http://en.wikipedia.org/wiki/Great-circle_distance
911 var R = 6371; // km
912 var dLat = deg2rad(aGPSPoint2.latitude - aGPSPoint1.latitude);
913 var dLon = deg2rad(aGPSPoint2.longitude - aGPSPoint1.longitude);
914 var lat1 = deg2rad(aGPSPoint1.latitude);
915 var lat2 = deg2rad(aGPSPoint2.latitude);
916
917 var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
918 Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
919 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
920 return R * c;
921}
922
923function deg2rad(aDegreeValue) {
924 // Convert an angle in degrees to radiants.
925 return aDegreeValue * (Math.PI / 180);
926}
927
23cd2dcc
RK
928var mapEvHandler = {
929 handleEvent: function(aEvent) {
930 var touchEvent = aEvent.type.indexOf('touch') != -1;
931
306ae634
RK
932 if (touchEvent) {
933 aEvent.stopPropagation();
934 }
935
8389557a
RK
936 // Bail out if the event is happening on an input.
937 if (aEvent.target.tagName.toLowerCase() == "input")
938 return;
939
1222624d
RK
940 // Bail out on unwanted map moves, but not zoom or keyboard events.
941 if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
23cd2dcc
RK
942 // Bail out if this is neither a touch nor left-click.
943 if (!touchEvent && aEvent.button != 0)
944 return;
945
946 // Bail out if the started touch can't be found.
4b12da3a 947 if (touchEvent && gDragging &&
aec007a6 948 !aEvent.targetTouches.item(0))
23cd2dcc
RK
949 return;
950 }
951
952 var coordObj = touchEvent ?
aec007a6 953 aEvent.targetTouches.item(0) :
23cd2dcc
RK
954 aEvent;
955
956 switch (aEvent.type) {
957 case "mousedown":
958 case "touchstart":
959 if (touchEvent) {
517c0099
RK
960 if (aEvent.targetTouches.length == 2) {
961 gPinchStartWidth = Math.sqrt(
962 Math.pow(aEvent.targetTouches.item(1).clientX -
963 aEvent.targetTouches.item(0).clientX, 2) +
964 Math.pow(aEvent.targetTouches.item(1).clientY -
965 aEvent.targetTouches.item(0).clientY, 2)
966 );
967 }
aec007a6 968 coordObj = aEvent.targetTouches.item(0);
23cd2dcc 969 }
ac6286bd
RK
970 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
971 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
b395419b 972
23cd2dcc
RK
973 if (touchEvent || aEvent.button === 0) {
974 gDragging = true;
975 }
976 gLastMouseX = x;
977 gLastMouseY = y;
7a549148 978 showUI();
68ca4617 979 gLastMoveAction = performance.now();
23cd2dcc
RK
980 break;
981 case "mousemove":
982 case "touchmove":
517c0099
RK
983 if (touchEvent && aEvent.targetTouches.length == 2) {
984 curPinchStartWidth = Math.sqrt(
985 Math.pow(aEvent.targetTouches.item(1).clientX -
986 aEvent.targetTouches.item(0).clientX, 2) +
987 Math.pow(aEvent.targetTouches.item(1).clientY -
988 aEvent.targetTouches.item(0).clientY, 2)
989 );
003d56f8
RK
990 if (!gPinchStartWidth)
991 gPinchStartWidth = curPinchStartWidth;
d07d7abc 992
517c0099
RK
993 if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
994 gPinchStartWidth / curPinchStartWidth < 0.6) {
dda55132
RK
995 var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
996 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
517c0099
RK
997 // Calculate new center of the map - preserve middle of pinch.
998 // This means that pixel distance between old center and middle
999 // must equal pixel distance of new center and middle.
1000 var x = (aEvent.targetTouches.item(1).clientX +
1001 aEvent.targetTouches.item(0).clientX) / 2 -
ac6286bd 1002 gGLMapCanvas.offsetLeft;
517c0099
RK
1003 var y = (aEvent.targetTouches.item(1).clientY +
1004 aEvent.targetTouches.item(0).clientY) / 2 -
ac6286bd 1005 gGLMapCanvas.offsetTop;
517c0099
RK
1006
1007 // Zoom factor after this action.
dda55132 1008 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
ac6286bd
RK
1009 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
1010 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
517c0099
RK
1011
1012 if (gPinchStartWidth < curPinchStartWidth)
aa45a91b 1013 gMap.zoomIn();
517c0099 1014 else
aa45a91b 1015 gMap.zoomOut();
003d56f8
RK
1016
1017 // Reset pinch start width and start another pinch gesture.
1018 gPinchStartWidth = null;
517c0099
RK
1019 }
1020 }
d07d7abc 1021 // If we are in a pinch, do not drag.
517c0099
RK
1022 break;
1023 }
ac6286bd
RK
1024 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
1025 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
23cd2dcc
RK
1026 if (gDragging === true) {
1027 var dX = x - gLastMouseX;
1028 var dY = y - gLastMouseY;
dda55132
RK
1029 gMap.pos.x -= dX * gMap.zoomFactor;
1030 gMap.pos.y -= dY * gMap.zoomFactor;
0f6678fa 1031 gMap.draw();
7a549148 1032 showUI();
23cd2dcc
RK
1033 }
1034 gLastMouseX = x;
1035 gLastMouseY = y;
68ca4617 1036 gLastMoveAction = performance.now();
23cd2dcc
RK
1037 break;
1038 case "mouseup":
1039 case "touchend":
d07d7abc 1040 gPinchStartWidth = null;
23cd2dcc 1041 gDragging = false;
7a549148 1042 showUI();
23cd2dcc
RK
1043 break;
1044 case "mouseout":
1045 case "touchcancel":
1046 case "touchleave":
1047 //gDragging = false;
1048 break;
5fb31b29
RK
1049 case "wheel":
1050 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
1051 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
1052
1053 // Only accept (non-null) deltaY values
1054 if (!aEvent.deltaY)
1055 break;
23cd2dcc 1056
55c4a0b7
RK
1057 // Debug output: "coordinates" of the point the mouse was over.
1058 /*
ac6286bd
RK
1059 var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor,
1060 y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor};
55c4a0b7
RK
1061 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
1062 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
915d4271
RK
1063 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
1064 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
1065 pt2Coord.x + "/" + pt2Coord.y);
55c4a0b7 1066 */
4b1d0915 1067
dda55132
RK
1068 var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1);
1069 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
4b1d0915
RK
1070 // Calculate new center of the map - same point stays under the mouse.
1071 // This means that the pixel distance between the old center and point
1072 // must equal the pixel distance of the new center and that point.
ac6286bd
RK
1073 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
1074 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
4b1d0915
RK
1075
1076 // Zoom factor after this action.
dda55132 1077 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
ac6286bd
RK
1078 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
1079 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
4b1d0915 1080
5fb31b29 1081 if (aEvent.deltaY < 0)
aa45a91b 1082 gMap.zoomIn();
5fb31b29 1083 else
aa45a91b 1084 gMap.zoomOut();
4b1d0915 1085 }
23cd2dcc 1086 break;
1222624d
RK
1087 case "keydown":
1088 // Allow keyboard control to move and zoom the map.
1089 // Should use aEvent.key instead of aEvent.which but needs bug 680830.
1090 // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
1091 var dX = 0;
1092 var dY = 0;
1093 switch (aEvent.which) {
1094 case 39: // right
dda55132 1095 dX = -gMap.tileSize / 2;
1222624d
RK
1096 break;
1097 case 37: // left
dda55132 1098 dX = gMap.tileSize / 2;
1222624d
RK
1099 break;
1100 case 38: // up
dda55132 1101 dY = gMap.tileSize / 2;
1222624d
RK
1102 break;
1103 case 40: // down
dda55132 1104 dY = -gMap.tileSize / 2;
1222624d
RK
1105 break;
1106 case 87: // w
1107 case 107: // + (numpad)
1108 case 171: // + (normal key)
aa45a91b 1109 gMap.zoomIn();
1222624d
RK
1110 break;
1111 case 83: // s
1112 case 109: // - (numpad)
1113 case 173: // - (normal key)
aa45a91b 1114 gMap.zoomOut();
1222624d
RK
1115 break;
1116 case 48: // 0
1117 case 49: // 1
1118 case 50: // 2
1119 case 51: // 3
1120 case 52: // 4
1121 case 53: // 5
1122 case 54: // 6
1123 case 55: // 7
1124 case 56: // 8
aa45a91b 1125 gMap.zoomTo(aEvent.which - 38);
1222624d
RK
1126 break;
1127 case 57: // 9
aa45a91b 1128 gMap.zoomTo(9);
1222624d
RK
1129 break;
1130 case 96: // 0 (numpad)
1131 case 97: // 1 (numpad)
1132 case 98: // 2 (numpad)
1133 case 99: // 3 (numpad)
1134 case 100: // 4 (numpad)
1135 case 101: // 5 (numpad)
1136 case 102: // 6 (numpad)
1137 case 103: // 7 (numpad)
1138 case 104: // 8 (numpad)
aa45a91b 1139 gMap.zoomTo(aEvent.which - 86);
1222624d
RK
1140 break;
1141 case 105: // 9 (numpad)
aa45a91b 1142 gMap.zoomTo(9);
1222624d
RK
1143 break;
1144 default: // not supported
1145 console.log("key not supported: " + aEvent.which);
1146 break;
1147 }
1148
1149 // Move if needed.
1150 if (dX || dY) {
dda55132
RK
1151 gMap.pos.x -= dX * gMap.zoomFactor;
1152 gMap.pos.y -= dY * gMap.zoomFactor;
0f6678fa 1153 gMap.draw();
68ca4617 1154 gLastMoveAction = performance.now();
1222624d
RK
1155 }
1156 break;
23cd2dcc
RK
1157 }
1158 }
1159};
55c4a0b7 1160
5dd2ab70
RK
1161function visibilityEvHandler() {
1162 // Immediately draw if we just got visible.
1163 if (document.hidden != true) {
1164 gMap.draw();
1165 }
1166 // No need to handle the event where we become invisible as we care only draw
1167 // when we are visible anyhow.
1168}
1169
993fd081 1170var geofake = {
55c4a0b7 1171 tracking: false,
4b12da3a 1172 lastPos: {x: undefined, y: undefined},
55c4a0b7
RK
1173 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
1174 this.tracking = true;
1175 var watchCall = function() {
4b12da3a
RK
1176 // calc new position in lat/lon degrees
1177 // 90° on Earth surface are ~10,000 km at the equator,
1178 // so try moving at most 10m at a time
1179 if (geofake.lastPos.x)
1180 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
1181 else
1182 geofake.lastPos.x = 48.208174
1183 if (geofake.lastPos.y)
1184 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
1185 else
1186 geofake.lastPos.y = 16.373819
55c4a0b7 1187 aSuccessCallback({timestamp: Date.now(),
4b12da3a
RK
1188 coords: {latitude: geofake.lastPos.x,
1189 longitude: geofake.lastPos.y,
55c4a0b7
RK
1190 accuracy: 20}});
1191 if (geofake.tracking)
1192 setTimeout(watchCall, 1000);
1193 };
1194 setTimeout(watchCall, 1000);
1195 return "foo";
1196 },
1197 clearWatch: function(aID) {
1198 this.tracking = false;
1199 }
1200}
1201
3610c22d
RK
1202function setCentering(aCheckbox) {
1203 if (gMapPrefsLoaded && mainDB)
1204 gPrefs.set("center_map", aCheckbox.checked);
1205 gCenterPosition = aCheckbox.checked;
1206}
1207
1208function setTracking(aCheckbox) {
1209 if (gMapPrefsLoaded && mainDB)
1210 gPrefs.set("tracking_enabled", aCheckbox.checked);
1211 if (aCheckbox.checked)
1212 startTracking();
1213 else
1214 endTracking();
1215}
1216
55c4a0b7 1217function startTracking() {
31f0fe16 1218 if (gGeolocation) {
68afcd96
RK
1219 gActionLabel.textContent = "Establishing Position";
1220 gAction.style.display = "block";
d361104b
RK
1221 if (navigator.requestWakeLock) {
1222 gGPSWakeLock = navigator.requestWakeLock("gps");
1223 }
4b12da3a 1224 gGeoWatchID = gGeolocation.watchPosition(
55c4a0b7 1225 function(position) {
68afcd96
RK
1226 if (gActionLabel.textContent) {
1227 gActionLabel.textContent = "";
1228 gAction.style.display = "none";
1229 }
55c4a0b7 1230 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
993fd081 1231 var tPoint = {time: position.timestamp,
31f0fe16
RK
1232 coords: {latitude: position.coords.latitude,
1233 longitude: position.coords.longitude,
1234 altitude: position.coords.altitude,
1235 accuracy: position.coords.accuracy,
1236 altitudeAccuracy: position.coords.altitudeAccuracy,
1237 heading: position.coords.heading,
1238 speed: position.coords.speed},
993fd081 1239 beginSegment: !gLastTrackPoint};
b054bd48
RK
1240 // Only add point to track is accuracy is good enough.
1241 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
1242 gLastTrackPoint = tPoint;
1243 gTrack.push(tPoint);
1244 try { gTrackStore.push(tPoint); } catch(e) {}
1245 var redrawn = false;
68ca4617 1246 if (gCenterPosition && (!gLastMoveAction || performance.now() > gLastMoveAction + gCenterDelayAfterMove)) {
b054bd48
RK
1247 var posCoord = gps2xy(position.coords.latitude,
1248 position.coords.longitude);
ac6286bd
RK
1249 if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 ||
1250 Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) {
dda55132
RK
1251 gMap.pos.x = posCoord.x;
1252 gMap.pos.y = posCoord.y;
ac6286bd 1253 gMap.draw(); // This draws the current point as well.
b054bd48
RK
1254 redrawn = true;
1255 }
99631a75 1256 }
b054bd48 1257 if (!redrawn)
aa45a91b 1258 gTrackLayer.undrawCurrentLocation();
b4df67c9 1259 gTrackLayer.drawTrackPoint(gTrack.length-1);
05c21757 1260 }
aa45a91b 1261 gTrackLayer.drawCurrentLocation(tPoint);
55c4a0b7
RK
1262 },
1263 function(error) {
1264 // Ignore erros for the moment, but this is good for debugging.
1265 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
915d4271
RK
1266 if (gDebug)
1267 console.log(error.message);
55c4a0b7
RK
1268 },
1269 {enableHighAccuracy: true}
1270 );
1271 }
1272}
1273
1274function endTracking() {
68afcd96
RK
1275 if (gActionLabel.textContent) {
1276 gActionLabel.textContent = "";
1277 gAction.style.display = "none";
1278 }
d361104b
RK
1279 if (navigator.requestWakeLock && gGPSWakeLock) {
1280 console.log("releasing WakeLock");
1281 gGPSWakeLock.unlock();
1282 }
55c4a0b7 1283 if (gGeoWatchID) {
4b12da3a 1284 gGeolocation.clearWatch(gGeoWatchID);
55c4a0b7
RK
1285 }
1286}
993fd081
RK
1287
1288function clearTrack() {
1289 gTrack = [];
1290 gTrackStore.clear();
aa45a91b 1291 gTrackLayer.drawTrack();
993fd081 1292}
a8634d37 1293
3b76e071
RK
1294function loadTrackFromBackend(aTrackId, aFeedbackElement, aSuccessCallback) {
1295 if (aFeedbackElement) {
1296 aFeedbackElement.textContent = "Loading...";
1297 // If someone loads without pointing to UI (e.g. for debugging), we just overwrite whatever's loaded.
1298 if (calcTrackLength() > 1) {
1299 aFeedbackElement.textContent = "Track >1km loaded, please save/clear.";
1300 aFeedbackElement.classList.add("error");
1301 return;
1302 }
1303 }
57ee3e06
RK
1304 fetchBackend("track_json?id=" + encodeURIComponent(aTrackId), "GET", null,
1305 function(aResult, aStatusCode) {
3b76e071 1306 if (aStatusCode >= 400) {
57ee3e06 1307 console.log("loading track failed: " + aStatusCode + ", result: " + aResult.message);
3b76e071
RK
1308 if (aFeedbackElement) {
1309 aFeedbackElement.textContent = "Error: " + aResult;
1310 aFeedbackElement.classList.add("error");
1311 }
57ee3e06 1312 }
3b76e071
RK
1313 else if (aResult) {
1314 loadTrack(aResult);
1315 if (aSuccessCallback) {
1316 aSuccessCallback();
1317 }
1318 }
1319 else { // If no result is returned, we assume a general error.
1320 console.log("Error getting track with ID " + aTrackId + " from backend.");
1321 if (aFeedbackElement) {
1322 aFeedbackElement.textContent = "Error fetching track from backend.";
1323 aFeedbackElement.classList.add("error");
57ee3e06 1324 }
57ee3e06
RK
1325 }
1326 }
1327 );
1328}
1329
3b76e071
RK
1330function loadTrack(aTrack) {
1331 console.log("Loading track with " + aTrack.length + " points.");
1332 gTrack = aTrack;
1333 gTrackStore.clear(function(aSuccess, aEvent) {
1334 for (var i = 0; i < gTrack.length; i++) {
1335 try { gTrackStore.push(gTrack[i]); } catch(e) {}
1336 }
1337 });
aa45a91b 1338 gTrackLayer.drawTrack(); // Draws from gTrack, so not problem that gTrackStore is filled async.
3b76e071
RK
1339}
1340
a8634d37
RK
1341var gTileService = {
1342 objStore: "tilecache",
1343
5d67397a 1344 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
3431f496 1345
a8634d37
RK
1346 get: function(aStyle, aCoords, aCallback) {
1347 var norm = normalizeCoords(aCoords);
b9707ee0 1348 var dbkey = getTileKey(aStyle, norm);
a8634d37
RK
1349 this.getDBCache(dbkey, function(aResult, aEvent) {
1350 if (aResult) {
1351 // We did get a cached object.
e8525b46 1352 aCallback(aResult.image, aStyle, aCoords, dbkey);
3431f496 1353 // Look at the timestamp and return if it's not too old.
5d67397a 1354 if (aResult.timestamp + gTileService.ageLimit > Date.now())
3431f496
RK
1355 return;
1356 // Reload cached tile otherwise.
5d67397a
RK
1357 var oldDate = new Date(aResult.timestamp);
1358 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
a8634d37 1359 }
3431f496
RK
1360 // Retrieve image from the web and store it in the cache.
1361 var XHR = new XMLHttpRequest();
1362 XHR.open("GET",
1363 gMapStyles[aStyle].url
1364 .replace("{x}", norm.x)
1365 .replace("{y}", norm.y)
1366 .replace("{z}", norm.z)
5ed2937e 1367 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 3)))
ca77d52d 1368 .replace("[a-d]", String.fromCharCode(97 + Math.floor(Math.random() * 4)))
5ed2937e 1369 .replace("[1-4]", 1 + Math.floor(Math.random() * 4)),
3431f496
RK
1370 true);
1371 XHR.responseType = "blob";
1372 XHR.addEventListener("load", function () {
1373 if (XHR.status === 200) {
1374 var blob = XHR.response;
e8525b46 1375 aCallback(blob, aStyle, aCoords, dbkey);
6d7cdcf6 1376 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
3431f496
RK
1377 }
1378 }, false);
1379 XHR.send();
a8634d37
RK
1380 });
1381 },
1382
1383 getDBCache: function(aKey, aCallback) {
1384 if (!mainDB)
1385 return;
1386 var transaction = mainDB.transaction([this.objStore]);
1387 var request = transaction.objectStore(this.objStore).get(aKey);
1388 request.onsuccess = function(event) {
1389 aCallback(request.result, event);
1390 };
1391 request.onerror = function(event) {
1392 // Errors can be handled here.
1393 aCallback(undefined, event);
1394 };
1395 },
1396
1397 setDBCache: function(aKey, aValue, aCallback) {
1398 if (!mainDB)
1399 return;
1400 var success = false;
1401 var transaction = mainDB.transaction([this.objStore], "readwrite");
1402 var objStore = transaction.objectStore(this.objStore);
1403 var request = objStore.put(aValue, aKey);
1404 request.onsuccess = function(event) {
1405 success = true;
1406 if (aCallback)
1407 aCallback(success, event);
1408 };
1409 request.onerror = function(event) {
1410 // Errors can be handled here.
1411 if (aCallback)
1412 aCallback(success, event);
1413 };
1414 },
1415
1416 unsetDBCache: function(aKey, aCallback) {
1417 if (!mainDB)
1418 return;
1419 var success = false;
1420 var transaction = mainDB.transaction([this.objStore], "readwrite");
1421 var request = transaction.objectStore(this.objStore).delete(aKey);
1422 request.onsuccess = function(event) {
1423 success = true;
1424 if (aCallback)
1425 aCallback(success, event);
1426 };
1427 request.onerror = function(event) {
1428 // Errors can be handled here.
1429 if (aCallback)
1430 aCallback(success, event);
1431 }
3431f496
RK
1432 },
1433
1434 clearDB: function(aCallback) {
1435 if (!mainDB)
1436 return;
1437 var success = false;
1438 var transaction = mainDB.transaction([this.objStore], "readwrite");
1439 var request = transaction.objectStore(this.objStore).clear();
1440 request.onsuccess = function(event) {
1441 success = true;
e4840ddc 1442 console.log("Cache cleared.");
3431f496
RK
1443 if (aCallback)
1444 aCallback(success, event);
1445 };
1446 request.onerror = function(event) {
1447 // Errors can be handled here.
e4840ddc 1448 console.log("Error clearing cache!");
3431f496
RK
1449 if (aCallback)
1450 aCallback(success, event);
1451 }
a8634d37
RK
1452 }
1453};