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