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 gMapCanvas, gMapContext, 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 contexts. TODO: Remove 2D map once GL support works.
67 gMapCanvas = document.getElementById("map");
68 gMapContext = gMapCanvas.getContext("2d");
69 gGLMapCanvas = document.getElementById("glmap");
71 // Try to grab the standard context. If it fails, fallback to experimental.
72 // We also try to tell it we do not need a depth buffer.
73 gMap.gl = gGLMapCanvas.getContext("webgl", {depth: false}) ||
74 gGLMapCanvas.getContext("experimental-webgl", {depth: false});
77 // If we don't have a GL context, give up now
79 showGLWarningDialog();
82 gTrackCanvas = document.getElementById("track");
83 gTrackContext = gTrackCanvas.getContext("2d");
85 gMap.activeMap = "osm_mapnik";
89 gGeolocation = geofake;
90 var hiddenList = document.getElementsByClassName("debugHide");
91 // last to first - list of elements with that class is changing!
92 for (var i = hiddenList.length - 1; i >= 0; i--) {
93 hiddenList[i].classList.remove("debugHide");
97 gAction.addEventListener("prefload-done", gMap.initGL, false);
99 console.log("map vars set, loading prefs...");
103 function loadPrefs(aEvent) {
104 if (aEvent && aEvent.type == "prefs-step") {
105 console.log("wait: " + gWaitCounter);
106 if (gWaitCounter == 0) {
107 gAction.removeEventListener(aEvent.type, loadPrefs, false);
108 gMapPrefsLoaded = true;
109 console.log("prefs loaded.");
111 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
112 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
113 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
114 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
116 gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
117 gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
118 gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
119 gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
120 gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
122 gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
124 document.getElementById("body").addEventListener("keydown", mapEvHandler, false);
126 document.getElementById("copyright").innerHTML =
127 gMapStyles[gMap.activeMap].copyright;
129 gLoadingTile = new Image();
130 gLoadingTile.src = "style/loading.png";
131 gLoadingTile.onload = function() {
132 var throwEv = new CustomEvent("prefload-done");
133 gAction.dispatchEvent(throwEv);
139 gAction.removeEventListener(aEvent.type, loadPrefs, false);
140 gAction.addEventListener("prefs-step", loadPrefs, false);
142 gPrefs.get("position", function(aValue) {
147 var throwEv = new CustomEvent("prefs-step");
148 gAction.dispatchEvent(throwEv);
151 gPrefs.get("center_map", function(aValue) {
152 if (aValue === undefined)
153 document.getElementById("centerCheckbox").checked = true;
155 document.getElementById("centerCheckbox").checked = aValue;
156 setCentering(document.getElementById("centerCheckbox"));
158 var throwEv = new CustomEvent("prefs-step");
159 gAction.dispatchEvent(throwEv);
162 gPrefs.get("tracking_enabled", function(aValue) {
163 if (aValue === undefined)
164 document.getElementById("trackCheckbox").checked = true;
166 document.getElementById("trackCheckbox").checked = aValue;
168 var throwEv = new CustomEvent("prefs-step");
169 gAction.dispatchEvent(throwEv);
172 var trackLoadStarted = false;
173 var redrawBase = 100;
174 gTrackStore.getListStepped(function(aTPoint) {
176 // Add in front and return new length.
177 var tracklen = gTrack.unshift(aTPoint);
178 // Redraw track periodically, larger distance the longer it gets.
179 // Initial paint will do initial track drawing.
180 if (tracklen % redrawBase == 0) {
182 redrawBase = tracklen;
186 // Last point received.
189 if (!trackLoadStarted) {
190 // We have the most recent point, if present, rest will load async.
191 trackLoadStarted = true;
193 var throwEv = new CustomEvent("prefs-step");
194 gAction.dispatchEvent(throwEv);
202 glShaderProgram: null,
203 glVertexPositionAttr: null,
204 glTextureCoordAttr: null,
205 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 getVertShaderSource: function() {
219 return 'attribute vec2 aVertexPosition;\n' +
220 'attribute vec2 aTextureCoord;\n\n' +
221 'uniform vec2 uResolution;\n\n' +
222 'varying highp vec2 vTextureCoord;\n\n' +
223 'void main(void) {\n' +
224 // convert the rectangle from pixels to -1.0 to +1.0 (clipspace) 0.0 to 1.0
225 ' vec2 clipSpace = aVertexPosition * 2.0 / uResolution - 1.0;\n' +
226 ' gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' +
227 ' vTextureCoord = aTextureCoord;\n' +
229 getFragShaderSource:function() {
230 return 'varying highp vec2 vTextureCoord;\n\n' +
231 'uniform sampler2D uImage;\n\n' +
232 'void main(void) {\n' +
233 ' gl_FragColor = texture2D(uImage, vTextureCoord);\n' +
237 // When called from the event listener, the "this" reference doesn't work, so use the object name.
239 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
240 gMap.gl.clearColor(0.0, 0.0, 0.0, 0.5); // Set clear color to black, fully opaque.
241 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT|gMap.gl.DEPTH_BUFFER_BIT); // Clear the color.
243 // Create and initialize the shaders.
244 var vertShader = gMap.gl.createShader(gMap.gl.VERTEX_SHADER);
245 var fragShader = gMap.gl.createShader(gMap.gl.FRAGMENT_SHADER);
246 gMap.gl.shaderSource(vertShader, gMap.getVertShaderSource());
247 // Compile the shader program.
248 gMap.gl.compileShader(vertShader);
249 // See if it compiled successfully.
250 if (!gMap.gl.getShaderParameter(vertShader, gMap.gl.COMPILE_STATUS)) {
251 console.log("An error occurred compiling the vertex shader: " + gMap.gl.getShaderInfoLog(vertShader));
254 gMap.gl.shaderSource(fragShader, gMap.getFragShaderSource());
255 // Compile the shader program.
256 gMap.gl.compileShader(fragShader);
257 // See if it compiled successfully.
258 if (!gMap.gl.getShaderParameter(fragShader, gMap.gl.COMPILE_STATUS)) {
259 console.log("An error occurred compiling the fragment shader: " + gMap.gl.getShaderInfoLog(fragShader));
263 gMap.glShaderProgram = gMap.gl.createProgram();
264 gMap.gl.attachShader(gMap.glShaderProgram, vertShader);
265 gMap.gl.attachShader(gMap.glShaderProgram, fragShader);
266 gMap.gl.linkProgram(gMap.glShaderProgram);
267 // If creating the shader program failed, alert
268 if (!gMap.gl.getProgramParameter(gMap.glShaderProgram, gMap.gl.LINK_STATUS)) {
269 alert("Unable to initialize the shader program.");
271 gMap.gl.useProgram(gMap.glShaderProgram);
272 // Get locations of the attributes.
273 gMap.glVertexPositionAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aVertexPosition");
274 gMap.glTextureCoordAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aTextureCoord");
275 gMap.glResolutionAttr = gMap.gl.getUniformLocation(gMap.glShaderProgram, "uResolution");
277 var tileVerticesBuffer = gMap.gl.createBuffer();
278 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, tileVerticesBuffer);
279 // The vertices are the coordinates of the corner points of the square.
288 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(vertices), gMap.gl.STATIC_DRAW);
289 gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr);
290 gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0);
293 gMap.glMapTexture = gMap.gl.createTexture();
294 gMap.gl.activeTexture(gMap.gl.TEXTURE0);
295 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glMapTexture);
296 gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0);
297 // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two).
298 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST);
299 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST);
300 // Upload the image into the texture.
301 gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, gLoadingTile);
303 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
305 // Create a buffer for the position of the rectangle corners.
306 var mapVerticesTextureCoordBuffer = gMap.gl.createBuffer();
307 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer);
308 gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr);
309 gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0);
312 var throwEv = new CustomEvent("mapinit-done");
313 gAction.dispatchEvent(throwEv);
316 drawGLTest: function() {
317 if (!gMap.gl) { return; }
319 this.drawTileGL(5, 10);
320 this.drawTileGL(300, 20);
323 drawGL: function(aPixels, aOverdraw) {
324 if (!gMap.gl) { return; }
325 // aPixels is an object with left/right/top/bottom members telling how many
326 // pixels on the borders should actually be drawn.
327 // aOverdraw is a bool that tells if we should draw placeholders or draw
328 // straight over the existing content.
329 // XXX: Both those optimizations are OFF for GL right now!
331 aPixels = {left: gMap.gl.drawingBufferWidth, right: gMap.gl.drawingBufferWidth,
332 top: gMap.gl.drawingBufferHeight, bottom: gMap.gl.drawingBufferHeight};
336 document.getElementById("zoomLevel").textContent = gMap.pos.z;
337 gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
338 var wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor; // Width in level 18 pixels.
339 var ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor; // Height in level 18 pixels.
340 var size = gMap.tileSize * gMap.zoomFactor; // Tile size in level 18 pixels.
342 var xMin = gMap.pos.x - wid / 2; // Corners of the window in level 18 pixels.
343 var yMin = gMap.pos.y - ht / 2;
344 var xMax = gMap.pos.x + wid / 2;
345 var yMax = gMap.pos.y + ht / 2;
347 if (gMapPrefsLoaded && mainDB)
348 gPrefs.set("position", gMap.pos);
350 var tiles = {left: Math.ceil((xMin + aPixels.left * gMap.zoomFactor) / size) -
351 (aPixels.left ? 0 : 1),
352 right: Math.floor((xMax - aPixels.right * gMap.zoomFactor) / size) -
353 (aPixels.right ? 1 : 0),
354 top: Math.ceil((yMin + aPixels.top * gMap.zoomFactor) / size) -
355 (aPixels.top ? 0 : 1),
356 bottom: Math.floor((yMax - aPixels.bottom * gMap.zoomFactor) / size) -
357 (aPixels.bottom ? 1 : 0)};
359 // Go through all the tiles in the map, find out if to draw them and do so.
360 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
361 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
362 // Only go to the drawing step if we need to draw this tile.
363 if (x < tiles.left || x > tiles.right ||
364 y < tiles.top || y > tiles.bottom) {
365 // Round here is **CRUCIAL** otherwise the images are filtered
366 // and the performance sucks (more than expected).
367 var xoff = Math.round((x * size - xMin) / gMap.zoomFactor);
368 var yoff = Math.round((y * size - yMin) / gMap.zoomFactor);
369 // Draw placeholder tile unless we overdraw.
371 (x < tiles.left -1 || x > tiles.right + 1 ||
372 y < tiles.top -1 || y > tiles.bottom + 1))
373 gMap.drawTileGL(xoff, yoff);
375 // Initiate loading/drawing of the actual tile.
376 gTileService.get(gMap.activeMap, {x: x, y: y, z: gMap.pos.z},
377 function(aImage, aStyle, aCoords) {
378 // Only draw if this applies for the current view.
379 if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) {
380 var ixMin = gMap.pos.x - wid / 2;
381 var iyMin = gMap.pos.y - ht / 2;
382 var ixoff = Math.round((aCoords.x * size - ixMin) / gMap.zoomFactor);
383 var iyoff = Math.round((aCoords.y * size - iyMin) / gMap.zoomFactor);
384 var URL = window.URL;
385 var imgURL = URL.createObjectURL(aImage);
386 var imgObj = new Image();
388 imgObj.onload = function() {
389 gMapContext.drawImage(imgObj, ixoff, iyoff);
390 URL.revokeObjectURL(imgURL);
401 resizeAndDrawGL: function() {
402 if (!gMap.gl) { return; }
404 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
405 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT); // Clear the color.
406 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
411 drawTileGL: function(aLeft, aRight) {
413 var i_width = gMap.tileSize;
414 var y_start = aRight;
415 var i_height = gMap.tileSize;
416 var textureCoordinates = [
418 x_start + i_width, y_start,
419 x_start, y_start + i_height,
420 x_start, y_start + i_height,
421 x_start + i_width, y_start,
422 x_start + i_width, y_start + i_height,
424 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW);
425 // gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glMapTexture);
427 // There are 6 indices in textureCoordinates.
428 gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
432 function resizeAndDraw() {
433 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
434 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
435 if (gMapCanvas && gGLMapCanvas && gTrackCanvas) {
436 gMapCanvas.width = viewportWidth;
437 gMapCanvas.height = viewportHeight;
438 gGLMapCanvas.width = viewportWidth;
439 gGLMapCanvas.height = viewportHeight;
440 gTrackCanvas.width = viewportWidth;
441 gTrackCanvas.height = viewportHeight;
443 gMap.resizeAndDrawGL();
448 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
449 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
452 if (gMap.pos.z < gMap.maxZoom) {
459 if (gMap.pos.z > 0) {
465 function zoomTo(aTargetLevel) {
466 aTargetLevel = parseInt(aTargetLevel);
467 if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) {
468 gMap.pos.z = aTargetLevel;
473 function gps2xy(aLatitude, aLongitude) {
474 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
475 var convLat = aLatitude * Math.PI / 180;
476 var rawY = (1 - Math.log(Math.tan(convLat) +
477 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
478 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
479 return {x: Math.round(rawX),
480 y: Math.round(rawY)};
483 function xy2gps(aX, aY) {
484 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
485 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
486 return {latitude: 180 / Math.PI *
487 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
488 longitude: aX / maxZoomFactor * 360 - 180};
491 function setMapStyle() {
492 var mapSel = document.getElementById("mapSelector");
493 if (mapSel.selectedIndex >= 0 && gMap.activeMap != mapSel.value) {
494 gMap.activeMap = mapSel.value;
495 document.getElementById("copyright").innerHTML =
496 gMapStyles[gMap.activeMap].copyright;
502 // A sane mod function that works for negative numbers.
505 return ((a % b) + b) % b;
508 function normalizeCoords(aCoords) {
509 var zoomFactor = Math.pow(2, aCoords.z);
510 return {x: mod(aCoords.x, zoomFactor),
511 y: mod(aCoords.y, zoomFactor),
515 // Returns true if the tile is outside the current view.
516 function isOutsideWindow(t) {
517 var pos = decodeIndex(t);
519 var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z);
520 var wid = gMapCanvas.width * zoomFactor;
521 var ht = gMapCanvas.height * zoomFactor;
526 var sz = gMap.tileSize * zoomFactor;
527 if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 ||
528 pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2)
533 function encodeIndex(x, y, z) {
534 var norm = normalizeCoords({x: x, y: y, z: z});
535 return norm.x + "," + norm.y + "," + norm.z;
538 function decodeIndex(encodedIdx) {
539 var ind = encodedIdx.split(",", 3);
540 return {x: ind[0], y: ind[1], z: ind[2]};
543 function drawMap(aPixels, aOverdraw) {
544 gMap.drawGL(aPixels, aOverdraw);
545 // aPixels is an object with left/right/top/bottom members telling how many
546 // pixels on the borders should actually be drawn.
547 // aOverdraw is a bool that tells if we should draw placeholders or draw
548 // straight over the existing content.
550 aPixels = {left: gMapCanvas.width, right: gMapCanvas.width,
551 top: gMapCanvas.height, bottom: gMapCanvas.height};
555 document.getElementById("zoomLevel").textContent = gMap.pos.z;
556 gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
557 var wid = gMapCanvas.width * gMap.zoomFactor; // Width in level 18 pixels.
558 var ht = gMapCanvas.height * gMap.zoomFactor; // Height in level 18 pixels.
559 var size = gMap.tileSize * gMap.zoomFactor; // Tile size in level 18 pixels.
561 var xMin = gMap.pos.x - wid / 2; // Corners of the window in level 18 pixels.
562 var yMin = gMap.pos.y - ht / 2;
563 var xMax = gMap.pos.x + wid / 2;
564 var yMax = gMap.pos.y + ht / 2;
566 if (gMapPrefsLoaded && mainDB)
567 gPrefs.set("position", gMap.pos);
569 var tiles = {left: Math.ceil((xMin + aPixels.left * gMap.zoomFactor) / size) -
570 (aPixels.left ? 0 : 1),
571 right: Math.floor((xMax - aPixels.right * gMap.zoomFactor) / size) -
572 (aPixels.right ? 1 : 0),
573 top: Math.ceil((yMin + aPixels.top * gMap.zoomFactor) / size) -
574 (aPixels.top ? 0 : 1),
575 bottom: Math.floor((yMax - aPixels.bottom * gMap.zoomFactor) / size) -
576 (aPixels.bottom ? 1 : 0)};
578 // Go through all the tiles in the map, find out if to draw them and do so.
579 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
580 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
581 // Only go to the drawing step if we need to draw this tile.
582 if (x < tiles.left || x > tiles.right ||
583 y < tiles.top || y > tiles.bottom) {
584 // Round here is **CRUCIAL** otherwise the images are filtered
585 // and the performance sucks (more than expected).
586 var xoff = Math.round((x * size - xMin) / gMap.zoomFactor);
587 var yoff = Math.round((y * size - yMin) / gMap.zoomFactor);
588 // Draw placeholder tile unless we overdraw.
590 (x < tiles.left -1 || x > tiles.right + 1 ||
591 y < tiles.top -1 || y > tiles.bottom + 1))
592 gMapContext.drawImage(gLoadingTile, xoff, yoff);
594 // Initiate loading/drawing of the actual tile.
595 gTileService.get(gMap.activeMap, {x: x, y: y, z: gMap.pos.z},
596 function(aImage, aStyle, aCoords) {
597 // Only draw if this applies for the current view.
598 if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) {
599 var ixMin = gMap.pos.x - wid / 2;
600 var iyMin = gMap.pos.y - ht / 2;
601 var ixoff = Math.round((aCoords.x * size - ixMin) / gMap.zoomFactor);
602 var iyoff = Math.round((aCoords.y * size - iyMin) / gMap.zoomFactor);
603 var URL = window.URL;
604 var imgURL = URL.createObjectURL(aImage);
605 var imgObj = new Image();
607 imgObj.onload = function() {
608 gMapContext.drawImage(imgObj, ixoff, iyoff);
609 URL.revokeObjectURL(imgURL);
619 function drawTrack() {
620 gLastDrawnPoint = null;
621 gCurPosMapCache = undefined;
622 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
624 for (var i = 0; i < gTrack.length; i++) {
625 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
626 (i + 1 >= gTrack.length));
631 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
632 var trackpoint = gps2xy(aLatitude, aLongitude);
633 // lastPoint is for optimizing (not actually executing the draw until the last)
634 trackpoint.optimized = (lastPoint === false);
635 var mappos = {x: Math.round((trackpoint.x - gMap.pos.x) / gMap.zoomFactor + gMapCanvas.width / 2),
636 y: Math.round((trackpoint.y - gMap.pos.y) / gMap.zoomFactor + gMapCanvas.height / 2)};
638 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
639 gTrackContext.strokeStyle = gTrackColor;
640 gTrackContext.fillStyle = gTrackContext.strokeStyle;
641 gTrackContext.lineWidth = gTrackWidth;
642 gTrackContext.lineCap = "round";
643 gTrackContext.lineJoin = "round";
645 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
646 // This breaks optimiziation, so make sure to close path and reset optimization.
647 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
648 gTrackContext.stroke();
649 gTrackContext.beginPath();
650 trackpoint.optimized = false;
651 gTrackContext.arc(mappos.x, mappos.y,
652 gTrackContext.lineWidth, 0, Math.PI * 2, false);
653 gTrackContext.fill();
656 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
657 gTrackContext.beginPath();
658 gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gMap.pos.x) / gMap.zoomFactor + gMapCanvas.width / 2),
659 Math.round((gLastDrawnPoint.y - gMap.pos.y) / gMap.zoomFactor + gMapCanvas.height / 2));
661 gTrackContext.lineTo(mappos.x, mappos.y);
662 if (!trackpoint.optimized)
663 gTrackContext.stroke();
665 gLastDrawnPoint = trackpoint;
668 function drawCurrentLocation(trackPoint) {
669 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
670 var circleRadius = Math.round(gCurLocSize / 2);
671 var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMapCanvas.width / 2),
672 y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMapCanvas.height / 2)};
674 undrawCurrentLocation();
676 // Cache overdrawn area.
679 radius: circleRadius,
680 data: gTrackContext.getImageData(mappos.x - circleRadius,
681 mappos.y - circleRadius,
682 circleRadius * 2, circleRadius * 2)};
684 gTrackContext.strokeStyle = gCurLocColor;
685 gTrackContext.fillStyle = gTrackContext.strokeStyle;
686 gTrackContext.beginPath();
687 gTrackContext.arc(mappos.x, mappos.y,
688 circleRadius, 0, Math.PI * 2, false);
689 gTrackContext.fill();
692 function undrawCurrentLocation() {
693 if (gCurPosMapCache) {
694 var oldpoint = gCurPosMapCache.point;
695 var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMapCanvas.width / 2),
696 y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMapCanvas.height / 2)};
697 gTrackContext.putImageData(gCurPosMapCache.data,
698 oldmp.x - gCurPosMapCache.radius,
699 oldmp.y - gCurPosMapCache.radius);
700 gCurPosMapCache = undefined;
705 handleEvent: function(aEvent) {
706 var touchEvent = aEvent.type.indexOf('touch') != -1;
709 aEvent.stopPropagation();
712 // Bail out if the event is happening on an input.
713 if (aEvent.target.tagName.toLowerCase() == "input")
716 // Bail out on unwanted map moves, but not zoom or keyboard events.
717 if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
718 // Bail out if this is neither a touch nor left-click.
719 if (!touchEvent && aEvent.button != 0)
722 // Bail out if the started touch can't be found.
723 if (touchEvent && gDragging &&
724 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
728 var coordObj = touchEvent ?
729 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
732 switch (aEvent.type) {
736 if (aEvent.targetTouches.length == 2) {
737 gPinchStartWidth = Math.sqrt(
738 Math.pow(aEvent.targetTouches.item(1).clientX -
739 aEvent.targetTouches.item(0).clientX, 2) +
740 Math.pow(aEvent.targetTouches.item(1).clientY -
741 aEvent.targetTouches.item(0).clientY, 2)
744 gDragTouchID = aEvent.changedTouches.item(0).identifier;
745 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
747 var x = coordObj.clientX - gMapCanvas.offsetLeft;
748 var y = coordObj.clientY - gMapCanvas.offsetTop;
750 if (touchEvent || aEvent.button === 0) {
759 if (touchEvent && aEvent.targetTouches.length == 2) {
760 curPinchStartWidth = Math.sqrt(
761 Math.pow(aEvent.targetTouches.item(1).clientX -
762 aEvent.targetTouches.item(0).clientX, 2) +
763 Math.pow(aEvent.targetTouches.item(1).clientY -
764 aEvent.targetTouches.item(0).clientY, 2)
766 if (!gPinchStartWidth)
767 gPinchStartWidth = curPinchStartWidth;
769 if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
770 gPinchStartWidth / curPinchStartWidth < 0.6) {
771 var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
772 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
773 // Calculate new center of the map - preserve middle of pinch.
774 // This means that pixel distance between old center and middle
775 // must equal pixel distance of new center and middle.
776 var x = (aEvent.targetTouches.item(1).clientX +
777 aEvent.targetTouches.item(0).clientX) / 2 -
778 gMapCanvas.offsetLeft;
779 var y = (aEvent.targetTouches.item(1).clientY +
780 aEvent.targetTouches.item(0).clientY) / 2 -
781 gMapCanvas.offsetTop;
783 // Zoom factor after this action.
784 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
785 gMap.pos.x -= (x - gMapCanvas.width / 2) * (newZoomFactor - gMap.zoomFactor);
786 gMap.pos.y -= (y - gMapCanvas.height / 2) * (newZoomFactor - gMap.zoomFactor);
788 if (gPinchStartWidth < curPinchStartWidth)
793 // Reset pinch start width and start another pinch gesture.
794 gPinchStartWidth = null;
797 // If we are in a pinch, do not drag.
800 var x = coordObj.clientX - gMapCanvas.offsetLeft;
801 var y = coordObj.clientY - gMapCanvas.offsetTop;
802 if (gDragging === true) {
803 var dX = x - gLastMouseX;
804 var dY = y - gLastMouseY;
805 gMap.pos.x -= dX * gMap.zoomFactor;
806 gMap.pos.y -= dY * gMap.zoomFactor;
807 if (true) { // use optimized path
808 var mapData = gMapContext.getImageData(0, 0,
811 gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
812 gMapContext.putImageData(mapData, dX, dY);
813 drawMap({left: (dX > 0) ? dX : 0,
814 right: (dX < 0) ? -dX : 0,
815 top: (dY > 0) ? dY : 0,
816 bottom: (dY < 0) ? -dY : 0});
819 drawMap(false, true);
828 gPinchStartWidth = null;
838 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
839 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
841 // Only accept (non-null) deltaY values
845 // Debug output: "coordinates" of the point the mouse was over.
847 var ptCoord = {x: gMap.pos.x + (x - gMapCanvas.width / 2) * gMap.zoomFactor,
848 y: gMap.pos.y + (x - gMapCanvas.height / 2) * gMap.zoomFactor};
849 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
850 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
851 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
852 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
853 pt2Coord.x + "/" + pt2Coord.y);
856 var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1);
857 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
858 // Calculate new center of the map - same point stays under the mouse.
859 // This means that the pixel distance between the old center and point
860 // must equal the pixel distance of the new center and that point.
861 var x = coordObj.clientX - gMapCanvas.offsetLeft;
862 var y = coordObj.clientY - gMapCanvas.offsetTop;
864 // Zoom factor after this action.
865 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
866 gMap.pos.x -= (x - gMapCanvas.width / 2) * (newZoomFactor - gMap.zoomFactor);
867 gMap.pos.y -= (y - gMapCanvas.height / 2) * (newZoomFactor - gMap.zoomFactor);
869 if (aEvent.deltaY < 0)
876 // Allow keyboard control to move and zoom the map.
877 // Should use aEvent.key instead of aEvent.which but needs bug 680830.
878 // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
881 switch (aEvent.which) {
883 dX = -gMap.tileSize / 2;
886 dX = gMap.tileSize / 2;
889 dY = gMap.tileSize / 2;
892 dY = -gMap.tileSize / 2;
895 case 107: // + (numpad)
896 case 171: // + (normal key)
900 case 109: // - (numpad)
901 case 173: // - (normal key)
913 zoomTo(aEvent.which - 38);
918 case 96: // 0 (numpad)
919 case 97: // 1 (numpad)
920 case 98: // 2 (numpad)
921 case 99: // 3 (numpad)
922 case 100: // 4 (numpad)
923 case 101: // 5 (numpad)
924 case 102: // 6 (numpad)
925 case 103: // 7 (numpad)
926 case 104: // 8 (numpad)
927 zoomTo(aEvent.which - 86);
929 case 105: // 9 (numpad)
932 default: // not supported
933 console.log("key not supported: " + aEvent.which);
939 gMap.pos.x -= dX * gMap.zoomFactor;
940 gMap.pos.y -= dY * gMap.zoomFactor;
941 if (true) { // use optimized path
942 var mapData = gMapContext.getImageData(0, 0,
945 gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
946 gMapContext.putImageData(mapData, dX, dY);
947 drawMap({left: (dX > 0) ? dX : 0,
948 right: (dX < 0) ? -dX : 0,
949 top: (dY > 0) ? dY : 0,
950 bottom: (dY < 0) ? -dY : 0});
953 drawMap(false, true);
963 lastPos: {x: undefined, y: undefined},
964 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
965 this.tracking = true;
966 var watchCall = function() {
967 // calc new position in lat/lon degrees
968 // 90° on Earth surface are ~10,000 km at the equator,
969 // so try moving at most 10m at a time
970 if (geofake.lastPos.x)
971 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
973 geofake.lastPos.x = 48.208174
974 if (geofake.lastPos.y)
975 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
977 geofake.lastPos.y = 16.373819
978 aSuccessCallback({timestamp: Date.now(),
979 coords: {latitude: geofake.lastPos.x,
980 longitude: geofake.lastPos.y,
982 if (geofake.tracking)
983 setTimeout(watchCall, 1000);
985 setTimeout(watchCall, 1000);
988 clearWatch: function(aID) {
989 this.tracking = false;
993 function setCentering(aCheckbox) {
994 if (gMapPrefsLoaded && mainDB)
995 gPrefs.set("center_map", aCheckbox.checked);
996 gCenterPosition = aCheckbox.checked;
999 function setTracking(aCheckbox) {
1000 if (gMapPrefsLoaded && mainDB)
1001 gPrefs.set("tracking_enabled", aCheckbox.checked);
1002 if (aCheckbox.checked)
1008 function startTracking() {
1010 gActionLabel.textContent = "Establishing Position";
1011 gAction.style.display = "block";
1012 gGeoWatchID = gGeolocation.watchPosition(
1013 function(position) {
1014 if (gActionLabel.textContent) {
1015 gActionLabel.textContent = "";
1016 gAction.style.display = "none";
1018 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
1019 var tPoint = {time: position.timestamp,
1020 coords: {latitude: position.coords.latitude,
1021 longitude: position.coords.longitude,
1022 altitude: position.coords.altitude,
1023 accuracy: position.coords.accuracy,
1024 altitudeAccuracy: position.coords.altitudeAccuracy,
1025 heading: position.coords.heading,
1026 speed: position.coords.speed},
1027 beginSegment: !gLastTrackPoint};
1028 // Only add point to track is accuracy is good enough.
1029 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
1030 gLastTrackPoint = tPoint;
1031 gTrack.push(tPoint);
1032 try { gTrackStore.push(tPoint); } catch(e) {}
1033 var redrawn = false;
1034 if (gCenterPosition) {
1035 var posCoord = gps2xy(position.coords.latitude,
1036 position.coords.longitude);
1037 if (Math.abs(gMap.pos.x - posCoord.x) > gMapCanvas.width * gMap.zoomFactor / 4 ||
1038 Math.abs(gMap.pos.y - posCoord.y) > gMapCanvas.height * gMap.zoomFactor / 4) {
1039 gMap.pos.x = posCoord.x;
1040 gMap.pos.y = posCoord.y;
1041 drawMap(); // This draws the current point as well.
1046 undrawCurrentLocation();
1047 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
1049 drawCurrentLocation(tPoint);
1052 // Ignore erros for the moment, but this is good for debugging.
1053 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
1055 console.log(error.message);
1057 {enableHighAccuracy: true}
1062 function endTracking() {
1063 if (gActionLabel.textContent) {
1064 gActionLabel.textContent = "";
1065 gAction.style.display = "none";
1068 gGeolocation.clearWatch(gGeoWatchID);
1072 function clearTrack() {
1074 gTrackStore.clear();
1078 var gTileService = {
1079 objStore: "tilecache",
1081 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
1083 get: function(aStyle, aCoords, aCallback) {
1084 var norm = normalizeCoords(aCoords);
1085 var dbkey = aStyle + "::" + norm.x + "," + norm.y + "," + norm.z;
1086 this.getDBCache(dbkey, function(aResult, aEvent) {
1088 // We did get a cached object.
1089 aCallback(aResult.image, aStyle, aCoords);
1090 // Look at the timestamp and return if it's not too old.
1091 if (aResult.timestamp + gTileService.ageLimit > Date.now())
1093 // Reload cached tile otherwise.
1094 var oldDate = new Date(aResult.timestamp);
1095 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
1097 // Retrieve image from the web and store it in the cache.
1098 var XHR = new XMLHttpRequest();
1100 gMapStyles[aStyle].url
1101 .replace("{x}", norm.x)
1102 .replace("{y}", norm.y)
1103 .replace("{z}", norm.z)
1104 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
1105 .replace("[1-4]", 1 + Math.floor(Math.random() * 3)),
1107 XHR.responseType = "blob";
1108 XHR.addEventListener("load", function () {
1109 if (XHR.status === 200) {
1110 var blob = XHR.response;
1111 aCallback(blob, aStyle, aCoords);
1112 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
1119 getDBCache: function(aKey, aCallback) {
1122 var transaction = mainDB.transaction([this.objStore]);
1123 var request = transaction.objectStore(this.objStore).get(aKey);
1124 request.onsuccess = function(event) {
1125 aCallback(request.result, event);
1127 request.onerror = function(event) {
1128 // Errors can be handled here.
1129 aCallback(undefined, event);
1133 setDBCache: function(aKey, aValue, aCallback) {
1136 var success = false;
1137 var transaction = mainDB.transaction([this.objStore], "readwrite");
1138 var objStore = transaction.objectStore(this.objStore);
1139 var request = objStore.put(aValue, aKey);
1140 request.onsuccess = function(event) {
1143 aCallback(success, event);
1145 request.onerror = function(event) {
1146 // Errors can be handled here.
1148 aCallback(success, event);
1152 unsetDBCache: function(aKey, aCallback) {
1155 var success = false;
1156 var transaction = mainDB.transaction([this.objStore], "readwrite");
1157 var request = transaction.objectStore(this.objStore).delete(aKey);
1158 request.onsuccess = function(event) {
1161 aCallback(success, event);
1163 request.onerror = function(event) {
1164 // Errors can be handled here.
1166 aCallback(success, event);
1170 clearDB: function(aCallback) {
1173 var success = false;
1174 var transaction = mainDB.transaction([this.objStore], "readwrite");
1175 var request = transaction.objectStore(this.objStore).clear();
1176 request.onsuccess = function(event) {
1179 aCallback(success, event);
1181 request.onerror = function(event) {
1182 // Errors can be handled here.
1184 aCallback(success, event);