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