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 gCanvas, gContext, gGeolocation;
9 var gMaxZoom = 18; // The minimum is 0.
12 // OSM tile usage policy: http://wiki.openstreetmap.org/wiki/Tile_usage_policy
13 // Find some more OSM ones at http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers
15 {name: "OpenStreetMap (Mapnik)",
16 url: "http://tile.openstreetmap.org/{z}/{x}/{y}.png",
17 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'},
19 {name: "Cycle Map (OSM)",
20 url: "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
21 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'},
23 {name: "Transport Map (OSM)",
24 url: "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png",
25 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'},
27 {name: "MapQuest OSM",
28 url: "http://otile1.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png",
29 copyright: 'Data, imagery and map information provided by MapQuest, <a href="http://www.openstreetmap.org/">OpenStreetMap</a> and contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>.'},
31 {name: "MapQuest Open Aerial",
32 url: "http://oatile1.mqcdn.com/naip/{z}/{x}/{y}.png",
33 copyright: 'Data, imagery and map information provided by MapQuest, <a href="http://www.openstreetmap.org/">OpenStreetMap</a> and contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>.'},
36 url: " http://mt1.google.com/vt/x={x}&y={y}&z={z}",
37 copyright: 'Map data and imagery © <a href="http://maps.google.com/">Google</a>'},
39 var gActiveMap = "osm_mapnik";
41 var gPos = {x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
42 y: 23670000.0, // The range is 0-67108864 (2^gMaxZoom * gTileSize)
43 z: 5}; // This could be fractional if supported being between zoom levels.
49 // Used as an associative array.
50 // The keys have to be strings, ours will be "xindex,yindex,zindex" e.g. "13,245,12".
54 var gMapPrefsLoaded = false;
56 var gDragging = false;
61 var gLastTrackPoint, gLastDrawnPoint;
62 var gCenterPosition = true;
65 gGeolocation = navigator.geolocation;
66 gCanvas = document.getElementById("map");
67 gContext = gCanvas.getContext("2d");
69 gActiveMap = "osm_mapnik";
73 gGeolocation = geofake;
74 var hiddenList = document.getElementsByClassName("debugHide");
75 // last to first - list of elements with that class is changing!
76 for (var i = hiddenList.length - 1; i >= 0; i--) {
77 hiddenList[i].classList.remove("debugHide");
82 var getPersistentPrefs = function() {
84 gPrefs.get("position", function(aValue) {
90 gPrefs.get("center_map", function(aValue) {
91 if (aValue === undefined)
92 document.getElementById("centerCheckbox").checked = true;
94 document.getElementById("centerCheckbox").checked = aValue;
95 setCentering(document.getElementById("centerCheckbox"));
97 gPrefs.get("tracking_enabled", function(aValue) {
98 if (aValue === undefined)
99 document.getElementById("trackCheckbox").checked = true;
101 document.getElementById("trackCheckbox").checked = aValue;
102 setTracking(document.getElementById("trackCheckbox"));
104 gMapPrefsLoaded = true;
107 setTimeout(getPersistentPrefs, 100);
110 gMapPrefsLoaded = true;
114 getPersistentPrefs();
116 gCanvas.addEventListener("mouseup", mapEvHandler, false);
117 gCanvas.addEventListener("mousemove", mapEvHandler, false);
118 gCanvas.addEventListener("mousedown", mapEvHandler, false);
119 gCanvas.addEventListener("mouseout", mapEvHandler, false);
121 gCanvas.addEventListener("touchstart", mapEvHandler, false);
122 gCanvas.addEventListener("touchmove", mapEvHandler, false);
123 gCanvas.addEventListener("touchend", mapEvHandler, false);
124 gCanvas.addEventListener("touchcancel", mapEvHandler, false);
125 gCanvas.addEventListener("touchleave", mapEvHandler, false);
127 // XXX deprecated? see https://groups.google.com/forum/?fromgroups#!topic/mozilla.dev.planning/kuhrORubaRY[1-25]
128 gCanvas.addEventListener("DOMMouseScroll", mapEvHandler, false);
129 gCanvas.addEventListener("mousewheel", mapEvHandler, false);
131 document.getElementById("copyright").innerHTML =
132 gMapStyles[gActiveMap].copyright;
134 gLoadingTile = new Image();
135 gLoadingTile.src = "style/loading.png";
138 function resizeAndDraw() {
139 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
140 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
142 var canvasWidth = viewportWidth - 2;
143 var canvasHeight = viewportHeight - 2;
144 gCanvas.style.position = "fixed";
145 gCanvas.width = canvasWidth;
146 gCanvas.height = canvasHeight;
152 if (gPos.z < gMaxZoom) {
165 function gps2xy(aLatitude, aLongitude) {
166 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
167 var convLat = aLatitude * Math.PI / 180;
168 var rawY = (1 - Math.log(Math.tan(convLat) +
169 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
170 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
171 return {x: Math.round(rawX),
172 y: Math.round(rawY)};
175 function xy2gps(aX, aY) {
176 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
177 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
178 return {latitude: 180 / Math.PI *
179 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
180 longitude: aX / maxZoomFactor * 360 - 180};
183 function setMapStyle() {
184 var mapSel = document.getElementById("mapSelector");
185 if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
186 gActiveMap = mapSel.value;
188 document.getElementById("copyright").innerHTML =
189 gMapStyles[gActiveMap].copyright;
194 // A sane mod function that works for negative numbers.
197 return ((a % b) + b) % b;
200 function normaliseIndices(x, y, z) {
201 var zoomFactor = Math.pow(2, z);
202 return {x: mod(x, zoomFactor),
203 y: mod(y, zoomFactor),
207 function tileURL(x, y, z) {
208 var norm = normaliseIndices(x, y, z);
209 return gMapStyles[gActiveMap].url
210 .replace("{x}", norm.x)
211 .replace("{y}", norm.y)
212 .replace("{z}", norm.z)
213 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)));
216 // Returns true if the tile is outside the current view.
217 function isOutsideWindow(t) {
218 var pos = decodeIndex(t);
223 var zoomFactor = Math.pow(2, gMaxZoom - z);
224 var wid = gCanvas.width * zoomFactor;
225 var ht = gCanvas.height * zoomFactor;
230 var sz = gTileSize * zoomFactor;
231 if (x > gPos.x + wid / 2 || y > gPos.y + ht / 2 ||
232 x + sz < gPos.x - wid / 2 || y - sz < gPos.y - ht / 2)
237 function encodeIndex(x, y, z) {
238 var norm = normaliseIndices(x, y, z);
239 return norm.x + "," + norm.y + "," + norm.z;
242 function decodeIndex(encodedIdx) {
243 return encodedIdx.split(",", 3);
247 // Go through all the currently loaded tiles. If we don't want any of them remove them.
248 // for (t in gTiles) {
249 // if (isOutsideWindow(t))
252 document.getElementById("zoomLevel").textContent = gPos.z;
253 gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
254 var wid = gCanvas.width * gZoomFactor; // Width in level 18 pixels.
255 var ht = gCanvas.height * gZoomFactor; // Height in level 18 pixels.
256 var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
258 var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
259 var yMin = gPos.y - ht / 2;
260 var xMax = gPos.x + wid / 2;
261 var yMax = gPos.y + ht / 2;
263 if (gMapPrefsLoaded && mainDB)
264 gPrefs.set("position", gPos);
266 // Go through all the tiles we want.
267 // If any of them aren't loaded or being loaded, do so.
268 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
269 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
270 var xoff = (x * size - xMin) / gZoomFactor;
271 var yoff = (y * size - yMin) / gZoomFactor;
272 var tileKey = encodeIndex(x, y, gPos.z);
273 if (gTiles[tileKey] && gTiles[tileKey].complete) {
274 // Round here is **CRUCIAL** otherwise the images are filtered
275 // and the performance sucks (more than expected).
276 gContext.drawImage(gTiles[tileKey], Math.round(xoff), Math.round(yoff));
279 if (!gTiles[tileKey]) {
280 gTiles[tileKey] = new Image();
281 gTiles[tileKey].src = tileURL(x, y, gPos.z);
282 gTiles[tileKey].onload = function() {
283 // TODO: Just render this tile where it should be.
284 // context.drawImage(gTiles[tileKey], Math.round(xoff), Math.round(yoff)); // Doesn't work for some reason.
288 gContext.drawImage(gLoadingTile, Math.round(xoff), Math.round(yoff));
293 gLastDrawnPoint = null;
294 for (var i = 0; i < gTrack.length; i++) {
295 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
296 (i + 1 >= gTrack.length));
301 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
302 var trackpoint = gps2xy(aLatitude, aLongitude);
303 // lastPoint is for optimizing (not actually executing the draw until the last)
304 trackpoint.optimized = (lastPoint === false);
306 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
307 gContext.strokeStyle = "#FF0000";
308 gContext.fillStyle = gContext.strokeStyle;
309 gContext.lineWidth = 2;
310 gContext.lineCap = "round";
311 gContext.lineJoin = "round";
313 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
314 // This breaks optimiziation, so make sure to close path and reset optimization.
315 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
317 gContext.beginPath();
318 trackpoint.optimized = false;
319 gContext.arc(Math.round((trackpoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
320 Math.round((trackpoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2),
321 gContext.lineWidth, 0, Math.PI * 2, false);
325 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
326 gContext.beginPath();
327 gContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
328 Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2));
330 gContext.lineTo(Math.round((trackpoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
331 Math.round((trackpoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2));
332 if (!trackpoint.optimized)
335 gLastDrawnPoint = trackpoint;
339 handleEvent: function(aEvent) {
340 var touchEvent = aEvent.type.indexOf('touch') != -1;
342 // Bail out on unwanted map moves, but not zoom-changing events.
343 if (aEvent.type != "DOMMouseScroll" && aEvent.type != "mousewheel") {
344 // Bail out if this is neither a touch nor left-click.
345 if (!touchEvent && aEvent.button != 0)
348 // Bail out if the started touch can't be found.
349 if (touchEvent && gDragging &&
350 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
354 var coordObj = touchEvent ?
355 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
358 switch (aEvent.type) {
362 gDragTouchID = aEvent.changedTouches.item(0).identifier;
363 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
365 var x = coordObj.clientX - gCanvas.offsetLeft;
366 var y = coordObj.clientY - gCanvas.offsetTop;
368 if (touchEvent || aEvent.button === 0) {
377 var x = coordObj.clientX - gCanvas.offsetLeft;
378 var y = coordObj.clientY - gCanvas.offsetTop;
379 if (gDragging === true) {
380 var dX = x - gLastMouseX;
381 var dY = y - gLastMouseY;
382 gPos.x -= dX * gZoomFactor;
383 gPos.y -= dY * gZoomFactor;
400 case "DOMMouseScroll":
403 if (aEvent.wheelDelta) {
404 delta = aEvent.wheelDelta / 120;
408 else if (aEvent.detail) {
409 delta = -aEvent.detail / 3;
412 // Calculate new center of the map - same point stays under the mouse.
413 // This means that the pixel distance between the old center and point
414 // must equal the pixel distance of the new center and that point.
415 var x = coordObj.clientX - gCanvas.offsetLeft;
416 var y = coordObj.clientY - gCanvas.offsetTop;
417 // Debug output: "coordinates" of the point the mouse was over.
419 var ptCoord = {x: gPos.x + (x - gCanvas.width / 2) * gZoomFactor,
420 y: gPos.y + (x - gCanvas.height / 2) * gZoomFactor};
421 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
422 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
423 document.getElementById("debug").textContent =
424 ptCoord.x + "/" + ptCoord.y + " - " +
425 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
426 pt2Coord.x + "/" + pt2Coord.y;
428 // Zoom factor after this action.
429 var newZoomFactor = Math.pow(2, gMaxZoom - gPos.z + (delta > 0 ? -1 : 1));
430 gPos.x -= (x - gCanvas.width / 2) * (newZoomFactor - gZoomFactor);
431 gPos.y -= (y - gCanvas.height / 2) * (newZoomFactor - gZoomFactor);
444 lastPos: {x: undefined, y: undefined},
445 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
446 this.tracking = true;
447 var watchCall = function() {
448 // calc new position in lat/lon degrees
449 // 90° on Earth surface are ~10,000 km at the equator,
450 // so try moving at most 10m at a time
451 if (geofake.lastPos.x)
452 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
454 geofake.lastPos.x = 48.208174
455 if (geofake.lastPos.y)
456 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
458 geofake.lastPos.y = 16.373819
459 aSuccessCallback({timestamp: Date.now(),
460 coords: {latitude: geofake.lastPos.x,
461 longitude: geofake.lastPos.y,
463 if (geofake.tracking)
464 setTimeout(watchCall, 1000);
466 setTimeout(watchCall, 1000);
469 clearWatch: function(aID) {
470 this.tracking = false;
474 function setCentering(aCheckbox) {
475 if (gMapPrefsLoaded && mainDB)
476 gPrefs.set("center_map", aCheckbox.checked);
477 gCenterPosition = aCheckbox.checked;
480 function setTracking(aCheckbox) {
481 if (gMapPrefsLoaded && mainDB)
482 gPrefs.set("tracking_enabled", aCheckbox.checked);
483 if (aCheckbox.checked)
489 function startTracking() {
491 var getStoredTrack = function() {
493 gTrackStore.getList(function(aTPoints) {
495 document.getElementById("debug").textContent = aTPoints.length + " points loaded.";
496 if (aTPoints.length) {
501 setTimeout(getStoredTrack, 100);
508 gGeoWatchID = gGeolocation.watchPosition(
510 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
511 var tPoint = {time: position.timestamp,
512 coords: {latitude: position.coords.latitude,
513 longitude: position.coords.longitude,
514 altitude: position.coords.altitude,
515 accuracy: position.coords.accuracy,
516 altitudeAccuracy: position.coords.altitudeAccuracy,
517 heading: position.coords.heading,
518 speed: position.coords.speed},
519 beginSegment: !gLastTrackPoint};
520 gLastTrackPoint = tPoint;
522 try { gTrackStore.push(tPoint); } catch(e) {}
524 if (gCenterPosition) {
525 var posCoord = gps2xy(position.coords.latitude,
526 position.coords.longitude);
527 if (Math.abs(gPos.x - posCoord.x) > gCanvas.width * gZoomFactor / 4 ||
528 Math.abs(gPos.y - posCoord.y) > gCanvas.height * gZoomFactor / 4) {
531 drawMap(); // This draws the current point as well.
536 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
539 // Ignore erros for the moment, but this is good for debugging.
540 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
541 document.getElementById("debug").textContent = error.message;
543 {enableHighAccuracy: true}
548 function endTracking() {
550 gGeolocation.clearWatch(gGeoWatchID);
554 function clearTrack() {