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