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