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