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