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