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 document.getElementById("copyright").innerHTML =
125 gMapStyles[gMap.activeMap].copyright;
127 gLoadingTile = new Image();
128 gLoadingTile.src = "style/loading.png";
129 gLoadingTile.onload = function() {
130 var throwEv = new CustomEvent("prefload-done");
131 gAction.dispatchEvent(throwEv);
137 gAction.removeEventListener(aEvent.type, loadPrefs, false);
138 gAction.addEventListener("prefs-step", loadPrefs, false);
140 gPrefs.get("position", function(aValue) {
141 if (aValue && aValue.x && aValue.y && aValue.z) {
145 var throwEv = new CustomEvent("prefs-step");
146 gAction.dispatchEvent(throwEv);
149 gPrefs.get("center_map", function(aValue) {
150 if (aValue === undefined)
151 document.getElementById("centerCheckbox").checked = true;
153 document.getElementById("centerCheckbox").checked = aValue;
154 setCentering(document.getElementById("centerCheckbox"));
156 var throwEv = new CustomEvent("prefs-step");
157 gAction.dispatchEvent(throwEv);
160 gPrefs.get("tracking_enabled", function(aValue) {
161 if (aValue === undefined)
162 document.getElementById("trackCheckbox").checked = true;
164 document.getElementById("trackCheckbox").checked = aValue;
166 var throwEv = new CustomEvent("prefs-step");
167 gAction.dispatchEvent(throwEv);
170 var trackLoadStarted = false;
171 var redrawBase = 100;
172 gTrackStore.getListStepped(function(aTPoint) {
174 // Add in front and return new length.
175 var tracklen = gTrack.unshift(aTPoint);
176 // Redraw track periodically, larger distance the longer it gets.
177 // Initial paint will do initial track drawing.
178 if (tracklen % redrawBase == 0) {
180 redrawBase = tracklen;
184 // Last point received.
187 if (!trackLoadStarted) {
188 // We have the most recent point, if present, rest will load async.
189 trackLoadStarted = true;
191 var throwEv = new CustomEvent("prefs-step");
192 gAction.dispatchEvent(throwEv);
200 glShaderProgram: null,
201 glVertexPositionAttr: null,
202 glTextureCoordAttr: null,
203 glResolutionAttr: null,
208 activeMap: "osm_mapnik",
210 maxZoom: 18, // The minimum is 0.
213 x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
214 y: 23670000.0, // The range is 0-67108864 (2^gMap.maxZoom * gMap.tileSize)
215 z: 5 // This could be fractional if supported being between zoom levels.
218 get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; },
219 get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; },
221 getVertShaderSource: function() {
222 return 'attribute vec2 aVertexPosition;\n' +
223 'attribute vec2 aTextureCoord;\n\n' +
224 'uniform vec2 uResolution;\n\n' +
225 'varying highp vec2 vTextureCoord;\n\n' +
226 'void main(void) {\n' +
227 // convert the rectangle from pixels to -1.0 to +1.0 (clipspace) 0.0 to 1.0
228 ' vec2 clipSpace = aVertexPosition * 2.0 / uResolution - 1.0;\n' +
229 ' gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' +
230 ' vTextureCoord = aTextureCoord;\n' +
232 getFragShaderSource:function() {
233 return 'varying highp vec2 vTextureCoord;\n\n' +
234 'uniform sampler2D uImage;\n\n' +
235 'void main(void) {\n' +
236 ' gl_FragColor = texture2D(uImage, vTextureCoord);\n' +
240 // When called from the event listener, the "this" reference doesn't work, so use the object name.
242 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
243 gMap.gl.clearColor(0.0, 0.0, 0.0, 0.5); // Set clear color to black, fully opaque.
244 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT|gMap.gl.DEPTH_BUFFER_BIT); // Clear the color.
246 // Create and initialize the shaders.
247 var vertShader = gMap.gl.createShader(gMap.gl.VERTEX_SHADER);
248 var fragShader = gMap.gl.createShader(gMap.gl.FRAGMENT_SHADER);
249 gMap.gl.shaderSource(vertShader, gMap.getVertShaderSource());
250 // Compile the shader program.
251 gMap.gl.compileShader(vertShader);
252 // See if it compiled successfully.
253 if (!gMap.gl.getShaderParameter(vertShader, gMap.gl.COMPILE_STATUS)) {
254 console.log("An error occurred compiling the vertex shader: " + gMap.gl.getShaderInfoLog(vertShader));
257 gMap.gl.shaderSource(fragShader, gMap.getFragShaderSource());
258 // Compile the shader program.
259 gMap.gl.compileShader(fragShader);
260 // See if it compiled successfully.
261 if (!gMap.gl.getShaderParameter(fragShader, gMap.gl.COMPILE_STATUS)) {
262 console.log("An error occurred compiling the fragment shader: " + gMap.gl.getShaderInfoLog(fragShader));
266 gMap.glShaderProgram = gMap.gl.createProgram();
267 gMap.gl.attachShader(gMap.glShaderProgram, vertShader);
268 gMap.gl.attachShader(gMap.glShaderProgram, fragShader);
269 gMap.gl.linkProgram(gMap.glShaderProgram);
270 // If creating the shader program failed, alert
271 if (!gMap.gl.getProgramParameter(gMap.glShaderProgram, gMap.gl.LINK_STATUS)) {
272 alert("Unable to initialize the shader program.");
274 gMap.gl.useProgram(gMap.glShaderProgram);
275 // Get locations of the attributes.
276 gMap.glVertexPositionAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aVertexPosition");
277 gMap.glTextureCoordAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aTextureCoord");
278 gMap.glResolutionAttr = gMap.gl.getUniformLocation(gMap.glShaderProgram, "uResolution");
280 var tileVerticesBuffer = gMap.gl.createBuffer();
281 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, tileVerticesBuffer);
282 // The vertices are the coordinates of the corner points of the square.
291 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(vertices), gMap.gl.STATIC_DRAW);
292 gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr);
293 gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0);
295 gMap.loadImageToTexture(gLoadingTile, 0, "loading::0,0,0");
297 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
299 // Create a buffer for the position of the rectangle corners.
300 var mapVerticesTextureCoordBuffer = gMap.gl.createBuffer();
301 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer);
302 gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr);
303 gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0);
306 var throwEv = new CustomEvent("mapinit-done");
307 gAction.dispatchEvent(throwEv);
310 draw: function(aPixels, aOverdraw) {
311 gMap.drawGL(aPixels, aOverdraw);
315 drawGL: function(aPixels, aOverdraw) {
316 if (!gMap.gl) { return; }
317 // aPixels is an object with left/right/top/bottom members telling how many
318 // pixels on the borders should actually be drawn.
319 // aOverdraw is a bool that tells if we should draw placeholders or draw
320 // straight over the existing content.
321 // XXX: Both those optimizations are OFF for GL right now!
323 aPixels = {left: gMap.gl.drawingBufferWidth, right: gMap.gl.drawingBufferWidth,
324 top: gMap.gl.drawingBufferHeight, bottom: gMap.gl.drawingBufferHeight};
328 document.getElementById("zoomLevel").textContent = gMap.pos.z;
329 gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
330 var wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor; // Width in level 18 pixels.
331 var ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor; // Height in level 18 pixels.
332 var size = gMap.tileSize * gMap.zoomFactor; // Tile size in level 18 pixels.
334 var xMin = gMap.pos.x - wid / 2; // Corners of the window in level 18 pixels.
335 var yMin = gMap.pos.y - ht / 2;
336 var xMax = gMap.pos.x + wid / 2;
337 var yMax = gMap.pos.y + ht / 2;
339 if (gMapPrefsLoaded && mainDB)
340 gPrefs.set("position", gMap.pos);
342 var tiles = {left: Math.ceil((xMin + aPixels.left * gMap.zoomFactor) / size) -
343 (aPixels.left ? 0 : 1),
344 right: Math.floor((xMax - aPixels.right * gMap.zoomFactor) / size) -
345 (aPixels.right ? 1 : 0),
346 top: Math.ceil((yMin + aPixels.top * gMap.zoomFactor) / size) -
347 (aPixels.top ? 0 : 1),
348 bottom: Math.floor((yMax - aPixels.bottom * gMap.zoomFactor) / size) -
349 (aPixels.bottom ? 1 : 0)};
351 // Go through all the tiles in the map, find out if to draw them and do so.
352 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
353 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
354 // Only go to the drawing step if we need to draw this tile.
355 if (x < tiles.left || x > tiles.right ||
356 y < tiles.top || y > tiles.bottom) {
357 // Round here is **CRUCIAL** otherwise the images are filtered
358 // and the performance sucks (more than expected).
359 var xoff = Math.round((x * size - xMin) / gMap.zoomFactor);
360 var yoff = Math.round((y * size - yMin) / gMap.zoomFactor);
361 // Draw placeholder tile unless we overdraw.
363 (x < tiles.left -1 || x > tiles.right + 1 ||
364 y < tiles.top -1 || y > tiles.bottom + 1)) {
365 gMap.drawTileGL(xoff, yoff, 0);
367 // Initiate loading/drawing of the actual tile.
368 gTileService.get(gMap.activeMap, {x: x, y: y, z: gMap.pos.z},
369 function(aImage, aStyle, aCoords, aTileKey) {
370 // Only draw if this applies for the current view.
371 if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) {
372 var ixMin = gMap.pos.x - wid / 2;
373 var iyMin = gMap.pos.y - ht / 2;
374 var ixoff = Math.round((aCoords.x * size - ixMin) / gMap.zoomFactor);
375 var iyoff = Math.round((aCoords.y * size - iyMin) / gMap.zoomFactor);
376 var URL = window.URL;
377 var imgURL = URL.createObjectURL(aImage);
378 var imgObj = new Image();
380 imgObj.onload = function() {
381 // TODO: Do actually paint in a separate function, called on requestAnimationFrame.
382 var txIndex = gMap.glTextureKeys[aTileKey];
384 txIndex = Object.keys(gMap.glTextureKeys).length;
385 gMap.loadImageToTexture(imgObj, txIndex, aTileKey);
387 gMap.drawTileGL(ixoff, iyoff, txIndex);
388 URL.revokeObjectURL(imgURL);
397 resizeAndDraw: function() {
398 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
399 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
400 if (gGLMapCanvas && gTrackCanvas) {
401 gGLMapCanvas.width = viewportWidth;
402 gGLMapCanvas.height = viewportHeight;
403 gTrackCanvas.width = viewportWidth;
404 gTrackCanvas.height = viewportHeight;
406 // Size viewport to canvas size.
407 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
409 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT);
410 // Make sure the vertex shader get the right resolution.
411 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
418 drawTileGL: function(aLeft, aRight, aTextureIndex) {
419 gMap.gl.activeTexture(gMap.gl.TEXTURE0 + aTextureIndex);
420 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTextureIndex]);
422 var i_width = gMap.tileSize;
423 var y_start = aRight;
424 var i_height = gMap.tileSize;
425 var textureCoordinates = [
427 x_start + i_width, y_start,
428 x_start, y_start + i_height,
429 x_start, y_start + i_height,
430 x_start + i_width, y_start,
431 x_start + i_width, y_start + i_height,
433 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW);
435 // There are 6 indices in textureCoordinates.
436 gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
439 loadImageToTexture: function(aImage, aTextureIndex, aTileKey) {
440 gMap.glTextureKeys[aTileKey] = aTextureIndex;
441 // Create and bind texture.
442 gMap.glTextures[aTextureIndex] = gMap.gl.createTexture();
443 gMap.gl.activeTexture(gMap.gl.TEXTURE0 + aTextureIndex);
444 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTextureIndex]);
445 gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0);
446 // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two).
447 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST);
448 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST);
449 // Upload the image into the texture.
450 gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage);
454 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
455 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
458 if (gMap.pos.z < gMap.maxZoom) {
465 if (gMap.pos.z > 0) {
471 function zoomTo(aTargetLevel) {
472 aTargetLevel = parseInt(aTargetLevel);
473 if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) {
474 gMap.pos.z = aTargetLevel;
479 function gps2xy(aLatitude, aLongitude) {
480 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
481 var convLat = aLatitude * Math.PI / 180;
482 var rawY = (1 - Math.log(Math.tan(convLat) +
483 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
484 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
485 return {x: Math.round(rawX),
486 y: Math.round(rawY)};
489 function xy2gps(aX, aY) {
490 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
491 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
492 return {latitude: 180 / Math.PI *
493 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
494 longitude: aX / maxZoomFactor * 360 - 180};
497 function setMapStyle() {
498 var mapSel = document.getElementById("mapSelector");
499 if (mapSel.selectedIndex >= 0 && gMap.activeMap != mapSel.value) {
500 gMap.activeMap = mapSel.value;
501 document.getElementById("copyright").innerHTML =
502 gMapStyles[gMap.activeMap].copyright;
508 // A sane mod function that works for negative numbers.
511 return ((a % b) + b) % b;
514 function normalizeCoords(aCoords) {
515 var zoomFactor = Math.pow(2, aCoords.z);
516 return {x: mod(aCoords.x, zoomFactor),
517 y: mod(aCoords.y, zoomFactor),
521 // Returns true if the tile is outside the current view.
522 function isOutsideWindow(t) {
523 var pos = decodeIndex(t);
525 var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z);
526 var wid = gMap.width * zoomFactor;
527 var ht = gMap.height * zoomFactor;
532 var sz = gMap.tileSize * zoomFactor;
533 if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 ||
534 pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2)
539 function encodeIndex(x, y, z) {
540 var norm = normalizeCoords({x: x, y: y, z: z});
541 return norm.x + "," + norm.y + "," + norm.z;
544 function decodeIndex(encodedIdx) {
545 var ind = encodedIdx.split(",", 3);
546 return {x: ind[0], y: ind[1], z: ind[2]};
549 function drawTrack() {
550 gLastDrawnPoint = null;
551 gCurPosMapCache = undefined;
552 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
554 for (var i = 0; i < gTrack.length; i++) {
555 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
556 (i + 1 >= gTrack.length));
561 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
562 var trackpoint = gps2xy(aLatitude, aLongitude);
563 // lastPoint is for optimizing (not actually executing the draw until the last)
564 trackpoint.optimized = (lastPoint === false);
565 var mappos = {x: Math.round((trackpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
566 y: Math.round((trackpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
568 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
569 gTrackContext.strokeStyle = gTrackColor;
570 gTrackContext.fillStyle = gTrackContext.strokeStyle;
571 gTrackContext.lineWidth = gTrackWidth;
572 gTrackContext.lineCap = "round";
573 gTrackContext.lineJoin = "round";
575 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
576 // This breaks optimiziation, so make sure to close path and reset optimization.
577 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
578 gTrackContext.stroke();
579 gTrackContext.beginPath();
580 trackpoint.optimized = false;
581 gTrackContext.arc(mappos.x, mappos.y,
582 gTrackContext.lineWidth, 0, Math.PI * 2, false);
583 gTrackContext.fill();
586 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
587 gTrackContext.beginPath();
588 gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
589 Math.round((gLastDrawnPoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2));
591 gTrackContext.lineTo(mappos.x, mappos.y);
592 if (!trackpoint.optimized)
593 gTrackContext.stroke();
595 gLastDrawnPoint = trackpoint;
598 function drawCurrentLocation(trackPoint) {
599 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
600 var circleRadius = Math.round(gCurLocSize / 2);
601 var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
602 y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
604 undrawCurrentLocation();
606 // Cache overdrawn area.
609 radius: circleRadius,
610 data: gTrackContext.getImageData(mappos.x - circleRadius,
611 mappos.y - circleRadius,
612 circleRadius * 2, circleRadius * 2)};
614 gTrackContext.strokeStyle = gCurLocColor;
615 gTrackContext.fillStyle = gTrackContext.strokeStyle;
616 gTrackContext.beginPath();
617 gTrackContext.arc(mappos.x, mappos.y,
618 circleRadius, 0, Math.PI * 2, false);
619 gTrackContext.fill();
622 function undrawCurrentLocation() {
623 if (gCurPosMapCache) {
624 var oldpoint = gCurPosMapCache.point;
625 var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
626 y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
627 gTrackContext.putImageData(gCurPosMapCache.data,
628 oldmp.x - gCurPosMapCache.radius,
629 oldmp.y - gCurPosMapCache.radius);
630 gCurPosMapCache = undefined;
635 handleEvent: function(aEvent) {
636 var touchEvent = aEvent.type.indexOf('touch') != -1;
639 aEvent.stopPropagation();
642 // Bail out if the event is happening on an input.
643 if (aEvent.target.tagName.toLowerCase() == "input")
646 // Bail out on unwanted map moves, but not zoom or keyboard events.
647 if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
648 // Bail out if this is neither a touch nor left-click.
649 if (!touchEvent && aEvent.button != 0)
652 // Bail out if the started touch can't be found.
653 if (touchEvent && gDragging &&
654 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
658 var coordObj = touchEvent ?
659 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
662 switch (aEvent.type) {
666 if (aEvent.targetTouches.length == 2) {
667 gPinchStartWidth = Math.sqrt(
668 Math.pow(aEvent.targetTouches.item(1).clientX -
669 aEvent.targetTouches.item(0).clientX, 2) +
670 Math.pow(aEvent.targetTouches.item(1).clientY -
671 aEvent.targetTouches.item(0).clientY, 2)
674 gDragTouchID = aEvent.changedTouches.item(0).identifier;
675 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
677 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
678 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
680 if (touchEvent || aEvent.button === 0) {
689 if (touchEvent && aEvent.targetTouches.length == 2) {
690 curPinchStartWidth = Math.sqrt(
691 Math.pow(aEvent.targetTouches.item(1).clientX -
692 aEvent.targetTouches.item(0).clientX, 2) +
693 Math.pow(aEvent.targetTouches.item(1).clientY -
694 aEvent.targetTouches.item(0).clientY, 2)
696 if (!gPinchStartWidth)
697 gPinchStartWidth = curPinchStartWidth;
699 if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
700 gPinchStartWidth / curPinchStartWidth < 0.6) {
701 var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
702 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
703 // Calculate new center of the map - preserve middle of pinch.
704 // This means that pixel distance between old center and middle
705 // must equal pixel distance of new center and middle.
706 var x = (aEvent.targetTouches.item(1).clientX +
707 aEvent.targetTouches.item(0).clientX) / 2 -
708 gGLMapCanvas.offsetLeft;
709 var y = (aEvent.targetTouches.item(1).clientY +
710 aEvent.targetTouches.item(0).clientY) / 2 -
711 gGLMapCanvas.offsetTop;
713 // Zoom factor after this action.
714 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
715 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
716 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
718 if (gPinchStartWidth < curPinchStartWidth)
723 // Reset pinch start width and start another pinch gesture.
724 gPinchStartWidth = null;
727 // If we are in a pinch, do not drag.
730 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
731 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
732 if (gDragging === true) {
733 var dX = x - gLastMouseX;
734 var dY = y - gLastMouseY;
735 gMap.pos.x -= dX * gMap.zoomFactor;
736 gMap.pos.y -= dY * gMap.zoomFactor;
737 if (false) { // use optimized path
738 /* TODO: investigate optimized path for GL - code below was 2D.
739 var mapData = gMapContext.getImageData(0, 0,
742 gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
743 gMapContext.putImageData(mapData, dX, dY);
744 gMap.draw({left: (dX > 0) ? dX : 0,
745 right: (dX < 0) ? -dX : 0,
746 top: (dY > 0) ? dY : 0,
747 bottom: (dY < 0) ? -dY : 0});
751 gMap.draw(false, true);
760 gPinchStartWidth = null;
770 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
771 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
773 // Only accept (non-null) deltaY values
777 // Debug output: "coordinates" of the point the mouse was over.
779 var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor,
780 y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor};
781 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
782 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
783 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
784 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
785 pt2Coord.x + "/" + pt2Coord.y);
788 var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1);
789 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
790 // Calculate new center of the map - same point stays under the mouse.
791 // This means that the pixel distance between the old center and point
792 // must equal the pixel distance of the new center and that point.
793 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
794 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
796 // Zoom factor after this action.
797 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
798 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
799 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
801 if (aEvent.deltaY < 0)
808 // Allow keyboard control to move and zoom the map.
809 // Should use aEvent.key instead of aEvent.which but needs bug 680830.
810 // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
813 switch (aEvent.which) {
815 dX = -gMap.tileSize / 2;
818 dX = gMap.tileSize / 2;
821 dY = gMap.tileSize / 2;
824 dY = -gMap.tileSize / 2;
827 case 107: // + (numpad)
828 case 171: // + (normal key)
832 case 109: // - (numpad)
833 case 173: // - (normal key)
845 zoomTo(aEvent.which - 38);
850 case 96: // 0 (numpad)
851 case 97: // 1 (numpad)
852 case 98: // 2 (numpad)
853 case 99: // 3 (numpad)
854 case 100: // 4 (numpad)
855 case 101: // 5 (numpad)
856 case 102: // 6 (numpad)
857 case 103: // 7 (numpad)
858 case 104: // 8 (numpad)
859 zoomTo(aEvent.which - 86);
861 case 105: // 9 (numpad)
864 default: // not supported
865 console.log("key not supported: " + aEvent.which);
871 gMap.pos.x -= dX * gMap.zoomFactor;
872 gMap.pos.y -= dY * gMap.zoomFactor;
873 if (false) { // use optimized path
874 /* TODO: investigate optimized path for GL - code below was 2D.
875 var mapData = gMapContext.getImageData(0, 0,
878 gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
879 gMapContext.putImageData(mapData, dX, dY);
880 gMap.draw({left: (dX > 0) ? dX : 0,
881 right: (dX < 0) ? -dX : 0,
882 top: (dY > 0) ? dY : 0,
883 bottom: (dY < 0) ? -dY : 0});
887 gMap.draw(false, true);
897 lastPos: {x: undefined, y: undefined},
898 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
899 this.tracking = true;
900 var watchCall = function() {
901 // calc new position in lat/lon degrees
902 // 90° on Earth surface are ~10,000 km at the equator,
903 // so try moving at most 10m at a time
904 if (geofake.lastPos.x)
905 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
907 geofake.lastPos.x = 48.208174
908 if (geofake.lastPos.y)
909 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
911 geofake.lastPos.y = 16.373819
912 aSuccessCallback({timestamp: Date.now(),
913 coords: {latitude: geofake.lastPos.x,
914 longitude: geofake.lastPos.y,
916 if (geofake.tracking)
917 setTimeout(watchCall, 1000);
919 setTimeout(watchCall, 1000);
922 clearWatch: function(aID) {
923 this.tracking = false;
927 function setCentering(aCheckbox) {
928 if (gMapPrefsLoaded && mainDB)
929 gPrefs.set("center_map", aCheckbox.checked);
930 gCenterPosition = aCheckbox.checked;
933 function setTracking(aCheckbox) {
934 if (gMapPrefsLoaded && mainDB)
935 gPrefs.set("tracking_enabled", aCheckbox.checked);
936 if (aCheckbox.checked)
942 function startTracking() {
944 gActionLabel.textContent = "Establishing Position";
945 gAction.style.display = "block";
946 gGeoWatchID = gGeolocation.watchPosition(
948 if (gActionLabel.textContent) {
949 gActionLabel.textContent = "";
950 gAction.style.display = "none";
952 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
953 var tPoint = {time: position.timestamp,
954 coords: {latitude: position.coords.latitude,
955 longitude: position.coords.longitude,
956 altitude: position.coords.altitude,
957 accuracy: position.coords.accuracy,
958 altitudeAccuracy: position.coords.altitudeAccuracy,
959 heading: position.coords.heading,
960 speed: position.coords.speed},
961 beginSegment: !gLastTrackPoint};
962 // Only add point to track is accuracy is good enough.
963 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
964 gLastTrackPoint = tPoint;
966 try { gTrackStore.push(tPoint); } catch(e) {}
968 if (gCenterPosition) {
969 var posCoord = gps2xy(position.coords.latitude,
970 position.coords.longitude);
971 if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 ||
972 Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) {
973 gMap.pos.x = posCoord.x;
974 gMap.pos.y = posCoord.y;
975 gMap.draw(); // This draws the current point as well.
980 undrawCurrentLocation();
981 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
983 drawCurrentLocation(tPoint);
986 // Ignore erros for the moment, but this is good for debugging.
987 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
989 console.log(error.message);
991 {enableHighAccuracy: true}
996 function endTracking() {
997 if (gActionLabel.textContent) {
998 gActionLabel.textContent = "";
999 gAction.style.display = "none";
1002 gGeolocation.clearWatch(gGeoWatchID);
1006 function clearTrack() {
1008 gTrackStore.clear();
1012 var gTileService = {
1013 objStore: "tilecache",
1015 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
1017 get: function(aStyle, aCoords, aCallback) {
1018 var norm = normalizeCoords(aCoords);
1019 var dbkey = aStyle + "::" + norm.x + "," + norm.y + "," + norm.z;
1020 this.getDBCache(dbkey, function(aResult, aEvent) {
1022 // We did get a cached object.
1023 aCallback(aResult.image, aStyle, aCoords, dbkey);
1024 // Look at the timestamp and return if it's not too old.
1025 if (aResult.timestamp + gTileService.ageLimit > Date.now())
1027 // Reload cached tile otherwise.
1028 var oldDate = new Date(aResult.timestamp);
1029 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
1031 // Retrieve image from the web and store it in the cache.
1032 var XHR = new XMLHttpRequest();
1034 gMapStyles[aStyle].url
1035 .replace("{x}", norm.x)
1036 .replace("{y}", norm.y)
1037 .replace("{z}", norm.z)
1038 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
1039 .replace("[1-4]", 1 + Math.floor(Math.random() * 3)),
1041 XHR.responseType = "blob";
1042 XHR.addEventListener("load", function () {
1043 if (XHR.status === 200) {
1044 var blob = XHR.response;
1045 aCallback(blob, aStyle, aCoords, dbkey);
1046 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
1053 getDBCache: function(aKey, aCallback) {
1056 var transaction = mainDB.transaction([this.objStore]);
1057 var request = transaction.objectStore(this.objStore).get(aKey);
1058 request.onsuccess = function(event) {
1059 aCallback(request.result, event);
1061 request.onerror = function(event) {
1062 // Errors can be handled here.
1063 aCallback(undefined, event);
1067 setDBCache: function(aKey, aValue, aCallback) {
1070 var success = false;
1071 var transaction = mainDB.transaction([this.objStore], "readwrite");
1072 var objStore = transaction.objectStore(this.objStore);
1073 var request = objStore.put(aValue, aKey);
1074 request.onsuccess = function(event) {
1077 aCallback(success, event);
1079 request.onerror = function(event) {
1080 // Errors can be handled here.
1082 aCallback(success, event);
1086 unsetDBCache: function(aKey, aCallback) {
1089 var success = false;
1090 var transaction = mainDB.transaction([this.objStore], "readwrite");
1091 var request = transaction.objectStore(this.objStore).delete(aKey);
1092 request.onsuccess = function(event) {
1095 aCallback(success, event);
1097 request.onerror = function(event) {
1098 // Errors can be handled here.
1100 aCallback(success, event);
1104 clearDB: function(aCallback) {
1107 var success = false;
1108 var transaction = mainDB.transaction([this.objStore], "readwrite");
1109 var request = transaction.objectStore(this.objStore).clear();
1110 request.onsuccess = function(event) {
1113 aCallback(success, event);
1115 request.onerror = function(event) {
1116 // Errors can be handled here.
1118 aCallback(success, event);