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