old pixels optimizations are not needed any more, determine if we even go to tile...
[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   osm_mapnik:
18     {name: "OpenStreetMap (Mapnik)",
19      url: "http://tile.openstreetmap.org/{z}/{x}/{y}.png",
20      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>'},
21   osm_cyclemap:
22     {name: "Cycle Map (OSM)",
23      url: "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
24      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>'},
25   osm_transmap:
26     {name: "Transport Map (OSM)",
27      url: "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png",
28      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>'},
29   mapquest_open:
30     {name: "MapQuest OSM",
31      url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png",
32      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>.'},
33   mapquest_aerial:
34     {name: "MapQuest Open Aerial",
35      url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg",
36      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.'},
37   opengeoserver_arial:
38     {name: "OpenGeoServer Aerial",
39      url: "http://services.opengeoserver.org/tiles/1.0.0/globe.aerial_EPSG3857/{z}/{x}/{y}.png?origin=nw",
40      copyright: 'Tiles by <a href="http://www.opengeoserver.org/">OpenGeoServer.org</a>, <a href="https://creativecommons.org/licenses/by/3.0/at/">CC-BY 3.0 AT</a>.'},
41   google_map:
42     {name: "Google Maps",
43      url: " http://mt1.google.com/vt/x={x}&y={y}&z={z}",
44      copyright: 'Map data and imagery &copy; <a href="http://maps.google.com/">Google</a>'},
45 };
46
47 var gLastMouseX = 0;
48 var gLastMouseY = 0;
49
50 var gLoadingTile;
51
52 var gMapPrefsLoaded = false;
53
54 var gDragging = false;
55 var gDragTouchID, gPinchStartWidth;
56
57 var gGeoWatchID;
58 var gTrack = [];
59 var gLastTrackPoint, gLastDrawnPoint;
60 var gCenterPosition = true;
61
62 var gCurPosMapCache;
63
64 function initMap() {
65   gGeolocation = navigator.geolocation;
66   // Set up canvas context.
67   gGLMapCanvas = document.getElementById("map");
68   try {
69     // Try to grab the standard context. If it fails, fallback to experimental.
70     // We also try to tell it we do not need a depth buffer.
71     gMap.gl = gGLMapCanvas.getContext("webgl", {depth: false}) ||
72               gGLMapCanvas.getContext("experimental-webgl", {depth: false});
73   }
74   catch(e) {}
75   // If we don't have a GL context, give up now
76   if (!gMap.gl) {
77     showGLWarningDialog();
78     gMap.gl = null;
79   }
80   gTrackCanvas = document.getElementById("track");
81   gTrackContext = gTrackCanvas.getContext("2d");
82   if (!gMap.activeMap)
83     gMap.activeMap = "osm_mapnik";
84
85   //gDebug = true;
86   if (gDebug) {
87     gGeolocation = geofake;
88     var hiddenList = document.getElementsByClassName("debugHide");
89     // last to first - list of elements with that class is changing!
90     for (var i = hiddenList.length - 1; i >= 0; i--) {
91       hiddenList[i].classList.remove("debugHide");
92     }
93   }
94
95   gAction.addEventListener("prefload-done", gMap.initGL, false);
96
97   console.log("map vars set, loading prefs...");
98   loadPrefs();
99 }
100
101 function loadPrefs(aEvent) {
102   if (aEvent && aEvent.type == "prefs-step") {
103     console.log("wait: " + gWaitCounter);
104     if (gWaitCounter == 0) {
105       gAction.removeEventListener(aEvent.type, loadPrefs, false);
106       gMapPrefsLoaded = true;
107       console.log("prefs loaded.");
108
109       gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
110       gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
111       gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
112       gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
113
114       gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
115       gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
116       gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
117       gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
118       gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
119
120       gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
121
122       document.getElementById("body").addEventListener("keydown", mapEvHandler, false);
123
124       document.getElementById("copyright").innerHTML =
125           gMapStyles[gMap.activeMap].copyright;
126
127       gLoadingTile = new Image();
128       gLoadingTile.src = "style/loading.png";
129       gLoadingTile.onload = function() {
130         var throwEv = new CustomEvent("prefload-done");
131         gAction.dispatchEvent(throwEv);
132       };
133     }
134   }
135   else {
136     if (aEvent)
137       gAction.removeEventListener(aEvent.type, loadPrefs, false);
138     gAction.addEventListener("prefs-step", loadPrefs, false);
139     gWaitCounter++;
140     gPrefs.get("position", function(aValue) {
141       if (aValue && aValue.x && aValue.y && aValue.z) {
142         gMap.pos = aValue;
143       }
144       gWaitCounter--;
145       var throwEv = new CustomEvent("prefs-step");
146       gAction.dispatchEvent(throwEv);
147     });
148     gWaitCounter++;
149     gPrefs.get("center_map", function(aValue) {
150       if (aValue === undefined)
151         document.getElementById("centerCheckbox").checked = true;
152       else
153         document.getElementById("centerCheckbox").checked = aValue;
154       setCentering(document.getElementById("centerCheckbox"));
155       gWaitCounter--;
156       var throwEv = new CustomEvent("prefs-step");
157       gAction.dispatchEvent(throwEv);
158     });
159     gWaitCounter++;
160     gPrefs.get("tracking_enabled", function(aValue) {
161       if (aValue === undefined)
162         document.getElementById("trackCheckbox").checked = true;
163       else
164         document.getElementById("trackCheckbox").checked = aValue;
165       gWaitCounter--;
166       var throwEv = new CustomEvent("prefs-step");
167       gAction.dispatchEvent(throwEv);
168     });
169     gWaitCounter++;
170     var trackLoadStarted = false;
171     var redrawBase = 100;
172     gTrackStore.getListStepped(function(aTPoint) {
173       if (aTPoint) {
174         // Add in front and return new length.
175         var tracklen = gTrack.unshift(aTPoint);
176         // Redraw track periodically, larger distance the longer it gets.
177         // Initial paint will do initial track drawing.
178         if (tracklen % redrawBase == 0) {
179           drawTrack();
180           redrawBase = tracklen;
181         }
182       }
183       else {
184         // Last point received.
185         drawTrack();
186       }
187       if (!trackLoadStarted) {
188         // We have the most recent point, if present, rest will load async.
189         trackLoadStarted = true;
190         gWaitCounter--;
191         var throwEv = new CustomEvent("prefs-step");
192         gAction.dispatchEvent(throwEv);
193       }
194     });
195   }
196 }
197
198 var gMap = {
199   gl: null,
200   glShaderProgram: null,
201   glVertexPositionAttr: null,
202   glTextureCoordAttr: null,
203   glResolutionAttr: null,
204   glMapTexture: null,
205   glTextures: {},
206   glTextureKeys: {},
207
208   activeMap: "osm_mapnik",
209   tileSize: 256,
210   maxZoom: 18, // The minimum is 0.
211   zoomFactor: null,
212   pos: {
213     x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
214     y: 23670000.0, // The range is 0-67108864 (2^gMap.maxZoom * gMap.tileSize)
215     z: 5           // This could be fractional if supported being between zoom levels.
216   },
217
218   get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; },
219   get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; },
220
221   getVertShaderSource: function() {
222     return 'attribute vec2 aVertexPosition;\n' +
223     'attribute vec2 aTextureCoord;\n\n' +
224     'uniform vec2 uResolution;\n\n' +
225     'varying highp vec2 vTextureCoord;\n\n' +
226     'void main(void) {\n' +
227     // convert the rectangle from pixels to -1.0 to +1.0 (clipspace) 0.0 to 1.0
228     '  vec2 clipSpace = aVertexPosition * 2.0 / uResolution - 1.0;\n' +
229     '  gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' +
230     '  vTextureCoord = aTextureCoord;\n' +
231     '}'; },
232   getFragShaderSource:function() {
233     return 'varying highp vec2 vTextureCoord;\n\n' +
234     'uniform sampler2D uImage;\n\n' +
235     'void main(void) {\n' +
236     '  gl_FragColor = texture2D(uImage, vTextureCoord);\n' +
237     '}'; },
238
239   initGL: function() {
240     // When called from the event listener, the "this" reference doesn't work, so use the object name.
241     if (gMap.gl) {
242       gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
243       gMap.gl.clearColor(0.0, 0.0, 0.0, 0.5);                          // Set clear color to black, fully opaque.
244       gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT|gMap.gl.DEPTH_BUFFER_BIT);  // Clear the color.
245
246       // Create and initialize the shaders.
247       var vertShader = gMap.gl.createShader(gMap.gl.VERTEX_SHADER);
248       var fragShader = gMap.gl.createShader(gMap.gl.FRAGMENT_SHADER);
249       gMap.gl.shaderSource(vertShader, gMap.getVertShaderSource());
250       // Compile the shader program.
251       gMap.gl.compileShader(vertShader);
252       // See if it compiled successfully.
253       if (!gMap.gl.getShaderParameter(vertShader, gMap.gl.COMPILE_STATUS)) {
254         console.log("An error occurred compiling the vertex shader: " + gMap.gl.getShaderInfoLog(vertShader));
255         return null;
256       }
257       gMap.gl.shaderSource(fragShader, gMap.getFragShaderSource());
258       // Compile the shader program.
259       gMap.gl.compileShader(fragShader);
260       // See if it compiled successfully.
261       if (!gMap.gl.getShaderParameter(fragShader, gMap.gl.COMPILE_STATUS)) {
262         console.log("An error occurred compiling the fragment shader: " + gMap.gl.getShaderInfoLog(fragShader));
263         return null;
264       }
265
266       gMap.glShaderProgram = gMap.gl.createProgram();
267       gMap.gl.attachShader(gMap.glShaderProgram, vertShader);
268       gMap.gl.attachShader(gMap.glShaderProgram, fragShader);
269       gMap.gl.linkProgram(gMap.glShaderProgram);
270       // If creating the shader program failed, alert
271       if (!gMap.gl.getProgramParameter(gMap.glShaderProgram, gMap.gl.LINK_STATUS)) {
272         alert("Unable to initialize the shader program.");
273       }
274       gMap.gl.useProgram(gMap.glShaderProgram);
275       // Get locations of the attributes.
276       gMap.glVertexPositionAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aVertexPosition");
277       gMap.glTextureCoordAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aTextureCoord");
278       gMap.glResolutionAttr = gMap.gl.getUniformLocation(gMap.glShaderProgram, "uResolution");
279
280       var tileVerticesBuffer = gMap.gl.createBuffer();
281       gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, tileVerticesBuffer);
282       // The vertices are the coordinates of the corner points of the square.
283       var vertices = [
284         0.0,  0.0,
285         1.0,  0.0,
286         0.0,  1.0,
287         0.0,  1.0,
288         1.0,  0.0,
289         1.0,  1.0,
290       ];
291       gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(vertices), gMap.gl.STATIC_DRAW);
292       gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr);
293       gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0);
294
295       gMap.loadImageToTexture(gLoadingTile, 0, "loading::0,0,0");
296
297       gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
298
299       // Create a buffer for the position of the rectangle corners.
300       var mapVerticesTextureCoordBuffer = gMap.gl.createBuffer();
301       gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer);
302       gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr);
303       gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0);
304     }
305
306     var throwEv = new CustomEvent("mapinit-done");
307     gAction.dispatchEvent(throwEv);
308   },
309
310   draw: function() {
311     gMap.assembleGL();
312     drawTrack();
313   },
314
315   assembleGL: function() {
316     if (!gMap.gl) { return; }
317
318     document.getElementById("zoomLevel").textContent = gMap.pos.z;
319     gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
320     var wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor; // Width in level 18 pixels.
321     var ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor; // Height in level 18 pixels.
322     var size = gMap.tileSize * gMap.zoomFactor; // Tile size in level 18 pixels.
323
324     var xMin = gMap.pos.x - wid / 2; // Corners of the window in level 18 pixels.
325     var yMin = gMap.pos.y - ht / 2;
326     var xMax = gMap.pos.x + wid / 2;
327     var yMax = gMap.pos.y + ht / 2;
328
329     if (gMapPrefsLoaded && mainDB)
330       gPrefs.set("position", gMap.pos);
331
332     // Go through all the tiles in the map, find out if to draw them and do so.
333     for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
334       for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
335         // Only go to loading step if we haven't loaded the texture.
336         var coords = {x: x, y: y, z: gMap.pos.z};
337         var tileKey = getTileKey(gMap.activeMap, normalizeCoords(coords));
338         if (!gMap.glTextureKeys[tileKey]) {
339           // Initiate loading/drawing of the actual tile.
340           gTileService.get(gMap.activeMap, coords,
341                            function(aImage, aStyle, aCoords, aTileKey) {
342             // Only actually load if this still applies for the current view.
343             if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) {
344               var URL = window.URL;
345               var imgURL = URL.createObjectURL(aImage);
346               var imgObj = new Image();
347               imgObj.onload = function() {
348                 var txNr = 1;
349                 while (gMap.glTextures["tx" + txNr]) { txNr++; }
350                 gMap.loadImageToTexture(imgObj, txNr, aTileKey);
351                 requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
352                 URL.revokeObjectURL(imgURL);
353               }
354               imgObj.src = imgURL;
355             }
356           });
357         }
358       }
359     }
360     requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
361   },
362
363   drawGL: function() {
364     var wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor; // Width in level 18 pixels.
365     var ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor; // Height in level 18 pixels.
366     var size = gMap.tileSize * gMap.zoomFactor; // Tile size in level 18 pixels.
367
368     var xMin = gMap.pos.x - wid / 2; // Corners of the window in level 18 pixels.
369     var yMin = gMap.pos.y - ht / 2;
370     var xMax = gMap.pos.x + wid / 2;
371     var yMax = gMap.pos.y + ht / 2;
372
373     var txIndexList = [];
374     // Go through all the tiles in the map, find out if to draw them and do so.
375     for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
376       for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
377         // Round here is **CRUCIAL** otherwise the images are filtered
378         // and the performance sucks (more than expected).
379         var xoff = Math.round((x * size - xMin) / gMap.zoomFactor);
380         var yoff = Math.round((y * size - yMin) / gMap.zoomFactor);
381         // Draw the tile, first find out the index of the texture to use.
382         var norm = normalizeCoords({x: x, y: y, z: gMap.pos.z});
383         var tileKey = getTileKey(gMap.activeMap, norm);
384         var txIndex = gMap.glTextureKeys[tileKey];
385         if (!txIndex) { txIndex = 0; }
386         txIndexList.push(txIndex);
387         gMap.drawTileGL(xoff, yoff, txIndex);
388       }
389     }
390     console.log("Used Indexes: " + txIndexList.join(","));
391   },
392
393   resizeAndDraw: function() {
394     var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
395     var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
396     if (gGLMapCanvas && gTrackCanvas) {
397       gGLMapCanvas.width = viewportWidth;
398       gGLMapCanvas.height = viewportHeight;
399       gTrackCanvas.width = viewportWidth;
400       gTrackCanvas.height = viewportHeight;
401       if (gMap.gl) {
402         // Size viewport to canvas size.
403         gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
404         // Clear the color.
405         gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT);
406         // Make sure the vertex shader get the right resolution.
407         gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
408       }
409       gMap.draw();
410       showUI();
411     }
412   },
413
414   drawTileGL: function(aLeft, aRight, aTextureIndex) {
415     gMap.gl.activeTexture(gMap.gl.TEXTURE0);
416     gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures["tx" + aTextureIndex]);
417     // Set uImage to refer to TEXTURE0
418     gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0);
419     var x_start = aLeft;
420     var i_width = gMap.tileSize;
421     var y_start = aRight;
422     var i_height = gMap.tileSize;
423     var textureCoordinates = [
424       x_start, y_start,
425       x_start + i_width, y_start,
426       x_start, y_start + i_height,
427       x_start, y_start + i_height,
428       x_start + i_width, y_start,
429       x_start + i_width, y_start + i_height,
430     ];
431     gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW);
432
433     // There are 6 indices in textureCoordinates.
434     gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
435   },
436
437   loadImageToTexture: function(aImage, aTextureIndex, aTileKey) {
438     // TODO: Get rid of old textures.
439     gMap.glTextureKeys[aTileKey] = aTextureIndex;
440     // Create and bind texture.
441     gMap.glTextures["tx" + aTextureIndex] = gMap.gl.createTexture();
442     gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures["tx" + aTextureIndex]);
443     // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two).
444     gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST);
445     gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST);
446     // Upload the image into the texture.
447     gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage);
448   },
449 }
450
451 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
452 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
453
454 function zoomIn() {
455   if (gMap.pos.z < gMap.maxZoom) {
456     gMap.pos.z++;
457     gMap.draw();
458   }
459 }
460
461 function zoomOut() {
462   if (gMap.pos.z > 0) {
463     gMap.pos.z--;
464     gMap.draw();
465   }
466 }
467
468 function zoomTo(aTargetLevel) {
469   aTargetLevel = parseInt(aTargetLevel);
470   if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) {
471     gMap.pos.z = aTargetLevel;
472     gMap.draw();
473   }
474 }
475
476 function gps2xy(aLatitude, aLongitude) {
477   var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
478   var convLat = aLatitude * Math.PI / 180;
479   var rawY = (1 - Math.log(Math.tan(convLat) +
480                            1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
481   var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
482   return {x: Math.round(rawX),
483           y: Math.round(rawY)};
484 }
485
486 function xy2gps(aX, aY) {
487   var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
488   var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
489   return {latitude: 180 / Math.PI *
490                     Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
491           longitude: aX / maxZoomFactor * 360 - 180};
492 }
493
494 function setMapStyle() {
495   var mapSel = document.getElementById("mapSelector");
496   if (mapSel.selectedIndex >= 0 && gMap.activeMap != mapSel.value) {
497     gMap.activeMap = mapSel.value;
498     document.getElementById("copyright").innerHTML =
499         gMapStyles[gMap.activeMap].copyright;
500     showUI();
501     gMap.draw();
502   }
503 }
504
505 // A sane mod function that works for negative numbers.
506 // Returns a % b.
507 function mod(a, b) {
508   return ((a % b) + b) % b;
509 }
510
511 function normalizeCoords(aCoords) {
512   var zoomFactor = Math.pow(2, aCoords.z);
513   return {x: mod(aCoords.x, zoomFactor),
514           y: mod(aCoords.y, zoomFactor),
515           z: aCoords.z};
516 }
517
518 function getTileKey(aStyle, aNormalizedCoords) {
519   return aStyle + "::" +
520          aNormalizedCoords.x + "," +
521          aNormalizedCoords.y + "," +
522          aNormalizedCoords.z;
523 }
524
525 // Returns true if the tile is outside the current view.
526 function isOutsideWindow(t) {
527   var pos = decodeIndex(t);
528
529   var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z);
530   var wid = gMap.width * zoomFactor;
531   var ht = gMap.height * zoomFactor;
532
533   pos.x *= zoomFactor;
534   pos.y *= zoomFactor;
535
536   var sz = gMap.tileSize * zoomFactor;
537   if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 ||
538       pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2)
539     return true;
540   return false;
541 }
542
543 function encodeIndex(x, y, z) {
544   var norm = normalizeCoords({x: x, y: y, z: z});
545   return norm.x + "," + norm.y + "," + norm.z;
546 }
547
548 function decodeIndex(encodedIdx) {
549   var ind = encodedIdx.split(",", 3);
550   return {x: ind[0], y: ind[1], z: ind[2]};
551 }
552
553 function drawTrack() {
554   gLastDrawnPoint = null;
555   gCurPosMapCache = undefined;
556   gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
557   if (gTrack.length) {
558     for (var i = 0; i < gTrack.length; i++) {
559       drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
560                      (i + 1 >= gTrack.length));
561     }
562   }
563 }
564
565 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
566   var trackpoint = gps2xy(aLatitude, aLongitude);
567   // lastPoint is for optimizing (not actually executing the draw until the last)
568   trackpoint.optimized = (lastPoint === false);
569   var mappos = {x: Math.round((trackpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
570                 y: Math.round((trackpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
571
572   if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
573     gTrackContext.strokeStyle = gTrackColor;
574     gTrackContext.fillStyle = gTrackContext.strokeStyle;
575     gTrackContext.lineWidth = gTrackWidth;
576     gTrackContext.lineCap = "round";
577     gTrackContext.lineJoin = "round";
578   }
579   if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
580     // This breaks optimiziation, so make sure to close path and reset optimization.
581     if (gLastDrawnPoint && gLastDrawnPoint.optimized)
582       gTrackContext.stroke();
583     gTrackContext.beginPath();
584     trackpoint.optimized = false;
585     gTrackContext.arc(mappos.x, mappos.y,
586                       gTrackContext.lineWidth, 0, Math.PI * 2, false);
587     gTrackContext.fill();
588   }
589   else {
590     if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
591       gTrackContext.beginPath();
592       gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
593                            Math.round((gLastDrawnPoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2));
594     }
595     gTrackContext.lineTo(mappos.x, mappos.y);
596     if (!trackpoint.optimized)
597       gTrackContext.stroke();
598   }
599   gLastDrawnPoint = trackpoint;
600 }
601
602 function drawCurrentLocation(trackPoint) {
603   var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
604   var circleRadius = Math.round(gCurLocSize / 2);
605   var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
606                 y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
607
608   undrawCurrentLocation();
609
610   // Cache overdrawn area.
611   gCurPosMapCache =
612       {point: locpoint,
613        radius: circleRadius,
614        data: gTrackContext.getImageData(mappos.x - circleRadius,
615                                         mappos.y - circleRadius,
616                                         circleRadius * 2, circleRadius * 2)};
617
618   gTrackContext.strokeStyle = gCurLocColor;
619   gTrackContext.fillStyle = gTrackContext.strokeStyle;
620   gTrackContext.beginPath();
621   gTrackContext.arc(mappos.x, mappos.y,
622                     circleRadius, 0, Math.PI * 2, false);
623   gTrackContext.fill();
624 }
625
626 function undrawCurrentLocation() {
627   if (gCurPosMapCache) {
628     var oldpoint = gCurPosMapCache.point;
629     var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
630                  y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
631     gTrackContext.putImageData(gCurPosMapCache.data,
632                                oldmp.x - gCurPosMapCache.radius,
633                                oldmp.y - gCurPosMapCache.radius);
634     gCurPosMapCache = undefined;
635   }
636 }
637
638 var mapEvHandler = {
639   handleEvent: function(aEvent) {
640     var touchEvent = aEvent.type.indexOf('touch') != -1;
641
642     if (touchEvent) {
643       aEvent.stopPropagation();
644     }
645
646     // Bail out if the event is happening on an input.
647     if (aEvent.target.tagName.toLowerCase() == "input")
648       return;
649
650     // Bail out on unwanted map moves, but not zoom or keyboard events.
651     if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
652       // Bail out if this is neither a touch nor left-click.
653       if (!touchEvent && aEvent.button != 0)
654         return;
655
656       // Bail out if the started touch can't be found.
657       if (touchEvent && gDragging &&
658           !aEvent.changedTouches.identifiedTouch(gDragTouchID))
659         return;
660     }
661
662     var coordObj = touchEvent ?
663                    aEvent.changedTouches.identifiedTouch(gDragTouchID) :
664                    aEvent;
665
666     switch (aEvent.type) {
667       case "mousedown":
668       case "touchstart":
669         if (touchEvent) {
670           if (aEvent.targetTouches.length == 2) {
671             gPinchStartWidth = Math.sqrt(
672                 Math.pow(aEvent.targetTouches.item(1).clientX -
673                          aEvent.targetTouches.item(0).clientX, 2) +
674                 Math.pow(aEvent.targetTouches.item(1).clientY -
675                          aEvent.targetTouches.item(0).clientY, 2)
676             );
677           }
678           gDragTouchID = aEvent.changedTouches.item(0).identifier;
679           coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
680         }
681         var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
682         var y = coordObj.clientY - gGLMapCanvas.offsetTop;
683
684         if (touchEvent || aEvent.button === 0) {
685           gDragging = true;
686         }
687         gLastMouseX = x;
688         gLastMouseY = y;
689         showUI();
690         break;
691       case "mousemove":
692       case "touchmove":
693         if (touchEvent && aEvent.targetTouches.length == 2) {
694           curPinchStartWidth = Math.sqrt(
695               Math.pow(aEvent.targetTouches.item(1).clientX -
696                        aEvent.targetTouches.item(0).clientX, 2) +
697               Math.pow(aEvent.targetTouches.item(1).clientY -
698                        aEvent.targetTouches.item(0).clientY, 2)
699           );
700           if (!gPinchStartWidth)
701             gPinchStartWidth = curPinchStartWidth;
702
703           if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
704               gPinchStartWidth / curPinchStartWidth < 0.6) {
705             var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
706             if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
707               // Calculate new center of the map - preserve middle of pinch.
708               // This means that pixel distance between old center and middle
709               // must equal pixel distance of new center and middle.
710               var x = (aEvent.targetTouches.item(1).clientX +
711                        aEvent.targetTouches.item(0).clientX) / 2 -
712                       gGLMapCanvas.offsetLeft;
713               var y = (aEvent.targetTouches.item(1).clientY +
714                        aEvent.targetTouches.item(0).clientY) / 2 -
715                       gGLMapCanvas.offsetTop;
716
717               // Zoom factor after this action.
718               var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
719               gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
720               gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
721
722               if (gPinchStartWidth < curPinchStartWidth)
723                 zoomIn();
724               else
725                 zoomOut();
726
727               // Reset pinch start width and start another pinch gesture.
728               gPinchStartWidth = null;
729             }
730           }
731           // If we are in a pinch, do not drag.
732           break;
733         }
734         var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
735         var y = coordObj.clientY - gGLMapCanvas.offsetTop;
736         if (gDragging === true) {
737           var dX = x - gLastMouseX;
738           var dY = y - gLastMouseY;
739           gMap.pos.x -= dX * gMap.zoomFactor;
740           gMap.pos.y -= dY * gMap.zoomFactor;
741           gMap.draw();
742           showUI();
743         }
744         gLastMouseX = x;
745         gLastMouseY = y;
746         break;
747       case "mouseup":
748       case "touchend":
749         gPinchStartWidth = null;
750         gDragging = false;
751         showUI();
752         break;
753       case "mouseout":
754       case "touchcancel":
755       case "touchleave":
756         //gDragging = false;
757         break;
758       case "wheel":
759         // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
760         // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
761
762         // Only accept (non-null) deltaY values
763         if (!aEvent.deltaY)
764           break;
765
766         // Debug output: "coordinates" of the point the mouse was over.
767         /*
768         var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor,
769                        y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor};
770         var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
771         var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
772         console.log(ptCoord.x + "/" + ptCoord.y + " - " +
773                     gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
774                     pt2Coord.x + "/" + pt2Coord.y);
775         */
776
777         var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1);
778         if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
779           // Calculate new center of the map - same point stays under the mouse.
780           // This means that the pixel distance between the old center and point
781           // must equal the pixel distance of the new center and that point.
782           var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
783           var y = coordObj.clientY - gGLMapCanvas.offsetTop;
784
785           // Zoom factor after this action.
786           var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
787           gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
788           gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
789
790           if (aEvent.deltaY < 0)
791             zoomIn();
792           else
793             zoomOut();
794         }
795         break;
796       case "keydown":
797         // Allow keyboard control to move and zoom the map.
798         // Should use aEvent.key instead of aEvent.which but needs bug 680830.
799         // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
800         var dX = 0;
801         var dY = 0;
802         switch (aEvent.which) {
803           case 39: // right
804             dX = -gMap.tileSize / 2;
805           break;
806           case 37: // left
807             dX = gMap.tileSize / 2;
808           break;
809           case 38: // up
810             dY = gMap.tileSize / 2;
811           break;
812           case 40: // down
813             dY = -gMap.tileSize / 2;
814           break;
815           case 87: // w
816           case 107: // + (numpad)
817           case 171: // + (normal key)
818             zoomIn();
819           break;
820           case 83: // s
821           case 109: // - (numpad)
822           case 173: // - (normal key)
823             zoomOut();
824           break;
825           case 48: // 0
826           case 49: // 1
827           case 50: // 2
828           case 51: // 3
829           case 52: // 4
830           case 53: // 5
831           case 54: // 6
832           case 55: // 7
833           case 56: // 8
834             zoomTo(aEvent.which - 38);
835           break;
836           case 57: // 9
837             zoomTo(9);
838           break;
839           case 96: // 0 (numpad)
840           case 97: // 1 (numpad)
841           case 98: // 2 (numpad)
842           case 99: // 3 (numpad)
843           case 100: // 4 (numpad)
844           case 101: // 5 (numpad)
845           case 102: // 6 (numpad)
846           case 103: // 7 (numpad)
847           case 104: // 8 (numpad)
848             zoomTo(aEvent.which - 86);
849           break;
850           case 105: // 9 (numpad)
851             zoomTo(9);
852           break;
853           default: // not supported
854             console.log("key not supported: " + aEvent.which);
855           break;
856         }
857
858         // Move if needed.
859         if (dX || dY) {
860           gMap.pos.x -= dX * gMap.zoomFactor;
861           gMap.pos.y -= dY * gMap.zoomFactor;
862           gMap.draw();
863         }
864         break;
865     }
866   }
867 };
868
869 var geofake = {
870   tracking: false,
871   lastPos: {x: undefined, y: undefined},
872   watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
873     this.tracking = true;
874     var watchCall = function() {
875       // calc new position in lat/lon degrees
876       // 90° on Earth surface are ~10,000 km at the equator,
877       // so try moving at most 10m at a time
878       if (geofake.lastPos.x)
879         geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
880       else
881         geofake.lastPos.x = 48.208174
882       if (geofake.lastPos.y)
883         geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
884       else
885         geofake.lastPos.y = 16.373819
886       aSuccessCallback({timestamp: Date.now(),
887                         coords: {latitude: geofake.lastPos.x,
888                                  longitude: geofake.lastPos.y,
889                                  accuracy: 20}});
890       if (geofake.tracking)
891         setTimeout(watchCall, 1000);
892     };
893     setTimeout(watchCall, 1000);
894     return "foo";
895   },
896   clearWatch: function(aID) {
897     this.tracking = false;
898   }
899 }
900
901 function setCentering(aCheckbox) {
902   if (gMapPrefsLoaded && mainDB)
903     gPrefs.set("center_map", aCheckbox.checked);
904   gCenterPosition = aCheckbox.checked;
905 }
906
907 function setTracking(aCheckbox) {
908   if (gMapPrefsLoaded && mainDB)
909     gPrefs.set("tracking_enabled", aCheckbox.checked);
910   if (aCheckbox.checked)
911     startTracking();
912   else
913     endTracking();
914 }
915
916 function startTracking() {
917   if (gGeolocation) {
918     gActionLabel.textContent = "Establishing Position";
919     gAction.style.display = "block";
920     gGeoWatchID = gGeolocation.watchPosition(
921       function(position) {
922         if (gActionLabel.textContent) {
923           gActionLabel.textContent = "";
924           gAction.style.display = "none";
925         }
926         // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
927         var tPoint = {time: position.timestamp,
928                       coords: {latitude: position.coords.latitude,
929                                longitude: position.coords.longitude,
930                                altitude: position.coords.altitude,
931                                accuracy: position.coords.accuracy,
932                                altitudeAccuracy: position.coords.altitudeAccuracy,
933                                heading: position.coords.heading,
934                                speed: position.coords.speed},
935                       beginSegment: !gLastTrackPoint};
936         // Only add point to track is accuracy is good enough.
937         if (tPoint.coords.accuracy < gMinTrackAccuracy) {
938           gLastTrackPoint = tPoint;
939           gTrack.push(tPoint);
940           try { gTrackStore.push(tPoint); } catch(e) {}
941           var redrawn = false;
942           if (gCenterPosition) {
943             var posCoord = gps2xy(position.coords.latitude,
944                                   position.coords.longitude);
945             if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 ||
946                 Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) {
947               gMap.pos.x = posCoord.x;
948               gMap.pos.y = posCoord.y;
949               gMap.draw(); // This draws the current point as well.
950               redrawn = true;
951             }
952           }
953           if (!redrawn)
954             undrawCurrentLocation();
955             drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
956         }
957         drawCurrentLocation(tPoint);
958       },
959       function(error) {
960         // Ignore erros for the moment, but this is good for debugging.
961         // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
962         if (gDebug)
963           console.log(error.message);
964       },
965       {enableHighAccuracy: true}
966     );
967   }
968 }
969
970 function endTracking() {
971   if (gActionLabel.textContent) {
972     gActionLabel.textContent = "";
973     gAction.style.display = "none";
974   }
975   if (gGeoWatchID) {
976     gGeolocation.clearWatch(gGeoWatchID);
977   }
978 }
979
980 function clearTrack() {
981   gTrack = [];
982   gTrackStore.clear();
983   drawTrack();
984 }
985
986 var gTileService = {
987   objStore: "tilecache",
988
989   ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
990
991   get: function(aStyle, aCoords, aCallback) {
992     var norm = normalizeCoords(aCoords);
993     var dbkey = getTileKey(aStyle, norm);
994     this.getDBCache(dbkey, function(aResult, aEvent) {
995       if (aResult) {
996         // We did get a cached object.
997         aCallback(aResult.image, aStyle, aCoords, dbkey);
998         // Look at the timestamp and return if it's not too old.
999         if (aResult.timestamp + gTileService.ageLimit > Date.now())
1000           return;
1001         // Reload cached tile otherwise.
1002         var oldDate = new Date(aResult.timestamp);
1003         console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
1004       }
1005       // Retrieve image from the web and store it in the cache.
1006       var XHR = new XMLHttpRequest();
1007       XHR.open("GET",
1008                 gMapStyles[aStyle].url
1009                   .replace("{x}", norm.x)
1010                   .replace("{y}", norm.y)
1011                   .replace("{z}", norm.z)
1012                   .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
1013                   .replace("[1-4]", 1 + Math.floor(Math.random() * 3)),
1014                 true);
1015       XHR.responseType = "blob";
1016       XHR.addEventListener("load", function () {
1017         if (XHR.status === 200) {
1018           var blob = XHR.response;
1019           aCallback(blob, aStyle, aCoords, dbkey);
1020           gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
1021         }
1022       }, false);
1023       XHR.send();
1024     });
1025   },
1026
1027   getDBCache: function(aKey, aCallback) {
1028     if (!mainDB)
1029       return;
1030     var transaction = mainDB.transaction([this.objStore]);
1031     var request = transaction.objectStore(this.objStore).get(aKey);
1032     request.onsuccess = function(event) {
1033       aCallback(request.result, event);
1034     };
1035     request.onerror = function(event) {
1036       // Errors can be handled here.
1037       aCallback(undefined, event);
1038     };
1039   },
1040
1041   setDBCache: function(aKey, aValue, aCallback) {
1042     if (!mainDB)
1043       return;
1044     var success = false;
1045     var transaction = mainDB.transaction([this.objStore], "readwrite");
1046     var objStore = transaction.objectStore(this.objStore);
1047     var request = objStore.put(aValue, aKey);
1048     request.onsuccess = function(event) {
1049       success = true;
1050       if (aCallback)
1051         aCallback(success, event);
1052     };
1053     request.onerror = function(event) {
1054       // Errors can be handled here.
1055       if (aCallback)
1056         aCallback(success, event);
1057     };
1058   },
1059
1060   unsetDBCache: function(aKey, aCallback) {
1061     if (!mainDB)
1062       return;
1063     var success = false;
1064     var transaction = mainDB.transaction([this.objStore], "readwrite");
1065     var request = transaction.objectStore(this.objStore).delete(aKey);
1066     request.onsuccess = function(event) {
1067       success = true;
1068       if (aCallback)
1069         aCallback(success, event);
1070     };
1071     request.onerror = function(event) {
1072       // Errors can be handled here.
1073       if (aCallback)
1074         aCallback(success, event);
1075     }
1076   },
1077
1078   clearDB: function(aCallback) {
1079     if (!mainDB)
1080       return;
1081     var success = false;
1082     var transaction = mainDB.transaction([this.objStore], "readwrite");
1083     var request = transaction.objectStore(this.objStore).clear();
1084     request.onsuccess = function(event) {
1085       success = true;
1086       if (aCallback)
1087         aCallback(success, event);
1088     };
1089     request.onerror = function(event) {
1090       // Errors can be handled here.
1091       if (aCallback)
1092         aCallback(success, event);
1093     }
1094   }
1095 };