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