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});
75 // If we don't have a GL context, give up now
77 showGLWarningDialog();
80 gTrackCanvas = document.getElementById("track");
81 gTrackContext = gTrackCanvas.getContext("2d");
83 gMap.activeMap = "osm_mapnik";
87 gGeolocation = geofake;
88 var hiddenList = document.getElementsByClassName("debugHide");
89 // last to first - list of elements with that class is changing!
90 for (var i = hiddenList.length - 1; i >= 0; i--) {
91 hiddenList[i].classList.remove("debugHide");
95 gAction.addEventListener("prefload-done", gMap.initGL, false);
97 console.log("map vars set, loading prefs...");
101 function loadPrefs(aEvent) {
102 if (aEvent && aEvent.type == "prefs-step") {
103 console.log("wait: " + gWaitCounter);
104 if (gWaitCounter == 0) {
105 gAction.removeEventListener(aEvent.type, loadPrefs, false);
106 gMapPrefsLoaded = true;
107 console.log("prefs loaded.");
109 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
110 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
111 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
112 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
114 gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
115 gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
116 gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
117 gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
118 gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
120 gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
122 document.getElementById("body").addEventListener("keydown", mapEvHandler, false);
124 console.log("Events added.");
125 document.getElementById("copyright").innerHTML =
126 gMapStyles[gMap.activeMap].copyright;
128 console.log("Init loading tile...");
129 gLoadingTile = new Image();
130 gLoadingTile.onload = function() {
131 console.log("Loading tile loaded.");
132 var throwEv = new CustomEvent("prefload-done");
133 gAction.dispatchEvent(throwEv);
135 console.log("Set loading tile...");
136 gLoadingTile.src = "style/loading.png";
141 gAction.removeEventListener(aEvent.type, loadPrefs, false);
142 gAction.addEventListener("prefs-step", loadPrefs, false);
144 gPrefs.get("position", function(aValue) {
145 if (aValue && aValue.x && aValue.y && aValue.z) {
149 var throwEv = new CustomEvent("prefs-step");
150 gAction.dispatchEvent(throwEv);
153 gPrefs.get("center_map", function(aValue) {
154 if (aValue === undefined)
155 document.getElementById("centerCheckbox").checked = true;
157 document.getElementById("centerCheckbox").checked = aValue;
158 setCentering(document.getElementById("centerCheckbox"));
160 var throwEv = new CustomEvent("prefs-step");
161 gAction.dispatchEvent(throwEv);
164 gPrefs.get("tracking_enabled", function(aValue) {
165 if (aValue === undefined)
166 document.getElementById("trackCheckbox").checked = true;
168 document.getElementById("trackCheckbox").checked = aValue;
170 var throwEv = new CustomEvent("prefs-step");
171 gAction.dispatchEvent(throwEv);
174 var trackLoadStarted = false;
175 var redrawBase = 100;
176 gTrackStore.getListStepped(function(aTPoint) {
178 // Add in front and return new length.
179 var tracklen = gTrack.unshift(aTPoint);
180 // Redraw track periodically, larger distance the longer it gets.
181 // Initial paint will do initial track drawing.
182 if (tracklen % redrawBase == 0) {
184 redrawBase = tracklen;
188 // Last point received.
191 if (!trackLoadStarted) {
192 // We have the most recent point, if present, rest will load async.
193 trackLoadStarted = true;
195 var throwEv = new CustomEvent("prefs-step");
196 gAction.dispatchEvent(throwEv);
204 glShaderProgram: null,
205 glVertexPositionAttr: null,
206 glTextureCoordAttr: null,
207 glResolutionAttr: null,
210 glTxCleanIntervalID: null,
211 glTexturesPerZoomLevel: 0,
213 activeMap: "osm_mapnik",
215 maxZoom: 18, // The minimum is 0.
218 x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
219 y: 23670000.0, // The range is 0-67108864 (2^gMap.maxZoom * gMap.tileSize)
220 z: 5 // This could be fractional if supported being between zoom levels.
222 baseDim: { // Map width, height and tile size in level 18 pixels.
228 get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; },
229 get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; },
231 getVertShaderSource: function() {
232 return 'attribute vec2 aVertexPosition;\n' +
233 'attribute vec2 aTextureCoord;\n\n' +
234 'uniform vec2 uResolution;\n\n' +
235 'varying highp vec2 vTextureCoord;\n\n' +
236 'void main(void) {\n' +
237 // convert the rectangle from pixels to -1.0 to +1.0 (clipspace) 0.0 to 1.0
238 ' vec2 clipSpace = aVertexPosition * 2.0 / uResolution - 1.0;\n' +
239 ' gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' +
240 ' vTextureCoord = aTextureCoord;\n' +
242 getFragShaderSource: function() {
243 return 'varying highp vec2 vTextureCoord;\n\n' +
244 'uniform sampler2D uImage;\n\n' +
245 'void main(void) {\n' +
246 ' gl_FragColor = texture2D(uImage, vTextureCoord);\n' +
250 // When called from the event listener, the "this" reference doesn't work, so use the object name.
251 console.log("Initializing WebGL...");
253 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
254 gMap.gl.clearColor(0.0, 0.0, 0.0, 0.5); // Set clear color to black, fully opaque.
255 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT|gMap.gl.DEPTH_BUFFER_BIT); // Clear the color.
257 // Create and initialize the shaders.
258 console.log("Create and compile shaders...");
259 var vertShader = gMap.gl.createShader(gMap.gl.VERTEX_SHADER);
260 var fragShader = gMap.gl.createShader(gMap.gl.FRAGMENT_SHADER);
261 gMap.gl.shaderSource(vertShader, gMap.getVertShaderSource());
262 // Compile the shader program.
263 gMap.gl.compileShader(vertShader);
264 // See if it compiled successfully.
265 if (!gMap.gl.getShaderParameter(vertShader, gMap.gl.COMPILE_STATUS)) {
266 console.log("An error occurred compiling the vertex shader: " + gMap.gl.getShaderInfoLog(vertShader));
269 gMap.gl.shaderSource(fragShader, gMap.getFragShaderSource());
270 // Compile the shader program.
271 gMap.gl.compileShader(fragShader);
272 // See if it compiled successfully.
273 if (!gMap.gl.getShaderParameter(fragShader, gMap.gl.COMPILE_STATUS)) {
274 console.log("An error occurred compiling the fragment shader: " + gMap.gl.getShaderInfoLog(fragShader));
278 console.log("Create and link shader program...");
279 gMap.glShaderProgram = gMap.gl.createProgram();
280 gMap.gl.attachShader(gMap.glShaderProgram, vertShader);
281 gMap.gl.attachShader(gMap.glShaderProgram, fragShader);
282 gMap.gl.linkProgram(gMap.glShaderProgram);
283 // If creating the shader program failed, alert
284 if (!gMap.gl.getProgramParameter(gMap.glShaderProgram, gMap.gl.LINK_STATUS)) {
285 alert("Unable to initialize the shader program.");
287 gMap.gl.useProgram(gMap.glShaderProgram);
288 // Get locations of the attributes.
289 gMap.glVertexPositionAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aVertexPosition");
290 gMap.glTextureCoordAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aTextureCoord");
291 gMap.glResolutionAttr = gMap.gl.getUniformLocation(gMap.glShaderProgram, "uResolution");
293 console.log("Set up vertex buffer...");
294 var tileVerticesBuffer = gMap.gl.createBuffer();
295 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, tileVerticesBuffer);
296 // The vertices are the coordinates of the corner points of the square.
305 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(vertices), gMap.gl.STATIC_DRAW);
306 gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr);
307 gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0);
309 gMap.loadImageToTexture(gLoadingTile, getTileKey("loading", {x: 0, y: 0, z: 0}));
311 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
313 // Create a buffer for the position of the rectangle corners.
314 console.log("Set up coord buffer...");
315 var mapVerticesTextureCoordBuffer = gMap.gl.createBuffer();
316 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer);
317 gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr);
318 gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0);
320 // Call texture cleaning every 30 seconds, for now (is 60 better?).
321 gMap.glTxCleanIntervalID = window.setInterval(gMap.cleanTextures, 30 * 1000);
324 var throwEv = new CustomEvent("mapinit-done");
325 gAction.dispatchEvent(throwEv);
333 assembleGL: function() {
334 if (!gMap.gl) { return; }
336 document.getElementById("zoomLevel").textContent = gMap.pos.z;
337 gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
338 gMap.baseDim.wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor;
339 gMap.baseDim.ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor;
340 gMap.baseDim.tsize = gMap.tileSize * gMap.zoomFactor;
342 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
343 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
344 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
345 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
347 if (gMapPrefsLoaded && mainDB)
348 gPrefs.set("position", gMap.pos);
350 // Go through all the tiles in the map, find out if to draw them and do so.
351 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
352 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
353 // Only go to loading step if we haven't loaded the texture.
354 var coords = {x: x, y: y, z: gMap.pos.z};
355 var tileKey = getTileKey(gMap.activeMap, normalizeCoords(coords));
356 if (!gMap.glTextures[tileKey]) {
357 // Initiate loading/drawing of the actual tile.
358 gTileService.get(gMap.activeMap, coords,
359 function(aImage, aStyle, aCoords, aTileKey) {
360 // Only actually load if this still applies for the current view.
361 if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) {
362 var URL = window.URL;
363 var imgURL = URL.createObjectURL(aImage);
364 var imgObj = new Image();
365 imgObj.onload = function() {
366 gMap.loadImageToTexture(imgObj, aTileKey);
367 window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
368 URL.revokeObjectURL(imgURL);
376 window.requestAnimationFrame(function(aTimestamp) { gMap.drawGL() });
380 var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels.
381 var yMin = gMap.pos.y - gMap.baseDim.ht / 2;
382 var xMax = gMap.pos.x + gMap.baseDim.wid / 2;
383 var yMax = gMap.pos.y + gMap.baseDim.ht / 2;
385 // Go through all the tiles in the map, find out if to draw them and do so.
386 for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) {
387 for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) {
388 // Rounding the pixel offsets ensures we position the tiles precisely.
389 var xoff = Math.round((x * gMap.baseDim.tsize - xMin) / gMap.zoomFactor);
390 var yoff = Math.round((y * gMap.baseDim.tsize - yMin) / gMap.zoomFactor);
391 // Draw the tile, first find out the actual texture to use.
392 var norm = normalizeCoords({x: x, y: y, z: gMap.pos.z});
393 var tileKey = getTileKey(gMap.activeMap, norm);
394 if (!gMap.glTextures[tileKey]) {
395 tileKey = getTileKey("loading", {x: 0, y: 0, z: 0});
397 gMap.drawTileGL(xoff, yoff, tileKey);
402 resizeAndDraw: function() {
403 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
404 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
405 if (gGLMapCanvas && gTrackCanvas) {
406 gGLMapCanvas.width = viewportWidth;
407 gGLMapCanvas.height = viewportHeight;
408 gTrackCanvas.width = viewportWidth;
409 gTrackCanvas.height = viewportHeight;
411 // Size viewport to canvas size.
412 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
414 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT);
415 // Make sure the vertex shader get the right resolution.
416 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
417 // Prepare recalculation of textures to keep for one zoom level.
418 gMap.glTexturesPerZoomLevel = 0;
425 drawTileGL: function(aLeft, aRight, aTileKey) {
426 gMap.gl.activeTexture(gMap.gl.TEXTURE0);
427 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
428 // Set uImage to refer to TEXTURE0
429 gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0);
431 var i_width = gMap.tileSize;
432 var y_start = aRight;
433 var i_height = gMap.tileSize;
434 var textureCoordinates = [
436 x_start + i_width, y_start,
437 x_start, y_start + i_height,
438 x_start, y_start + i_height,
439 x_start + i_width, y_start,
440 x_start + i_width, y_start + i_height,
442 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW);
444 // There are 6 indices in textureCoordinates.
445 gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
448 loadImageToTexture: function(aImage, aTileKey) {
449 // Create and bind texture.
450 gMap.glTextures[aTileKey] = gMap.gl.createTexture();
451 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]);
452 // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two).
453 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST);
454 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST);
455 // Upload the image into the texture.
456 gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage);
459 cleanTextures: function() {
460 // Get rid of unneeded textures to save memory.
461 // TODO: Be less aggressive, maybe keep neighboring zoom levels (but x/y coords there are zoom-specific).
462 if (!gMap.glTexturesPerZoomLevel) {
463 // Calculate how many textures we need to keep for one zoom level.
464 // ceil(width/size) gives us the minimum, keep one on either side as well.
465 gMap.glTexturesPerZoomLevel =
466 Math.ceil(gMap.gl.drawingBufferWidth / gMap.tileSize + 2) *
467 Math.ceil(gMap.gl.drawingBufferHeight / gMap.tileSize + 2);
468 console.log("Keeping " + gMap.glTexturesPerZoomLevel + " textures per level");
470 if (Object.keys(gMap.glTextures).length > gMap.glTexturesPerZoomLevel) {
471 console.log("Cleaning textures... (have " + Object.keys(gMap.glTextures).length + " atm)");
473 // Find coordinate ranges for tiles to keep.
474 var tMin = normalizeCoords({x: Math.floor((gMap.pos.x - gMap.baseDim.wid / 2) / gMap.baseDim.tsize) - 1,
475 y: Math.floor((gMap.pos.y - gMap.baseDim.ht / 2) / gMap.baseDim.tsize) - 1,
477 var tMax = normalizeCoords({x: Math.ceil((gMap.pos.x + gMap.baseDim.wid / 2) / gMap.baseDim.tsize) + 1,
478 y: Math.ceil((gMap.pos.y + gMap.baseDim.ht / 2) / gMap.baseDim.tsize) + 1,
480 console.log("In range: " + tMin.x + "," + tMin.y + "," + tMin.z + " - " + tMax.x + "," + tMax.y + "," + tMax.z);
481 for (var tileKey in gMap.glTextures) {
482 var keyMatches = tileKey.match(/([^:]+)::(\d+),(\d+),(\d+)/);
483 if (keyMatches && keyMatches[1] != "loading") {
485 style: keyMatches[1],
491 if (txData.style != gMap.activeMap) { delTx = true; console.log("Different map style: " + txData.style); }
492 if (!delTx && (txData.z < tMin.z || txData.z > tMax.z)) { delTx = true; console.log("Out-of-range zoom: " + txData.z); }
493 if (tMin.x < tMax.x) {
494 if (!delTx && (txData.x < tMin.x || txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
497 // We are crossing over the 0 coordinate!
498 if (!delTx && (txData.x < tMin.x && txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); }
500 if (tMin.y < tMax.y) {
501 if (!delTx && (txData.y < tMin.y || txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
504 // We are crossing over the 0 coordinate!
505 if (!delTx && (txData.y < tMin.y && txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); }
508 // Delete texture from GL and from the array we are holding.
509 gMap.gl.deleteTexture(gMap.glTextures[tileKey]);
510 delete gMap.glTextures[tileKey];
514 console.log("Cleaning complete, " + Object.keys(gMap.glTextures).length + " textures left)");
515 //clearInterval(gMap.glTxCleanIntervalID);
520 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
521 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
524 if (gMap.pos.z < gMap.maxZoom) {
531 if (gMap.pos.z > 0) {
537 function zoomTo(aTargetLevel) {
538 aTargetLevel = parseInt(aTargetLevel);
539 if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) {
540 gMap.pos.z = aTargetLevel;
545 function gps2xy(aLatitude, aLongitude) {
546 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
547 var convLat = aLatitude * Math.PI / 180;
548 var rawY = (1 - Math.log(Math.tan(convLat) +
549 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
550 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
551 return {x: Math.round(rawX),
552 y: Math.round(rawY)};
555 function xy2gps(aX, aY) {
556 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
557 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
558 return {latitude: 180 / Math.PI *
559 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
560 longitude: aX / maxZoomFactor * 360 - 180};
563 function setMapStyle() {
564 var mapSel = document.getElementById("mapSelector");
565 if (mapSel.selectedIndex >= 0 && gMap.activeMap != mapSel.value) {
566 gMap.activeMap = mapSel.value;
567 document.getElementById("copyright").innerHTML =
568 gMapStyles[gMap.activeMap].copyright;
574 // A sane mod function that works for negative numbers.
577 return ((a % b) + b) % b;
580 function normalizeCoords(aCoords) {
581 var zoomFactor = Math.pow(2, aCoords.z);
582 return {x: mod(aCoords.x, zoomFactor),
583 y: mod(aCoords.y, zoomFactor),
587 function getTileKey(aStyle, aNormalizedCoords) {
588 return aStyle + "::" +
589 aNormalizedCoords.x + "," +
590 aNormalizedCoords.y + "," +
594 // Returns true if the tile is outside the current view.
595 function isOutsideWindow(t) {
596 var pos = decodeIndex(t);
598 var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z);
599 var wid = gMap.width * zoomFactor;
600 var ht = gMap.height * zoomFactor;
605 var sz = gMap.tileSize * zoomFactor;
606 if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 ||
607 pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2)
612 function encodeIndex(x, y, z) {
613 var norm = normalizeCoords({x: x, y: y, z: z});
614 return norm.x + "," + norm.y + "," + norm.z;
617 function decodeIndex(encodedIdx) {
618 var ind = encodedIdx.split(",", 3);
619 return {x: ind[0], y: ind[1], z: ind[2]};
622 function drawTrack() {
623 gLastDrawnPoint = null;
624 gCurPosMapCache = undefined;
625 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
627 for (var i = 0; i < gTrack.length; i++) {
628 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
629 (i + 1 >= gTrack.length));
634 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
635 var trackpoint = gps2xy(aLatitude, aLongitude);
636 // lastPoint is for optimizing (not actually executing the draw until the last)
637 trackpoint.optimized = (lastPoint === false);
638 var mappos = {x: Math.round((trackpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
639 y: Math.round((trackpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
641 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
642 gTrackContext.strokeStyle = gTrackColor;
643 gTrackContext.fillStyle = gTrackContext.strokeStyle;
644 gTrackContext.lineWidth = gTrackWidth;
645 gTrackContext.lineCap = "round";
646 gTrackContext.lineJoin = "round";
648 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
649 // This breaks optimiziation, so make sure to close path and reset optimization.
650 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
651 gTrackContext.stroke();
652 gTrackContext.beginPath();
653 trackpoint.optimized = false;
654 gTrackContext.arc(mappos.x, mappos.y,
655 gTrackContext.lineWidth, 0, Math.PI * 2, false);
656 gTrackContext.fill();
659 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
660 gTrackContext.beginPath();
661 gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
662 Math.round((gLastDrawnPoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2));
664 gTrackContext.lineTo(mappos.x, mappos.y);
665 if (!trackpoint.optimized)
666 gTrackContext.stroke();
668 gLastDrawnPoint = trackpoint;
671 function drawCurrentLocation(trackPoint) {
672 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
673 var circleRadius = Math.round(gCurLocSize / 2);
674 var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
675 y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
677 undrawCurrentLocation();
679 // Cache overdrawn area.
682 radius: circleRadius,
683 data: gTrackContext.getImageData(mappos.x - circleRadius,
684 mappos.y - circleRadius,
685 circleRadius * 2, circleRadius * 2)};
687 gTrackContext.strokeStyle = gCurLocColor;
688 gTrackContext.fillStyle = gTrackContext.strokeStyle;
689 gTrackContext.beginPath();
690 gTrackContext.arc(mappos.x, mappos.y,
691 circleRadius, 0, Math.PI * 2, false);
692 gTrackContext.fill();
695 function undrawCurrentLocation() {
696 if (gCurPosMapCache) {
697 var oldpoint = gCurPosMapCache.point;
698 var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
699 y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
700 gTrackContext.putImageData(gCurPosMapCache.data,
701 oldmp.x - gCurPosMapCache.radius,
702 oldmp.y - gCurPosMapCache.radius);
703 gCurPosMapCache = undefined;
708 handleEvent: function(aEvent) {
709 var touchEvent = aEvent.type.indexOf('touch') != -1;
712 aEvent.stopPropagation();
715 // Bail out if the event is happening on an input.
716 if (aEvent.target.tagName.toLowerCase() == "input")
719 // Bail out on unwanted map moves, but not zoom or keyboard events.
720 if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
721 // Bail out if this is neither a touch nor left-click.
722 if (!touchEvent && aEvent.button != 0)
725 // Bail out if the started touch can't be found.
726 if (touchEvent && gDragging &&
727 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
731 var coordObj = touchEvent ?
732 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
735 switch (aEvent.type) {
739 if (aEvent.targetTouches.length == 2) {
740 gPinchStartWidth = Math.sqrt(
741 Math.pow(aEvent.targetTouches.item(1).clientX -
742 aEvent.targetTouches.item(0).clientX, 2) +
743 Math.pow(aEvent.targetTouches.item(1).clientY -
744 aEvent.targetTouches.item(0).clientY, 2)
747 gDragTouchID = aEvent.changedTouches.item(0).identifier;
748 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
750 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
751 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
753 if (touchEvent || aEvent.button === 0) {
762 if (touchEvent && aEvent.targetTouches.length == 2) {
763 curPinchStartWidth = Math.sqrt(
764 Math.pow(aEvent.targetTouches.item(1).clientX -
765 aEvent.targetTouches.item(0).clientX, 2) +
766 Math.pow(aEvent.targetTouches.item(1).clientY -
767 aEvent.targetTouches.item(0).clientY, 2)
769 if (!gPinchStartWidth)
770 gPinchStartWidth = curPinchStartWidth;
772 if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
773 gPinchStartWidth / curPinchStartWidth < 0.6) {
774 var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
775 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
776 // Calculate new center of the map - preserve middle of pinch.
777 // This means that pixel distance between old center and middle
778 // must equal pixel distance of new center and middle.
779 var x = (aEvent.targetTouches.item(1).clientX +
780 aEvent.targetTouches.item(0).clientX) / 2 -
781 gGLMapCanvas.offsetLeft;
782 var y = (aEvent.targetTouches.item(1).clientY +
783 aEvent.targetTouches.item(0).clientY) / 2 -
784 gGLMapCanvas.offsetTop;
786 // Zoom factor after this action.
787 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
788 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
789 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
791 if (gPinchStartWidth < curPinchStartWidth)
796 // Reset pinch start width and start another pinch gesture.
797 gPinchStartWidth = null;
800 // If we are in a pinch, do not drag.
803 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
804 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
805 if (gDragging === true) {
806 var dX = x - gLastMouseX;
807 var dY = y - gLastMouseY;
808 gMap.pos.x -= dX * gMap.zoomFactor;
809 gMap.pos.y -= dY * gMap.zoomFactor;
818 gPinchStartWidth = null;
828 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
829 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
831 // Only accept (non-null) deltaY values
835 // Debug output: "coordinates" of the point the mouse was over.
837 var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor,
838 y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor};
839 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
840 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
841 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
842 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
843 pt2Coord.x + "/" + pt2Coord.y);
846 var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1);
847 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
848 // Calculate new center of the map - same point stays under the mouse.
849 // This means that the pixel distance between the old center and point
850 // must equal the pixel distance of the new center and that point.
851 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
852 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
854 // Zoom factor after this action.
855 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
856 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
857 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
859 if (aEvent.deltaY < 0)
866 // Allow keyboard control to move and zoom the map.
867 // Should use aEvent.key instead of aEvent.which but needs bug 680830.
868 // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
871 switch (aEvent.which) {
873 dX = -gMap.tileSize / 2;
876 dX = gMap.tileSize / 2;
879 dY = gMap.tileSize / 2;
882 dY = -gMap.tileSize / 2;
885 case 107: // + (numpad)
886 case 171: // + (normal key)
890 case 109: // - (numpad)
891 case 173: // - (normal key)
903 zoomTo(aEvent.which - 38);
908 case 96: // 0 (numpad)
909 case 97: // 1 (numpad)
910 case 98: // 2 (numpad)
911 case 99: // 3 (numpad)
912 case 100: // 4 (numpad)
913 case 101: // 5 (numpad)
914 case 102: // 6 (numpad)
915 case 103: // 7 (numpad)
916 case 104: // 8 (numpad)
917 zoomTo(aEvent.which - 86);
919 case 105: // 9 (numpad)
922 default: // not supported
923 console.log("key not supported: " + aEvent.which);
929 gMap.pos.x -= dX * gMap.zoomFactor;
930 gMap.pos.y -= dY * gMap.zoomFactor;
940 lastPos: {x: undefined, y: undefined},
941 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
942 this.tracking = true;
943 var watchCall = function() {
944 // calc new position in lat/lon degrees
945 // 90° on Earth surface are ~10,000 km at the equator,
946 // so try moving at most 10m at a time
947 if (geofake.lastPos.x)
948 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
950 geofake.lastPos.x = 48.208174
951 if (geofake.lastPos.y)
952 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
954 geofake.lastPos.y = 16.373819
955 aSuccessCallback({timestamp: Date.now(),
956 coords: {latitude: geofake.lastPos.x,
957 longitude: geofake.lastPos.y,
959 if (geofake.tracking)
960 setTimeout(watchCall, 1000);
962 setTimeout(watchCall, 1000);
965 clearWatch: function(aID) {
966 this.tracking = false;
970 function setCentering(aCheckbox) {
971 if (gMapPrefsLoaded && mainDB)
972 gPrefs.set("center_map", aCheckbox.checked);
973 gCenterPosition = aCheckbox.checked;
976 function setTracking(aCheckbox) {
977 if (gMapPrefsLoaded && mainDB)
978 gPrefs.set("tracking_enabled", aCheckbox.checked);
979 if (aCheckbox.checked)
985 function startTracking() {
987 gActionLabel.textContent = "Establishing Position";
988 gAction.style.display = "block";
989 gGeoWatchID = gGeolocation.watchPosition(
991 if (gActionLabel.textContent) {
992 gActionLabel.textContent = "";
993 gAction.style.display = "none";
995 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
996 var tPoint = {time: position.timestamp,
997 coords: {latitude: position.coords.latitude,
998 longitude: position.coords.longitude,
999 altitude: position.coords.altitude,
1000 accuracy: position.coords.accuracy,
1001 altitudeAccuracy: position.coords.altitudeAccuracy,
1002 heading: position.coords.heading,
1003 speed: position.coords.speed},
1004 beginSegment: !gLastTrackPoint};
1005 // Only add point to track is accuracy is good enough.
1006 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
1007 gLastTrackPoint = tPoint;
1008 gTrack.push(tPoint);
1009 try { gTrackStore.push(tPoint); } catch(e) {}
1010 var redrawn = false;
1011 if (gCenterPosition) {
1012 var posCoord = gps2xy(position.coords.latitude,
1013 position.coords.longitude);
1014 if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 ||
1015 Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) {
1016 gMap.pos.x = posCoord.x;
1017 gMap.pos.y = posCoord.y;
1018 gMap.draw(); // This draws the current point as well.
1023 undrawCurrentLocation();
1024 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
1026 drawCurrentLocation(tPoint);
1029 // Ignore erros for the moment, but this is good for debugging.
1030 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
1032 console.log(error.message);
1034 {enableHighAccuracy: true}
1039 function endTracking() {
1040 if (gActionLabel.textContent) {
1041 gActionLabel.textContent = "";
1042 gAction.style.display = "none";
1045 gGeolocation.clearWatch(gGeoWatchID);
1049 function clearTrack() {
1051 gTrackStore.clear();
1055 var gTileService = {
1056 objStore: "tilecache",
1058 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
1060 get: function(aStyle, aCoords, aCallback) {
1061 var norm = normalizeCoords(aCoords);
1062 var dbkey = getTileKey(aStyle, norm);
1063 this.getDBCache(dbkey, function(aResult, aEvent) {
1065 // We did get a cached object.
1066 aCallback(aResult.image, aStyle, aCoords, dbkey);
1067 // Look at the timestamp and return if it's not too old.
1068 if (aResult.timestamp + gTileService.ageLimit > Date.now())
1070 // Reload cached tile otherwise.
1071 var oldDate = new Date(aResult.timestamp);
1072 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
1074 // Retrieve image from the web and store it in the cache.
1075 var XHR = new XMLHttpRequest();
1077 gMapStyles[aStyle].url
1078 .replace("{x}", norm.x)
1079 .replace("{y}", norm.y)
1080 .replace("{z}", norm.z)
1081 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
1082 .replace("[1-4]", 1 + Math.floor(Math.random() * 3)),
1084 XHR.responseType = "blob";
1085 XHR.addEventListener("load", function () {
1086 if (XHR.status === 200) {
1087 var blob = XHR.response;
1088 aCallback(blob, aStyle, aCoords, dbkey);
1089 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
1096 getDBCache: function(aKey, aCallback) {
1099 var transaction = mainDB.transaction([this.objStore]);
1100 var request = transaction.objectStore(this.objStore).get(aKey);
1101 request.onsuccess = function(event) {
1102 aCallback(request.result, event);
1104 request.onerror = function(event) {
1105 // Errors can be handled here.
1106 aCallback(undefined, event);
1110 setDBCache: function(aKey, aValue, aCallback) {
1113 var success = false;
1114 var transaction = mainDB.transaction([this.objStore], "readwrite");
1115 var objStore = transaction.objectStore(this.objStore);
1116 var request = objStore.put(aValue, aKey);
1117 request.onsuccess = function(event) {
1120 aCallback(success, event);
1122 request.onerror = function(event) {
1123 // Errors can be handled here.
1125 aCallback(success, event);
1129 unsetDBCache: function(aKey, aCallback) {
1132 var success = false;
1133 var transaction = mainDB.transaction([this.objStore], "readwrite");
1134 var request = transaction.objectStore(this.objStore).delete(aKey);
1135 request.onsuccess = function(event) {
1138 aCallback(success, event);
1140 request.onerror = function(event) {
1141 // Errors can be handled here.
1143 aCallback(success, event);
1147 clearDB: function(aCallback) {
1150 var success = false;
1151 var transaction = mainDB.transaction([this.objStore], "readwrite");
1152 var request = transaction.objectStore(this.objStore).clear();
1153 request.onsuccess = function(event) {
1156 aCallback(success, event);
1158 request.onerror = function(event) {
1159 // Errors can be handled here.
1161 aCallback(success, event);