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