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/. */
5 var gGLMapCanvas, gTrackCanvas, gTrackContext, gGeolocation;
8 var gMinTrackAccuracy = 1000; // meters
9 var gTrackWidth = 2; // pixels
10 var gTrackColor = "#FF0000";
11 var gCurLocSize = 6; // pixels
12 var gCurLocColor = "#A00000";
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
18 {name: "OpenStreetMap (Mapnik)",
19 url: "http://tile.openstreetmap.org/{z}/{x}/{y}.png",
20 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
22 {name: "Cycle Map (OSM)",
23 url: "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
24 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
26 {name: "Transport Map (OSM)",
27 url: "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png",
28 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
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 © <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>.'},
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.'},
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>.'},
43 url: " http://mt1.google.com/vt/x={x}&y={y}&z={z}",
44 copyright: 'Map data and imagery © <a href="http://maps.google.com/">Google</a>'},
52 var gMapPrefsLoaded = false;
54 var gDragging = false;
55 var gDragTouchID, gPinchStartWidth;
59 var gLastTrackPoint, gLastDrawnPoint;
60 var gCenterPosition = true;
65 gGeolocation = navigator.geolocation;
66 // Set up canvas context.
67 gGLMapCanvas = document.getElementById("map");
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});
76 // If we don't have a GL context, give up now
77 showGLWarningDialog();
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);
88 gTrackCanvas = document.getElementById("track");
89 gTrackContext = gTrackCanvas.getContext("2d");
91 gMap.activeMap = "osm_mapnik";
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");
103 gAction.addEventListener("prefload-done", gMap.initGL, false);
105 console.log("map vars set, loading prefs...");
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.");
117 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
118 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
119 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
120 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
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);
128 gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
130 document.getElementById("body").addEventListener("keydown", mapEvHandler, false);
132 document.addEventListener("visibilitychange", visibilityEvHandler, false);
134 console.log("Events added.");
135 document.getElementById("copyright").innerHTML =
136 gMapStyles[gMap.activeMap].copyright;
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);
145 console.log("Set loading tile...");
146 gLoadingTile.src = "style/loading.png";
151 gAction.removeEventListener(aEvent.type, loadPrefs, false);
152 gAction.addEventListener("prefs-step", loadPrefs, false);
154 gPrefs.get("position", function(aValue) {
155 if (aValue && aValue.x && aValue.y && aValue.z) {
159 var throwEv = new CustomEvent("prefs-step");
160 gAction.dispatchEvent(throwEv);
163 gPrefs.get("center_map", function(aValue) {
164 if (aValue === undefined)
165 document.getElementById("centerCheckbox").checked = true;
167 document.getElementById("centerCheckbox").checked = aValue;
168 setCentering(document.getElementById("centerCheckbox"));
170 var throwEv = new CustomEvent("prefs-step");
171 gAction.dispatchEvent(throwEv);
174 gPrefs.get("tracking_enabled", function(aValue) {
175 if (aValue === undefined)
176 document.getElementById("trackCheckbox").checked = true;
178 document.getElementById("trackCheckbox").checked = aValue;
180 var throwEv = new CustomEvent("prefs-step");
181 gAction.dispatchEvent(throwEv);
184 var trackLoadStarted = false;
185 var redrawBase = 100;
186 gTrackStore.getListStepped(function(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) {
195 if (redrawBase < 1000) {
196 redrawBase = tracklen;
201 // Last point received.
204 if (!trackLoadStarted) {
205 // We have the most recent point, if present, rest will load async.
206 trackLoadStarted = true;
208 var throwEv = new CustomEvent("prefs-step");
209 gAction.dispatchEvent(throwEv);
217 glShaderProgram: null,
218 glVertexPositionAttr: null,
219 glTextureCoordAttr: null,
220 glResolutionAttr: null,
223 glTxCleanIntervalID: null,
224 glTexturesPerZoomLevel: 0,
226 activeMap: "osm_mapnik",
228 maxZoom: 18, // The minimum is 0.
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.
235 baseDim: { // Map width, height and tile size in level 18 pixels.
241 get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; },
242 get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; },
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' +
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' +
263 // When called from the event listener, the "this" reference doesn't work, so use the object name.
264 console.log("Initializing WebGL...");
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.
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));
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));
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.");
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");
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.
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);
322 gMap.loadImageToTexture(gLoadingTile, getTileKey("loading", {x: 0, y: 0, z: 0}));
324 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
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);
333 // Call texture cleaning every 30 seconds, for now (is 60 better?).
334 gMap.glTxCleanIntervalID = window.setInterval(gMap.cleanTextures, 30 * 1000);
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);
351 assembleGL: function() {
352 if (!gMap.gl) { return; }
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;
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;
365 if (gMapPrefsLoaded && mainDB)
366 gPrefs.set("position", gMap.pos);
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() });
388 URL.revokeObjectURL(imgURL);
396 if (document.hidden != true) { // Only draw if we're actually visible.
397 window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
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;
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});
419 gMap.drawTileGL(xoff, yoff, tileKey);
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;
433 // Size viewport to canvas size.
434 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
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;
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);
453 var i_width = gMap.tileSize;
454 var y_start = aRight;
455 var i_height = gMap.tileSize;
456 var textureCoordinates = [
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,
464 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW);
466 // There are 6 indices in textureCoordinates.
467 gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
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);
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");
492 if (Object.keys(gMap.glTextures).length > gMap.glTexturesPerZoomLevel) {
493 console.log("Cleaning textures... (have " + Object.keys(gMap.glTextures).length + " atm)");
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,
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,
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") {
507 style: keyMatches[1],
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); }
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); }
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); }
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); }
530 // Delete texture from GL and from the array we are holding.
531 gMap.gl.deleteTexture(gMap.glTextures[tileKey]);
532 delete gMap.glTextures[tileKey];
536 console.log("Cleaning complete, " + Object.keys(gMap.glTextures).length + " textures left)");
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 = {};
547 handleContextRestored: function(event) {
548 // When GL context is back, init GL again and draw.
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
558 if (gMap.pos.z < gMap.maxZoom) {
565 if (gMap.pos.z > 0) {
571 function zoomTo(aTargetLevel) {
572 aTargetLevel = parseInt(aTargetLevel);
573 if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) {
574 gMap.pos.z = aTargetLevel;
579 function 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)};
589 function 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};
597 function 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;
608 // A sane mod function that works for negative numbers.
611 return ((a % b) + b) % b;
614 function normalizeCoords(aCoords) {
615 var zoomFactor = Math.pow(2, aCoords.z);
616 return {x: mod(aCoords.x, zoomFactor),
617 y: mod(aCoords.y, zoomFactor),
621 function getTileKey(aStyle, aNormalizedCoords) {
622 return aStyle + "::" +
623 aNormalizedCoords.x + "," +
624 aNormalizedCoords.y + "," +
628 // Returns true if the tile is outside the current view.
629 function isOutsideWindow(t) {
630 var pos = decodeIndex(t);
632 var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z);
633 var wid = gMap.width * zoomFactor;
634 var ht = gMap.height * zoomFactor;
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)
646 function encodeIndex(x, y, z) {
647 var norm = normalizeCoords({x: x, y: y, z: z});
648 return norm.x + "," + norm.y + "," + norm.z;
651 function decodeIndex(encodedIdx) {
652 var ind = encodedIdx.split(",", 3);
653 return {x: ind[0], y: ind[1], z: ind[2]};
656 function 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);
662 for (var i = 0; i < gTrack.length; i++) {
663 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
664 (i + 1 >= gTrack.length || gTrack[i+1].beginSegment));
670 function 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)};
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";
684 // This breaks optimiziation, so make sure to reset optimization.
685 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
686 trackpoint.optimized = false;
687 // Close path if one was open.
688 if (gLastDrawnPoint && gLastDrawnPoint.optimized) {
689 gTrackContext.stroke();
692 if (!gLastDrawnPoint || (gLastDrawnPoint == trackpoint) || !gLastDrawnPoint.optimized) {
693 // Start drawing a segment.
694 gTrackContext.beginPath();
695 gTrackContext.arc(mappos.x, mappos.y,
696 gTrackContext.lineWidth, 0, Math.PI * 2, false);
697 gTrackContext.fill();
700 // Continue drawing segment, close if needed.
701 gTrackContext.lineTo(mappos.x, mappos.y);
702 if (!trackpoint.optimized)
703 gTrackContext.stroke();
705 gLastDrawnPoint = trackpoint;
708 function drawCurrentLocation(trackPoint) {
709 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
710 var circleRadius = Math.round(gCurLocSize / 2);
711 var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
712 y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
714 undrawCurrentLocation();
716 // Cache overdrawn area.
719 radius: circleRadius,
720 data: gTrackContext.getImageData(mappos.x - circleRadius,
721 mappos.y - circleRadius,
722 circleRadius * 2, circleRadius * 2)};
724 gTrackContext.strokeStyle = gCurLocColor;
725 gTrackContext.fillStyle = gTrackContext.strokeStyle;
726 gTrackContext.beginPath();
727 gTrackContext.arc(mappos.x, mappos.y,
728 circleRadius, 0, Math.PI * 2, false);
729 gTrackContext.fill();
732 function undrawCurrentLocation() {
733 if (gCurPosMapCache) {
734 var oldpoint = gCurPosMapCache.point;
735 var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
736 y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
737 gTrackContext.putImageData(gCurPosMapCache.data,
738 oldmp.x - gCurPosMapCache.radius,
739 oldmp.y - gCurPosMapCache.radius);
740 gCurPosMapCache = undefined;
744 function calcTrackDuration() {
745 // Get the duration of the track in s.
747 if (gTrack.length > 1) {
748 for (var i = 1; i < gTrack.length; i++) {
749 if (!gTrack[i].beginSegment) {
750 tDuration += (gTrack[i].time - gTrack[i-1].time);
754 return Math.round(tDuration / 1000); // The timestamps are in ms but we return seconds.
757 function calcTrackLength() {
758 // Get the length of the track in km.
760 if (gTrack.length > 1) {
761 for (var i = 1; i < gTrack.length; i++) {
762 if (!gTrack[i].beginSegment) {
763 tLength += getPointDistance(gTrack[i-1].coords, gTrack[i].coords);
770 function getPointDistance(aGPSPoint1, aGPSPoint2) {
771 // Get the distance in km between the two given GPS points.
772 // See http://stackoverflow.com/questions/365826/calculate-distance-between-2-gps-coordinates
773 // Earth is almost exactly a sphere and we calculate small distances on the surface, so we can do spherical great-circle math.
774 // Also see http://en.wikipedia.org/wiki/Great-circle_distance
776 var dLat = deg2rad(aGPSPoint2.latitude - aGPSPoint1.latitude);
777 var dLon = deg2rad(aGPSPoint2.longitude - aGPSPoint1.longitude);
778 var lat1 = deg2rad(aGPSPoint1.latitude);
779 var lat2 = deg2rad(aGPSPoint2.latitude);
781 var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
782 Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
783 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
787 function deg2rad(aDegreeValue) {
788 // Convert an angle in degrees to radiants.
789 return aDegreeValue * (Math.PI / 180);
793 handleEvent: function(aEvent) {
794 var touchEvent = aEvent.type.indexOf('touch') != -1;
797 aEvent.stopPropagation();
800 // Bail out if the event is happening on an input.
801 if (aEvent.target.tagName.toLowerCase() == "input")
804 // Bail out on unwanted map moves, but not zoom or keyboard events.
805 if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
806 // Bail out if this is neither a touch nor left-click.
807 if (!touchEvent && aEvent.button != 0)
810 // Bail out if the started touch can't be found.
811 if (touchEvent && gDragging &&
812 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
816 var coordObj = touchEvent ?
817 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
820 switch (aEvent.type) {
824 if (aEvent.targetTouches.length == 2) {
825 gPinchStartWidth = Math.sqrt(
826 Math.pow(aEvent.targetTouches.item(1).clientX -
827 aEvent.targetTouches.item(0).clientX, 2) +
828 Math.pow(aEvent.targetTouches.item(1).clientY -
829 aEvent.targetTouches.item(0).clientY, 2)
832 gDragTouchID = aEvent.changedTouches.item(0).identifier;
833 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
835 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
836 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
838 if (touchEvent || aEvent.button === 0) {
847 if (touchEvent && aEvent.targetTouches.length == 2) {
848 curPinchStartWidth = Math.sqrt(
849 Math.pow(aEvent.targetTouches.item(1).clientX -
850 aEvent.targetTouches.item(0).clientX, 2) +
851 Math.pow(aEvent.targetTouches.item(1).clientY -
852 aEvent.targetTouches.item(0).clientY, 2)
854 if (!gPinchStartWidth)
855 gPinchStartWidth = curPinchStartWidth;
857 if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
858 gPinchStartWidth / curPinchStartWidth < 0.6) {
859 var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
860 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
861 // Calculate new center of the map - preserve middle of pinch.
862 // This means that pixel distance between old center and middle
863 // must equal pixel distance of new center and middle.
864 var x = (aEvent.targetTouches.item(1).clientX +
865 aEvent.targetTouches.item(0).clientX) / 2 -
866 gGLMapCanvas.offsetLeft;
867 var y = (aEvent.targetTouches.item(1).clientY +
868 aEvent.targetTouches.item(0).clientY) / 2 -
869 gGLMapCanvas.offsetTop;
871 // Zoom factor after this action.
872 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
873 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
874 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
876 if (gPinchStartWidth < curPinchStartWidth)
881 // Reset pinch start width and start another pinch gesture.
882 gPinchStartWidth = null;
885 // If we are in a pinch, do not drag.
888 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
889 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
890 if (gDragging === true) {
891 var dX = x - gLastMouseX;
892 var dY = y - gLastMouseY;
893 gMap.pos.x -= dX * gMap.zoomFactor;
894 gMap.pos.y -= dY * gMap.zoomFactor;
903 gPinchStartWidth = null;
913 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
914 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
916 // Only accept (non-null) deltaY values
920 // Debug output: "coordinates" of the point the mouse was over.
922 var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor,
923 y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor};
924 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
925 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
926 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
927 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
928 pt2Coord.x + "/" + pt2Coord.y);
931 var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1);
932 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
933 // Calculate new center of the map - same point stays under the mouse.
934 // This means that the pixel distance between the old center and point
935 // must equal the pixel distance of the new center and that point.
936 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
937 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
939 // Zoom factor after this action.
940 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
941 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
942 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
944 if (aEvent.deltaY < 0)
951 // Allow keyboard control to move and zoom the map.
952 // Should use aEvent.key instead of aEvent.which but needs bug 680830.
953 // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
956 switch (aEvent.which) {
958 dX = -gMap.tileSize / 2;
961 dX = gMap.tileSize / 2;
964 dY = gMap.tileSize / 2;
967 dY = -gMap.tileSize / 2;
970 case 107: // + (numpad)
971 case 171: // + (normal key)
975 case 109: // - (numpad)
976 case 173: // - (normal key)
988 zoomTo(aEvent.which - 38);
993 case 96: // 0 (numpad)
994 case 97: // 1 (numpad)
995 case 98: // 2 (numpad)
996 case 99: // 3 (numpad)
997 case 100: // 4 (numpad)
998 case 101: // 5 (numpad)
999 case 102: // 6 (numpad)
1000 case 103: // 7 (numpad)
1001 case 104: // 8 (numpad)
1002 zoomTo(aEvent.which - 86);
1004 case 105: // 9 (numpad)
1007 default: // not supported
1008 console.log("key not supported: " + aEvent.which);
1014 gMap.pos.x -= dX * gMap.zoomFactor;
1015 gMap.pos.y -= dY * gMap.zoomFactor;
1023 function visibilityEvHandler() {
1024 // Immediately draw if we just got visible.
1025 if (document.hidden != true) {
1028 // No need to handle the event where we become invisible as we care only draw
1029 // when we are visible anyhow.
1034 lastPos: {x: undefined, y: undefined},
1035 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
1036 this.tracking = true;
1037 var watchCall = function() {
1038 // calc new position in lat/lon degrees
1039 // 90° on Earth surface are ~10,000 km at the equator,
1040 // so try moving at most 10m at a time
1041 if (geofake.lastPos.x)
1042 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
1044 geofake.lastPos.x = 48.208174
1045 if (geofake.lastPos.y)
1046 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
1048 geofake.lastPos.y = 16.373819
1049 aSuccessCallback({timestamp: Date.now(),
1050 coords: {latitude: geofake.lastPos.x,
1051 longitude: geofake.lastPos.y,
1053 if (geofake.tracking)
1054 setTimeout(watchCall, 1000);
1056 setTimeout(watchCall, 1000);
1059 clearWatch: function(aID) {
1060 this.tracking = false;
1064 function setCentering(aCheckbox) {
1065 if (gMapPrefsLoaded && mainDB)
1066 gPrefs.set("center_map", aCheckbox.checked);
1067 gCenterPosition = aCheckbox.checked;
1070 function setTracking(aCheckbox) {
1071 if (gMapPrefsLoaded && mainDB)
1072 gPrefs.set("tracking_enabled", aCheckbox.checked);
1073 if (aCheckbox.checked)
1079 function startTracking() {
1081 gActionLabel.textContent = "Establishing Position";
1082 gAction.style.display = "block";
1083 gGeoWatchID = gGeolocation.watchPosition(
1084 function(position) {
1085 if (gActionLabel.textContent) {
1086 gActionLabel.textContent = "";
1087 gAction.style.display = "none";
1089 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
1090 var tPoint = {time: position.timestamp,
1091 coords: {latitude: position.coords.latitude,
1092 longitude: position.coords.longitude,
1093 altitude: position.coords.altitude,
1094 accuracy: position.coords.accuracy,
1095 altitudeAccuracy: position.coords.altitudeAccuracy,
1096 heading: position.coords.heading,
1097 speed: position.coords.speed},
1098 beginSegment: !gLastTrackPoint};
1099 // Only add point to track is accuracy is good enough.
1100 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
1101 gLastTrackPoint = tPoint;
1102 gTrack.push(tPoint);
1103 try { gTrackStore.push(tPoint); } catch(e) {}
1104 var redrawn = false;
1105 if (gCenterPosition) {
1106 var posCoord = gps2xy(position.coords.latitude,
1107 position.coords.longitude);
1108 if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 ||
1109 Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) {
1110 gMap.pos.x = posCoord.x;
1111 gMap.pos.y = posCoord.y;
1112 gMap.draw(); // This draws the current point as well.
1117 undrawCurrentLocation();
1118 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
1120 drawCurrentLocation(tPoint);
1123 // Ignore erros for the moment, but this is good for debugging.
1124 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
1126 console.log(error.message);
1128 {enableHighAccuracy: true}
1133 function endTracking() {
1134 if (gActionLabel.textContent) {
1135 gActionLabel.textContent = "";
1136 gAction.style.display = "none";
1139 gGeolocation.clearWatch(gGeoWatchID);
1143 function clearTrack() {
1145 gTrackStore.clear();
1149 var gTileService = {
1150 objStore: "tilecache",
1152 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
1154 get: function(aStyle, aCoords, aCallback) {
1155 var norm = normalizeCoords(aCoords);
1156 var dbkey = getTileKey(aStyle, norm);
1157 this.getDBCache(dbkey, function(aResult, aEvent) {
1159 // We did get a cached object.
1160 aCallback(aResult.image, aStyle, aCoords, dbkey);
1161 // Look at the timestamp and return if it's not too old.
1162 if (aResult.timestamp + gTileService.ageLimit > Date.now())
1164 // Reload cached tile otherwise.
1165 var oldDate = new Date(aResult.timestamp);
1166 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
1168 // Retrieve image from the web and store it in the cache.
1169 var XHR = new XMLHttpRequest();
1171 gMapStyles[aStyle].url
1172 .replace("{x}", norm.x)
1173 .replace("{y}", norm.y)
1174 .replace("{z}", norm.z)
1175 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 3)))
1176 .replace("[1-4]", 1 + Math.floor(Math.random() * 4)),
1178 XHR.responseType = "blob";
1179 XHR.addEventListener("load", function () {
1180 if (XHR.status === 200) {
1181 var blob = XHR.response;
1182 aCallback(blob, aStyle, aCoords, dbkey);
1183 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
1190 getDBCache: function(aKey, aCallback) {
1193 var transaction = mainDB.transaction([this.objStore]);
1194 var request = transaction.objectStore(this.objStore).get(aKey);
1195 request.onsuccess = function(event) {
1196 aCallback(request.result, event);
1198 request.onerror = function(event) {
1199 // Errors can be handled here.
1200 aCallback(undefined, event);
1204 setDBCache: function(aKey, aValue, aCallback) {
1207 var success = false;
1208 var transaction = mainDB.transaction([this.objStore], "readwrite");
1209 var objStore = transaction.objectStore(this.objStore);
1210 var request = objStore.put(aValue, aKey);
1211 request.onsuccess = function(event) {
1214 aCallback(success, event);
1216 request.onerror = function(event) {
1217 // Errors can be handled here.
1219 aCallback(success, event);
1223 unsetDBCache: function(aKey, aCallback) {
1226 var success = false;
1227 var transaction = mainDB.transaction([this.objStore], "readwrite");
1228 var request = transaction.objectStore(this.objStore).delete(aKey);
1229 request.onsuccess = function(event) {
1232 aCallback(success, event);
1234 request.onerror = function(event) {
1235 // Errors can be handled here.
1237 aCallback(success, event);
1241 clearDB: function(aCallback) {
1244 var success = false;
1245 var transaction = mainDB.transaction([this.objStore], "readwrite");
1246 var request = transaction.objectStore(this.objStore).clear();
1247 request.onsuccess = function(event) {
1250 aCallback(success, event);
1252 request.onerror = function(event) {
1253 // Errors can be handled here.
1255 aCallback(success, event);