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