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