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