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://www.openstreetmap.org/copyright">ODbL/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://www.openstreetmap.org/copyright">ODbL/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://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
27 {name: "MapQuest OSM",
28 url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png",
29 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>.'},
31 {name: "MapQuest Open Aerial",
32 url: "http://oatile[1-4].mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg",
33 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.'},
35 {name: "OpenGeoServer Aerial",
36 url: "http://services.opengeoserver.org/tiles/1.0.0/globe.aerial_EPSG3857/{z}/{x}/{y}.png?origin=nw",
37 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>.'},
40 url: " http://mt1.google.com/vt/x={x}&y={y}&z={z}",
41 copyright: 'Map data and imagery © <a href="http://maps.google.com/">Google</a>'},
43 var gActiveMap = "osm_mapnik";
45 var gPos = {x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
46 y: 23670000.0, // The range is 0-67108864 (2^gMaxZoom * gTileSize)
47 z: 5}; // This could be fractional if supported being between zoom levels.
53 // Used as an associative array.
54 // The keys have to be strings, ours will be "xindex,yindex,zindex" e.g. "13,245,12".
58 var gMapPrefsLoaded = false;
60 var gDragging = false;
65 var gLastTrackPoint, gLastDrawnPoint;
66 var gCenterPosition = true;
69 gGeolocation = navigator.geolocation;
70 gCanvas = document.getElementById("map");
71 gContext = gCanvas.getContext("2d");
73 gActiveMap = "osm_mapnik";
77 gGeolocation = geofake;
78 var hiddenList = document.getElementsByClassName("debugHide");
79 // last to first - list of elements with that class is changing!
80 for (var i = hiddenList.length - 1; i >= 0; i--) {
81 hiddenList[i].classList.remove("debugHide");
86 var getPersistentPrefs = function() {
88 gPrefs.get("position", function(aValue) {
94 gPrefs.get("center_map", function(aValue) {
95 if (aValue === undefined)
96 document.getElementById("centerCheckbox").checked = true;
98 document.getElementById("centerCheckbox").checked = aValue;
99 setCentering(document.getElementById("centerCheckbox"));
101 gPrefs.get("tracking_enabled", function(aValue) {
102 if (aValue === undefined)
103 document.getElementById("trackCheckbox").checked = true;
105 document.getElementById("trackCheckbox").checked = aValue;
106 setTracking(document.getElementById("trackCheckbox"));
108 gMapPrefsLoaded = true;
111 setTimeout(getPersistentPrefs, 100);
114 gMapPrefsLoaded = true;
118 getPersistentPrefs();
120 gCanvas.addEventListener("mouseup", mapEvHandler, false);
121 gCanvas.addEventListener("mousemove", mapEvHandler, false);
122 gCanvas.addEventListener("mousedown", mapEvHandler, false);
123 gCanvas.addEventListener("mouseout", mapEvHandler, false);
125 gCanvas.addEventListener("touchstart", mapEvHandler, false);
126 gCanvas.addEventListener("touchmove", mapEvHandler, false);
127 gCanvas.addEventListener("touchend", mapEvHandler, false);
128 gCanvas.addEventListener("touchcancel", mapEvHandler, false);
129 gCanvas.addEventListener("touchleave", mapEvHandler, false);
131 // XXX deprecated? see https://groups.google.com/forum/?fromgroups#!topic/mozilla.dev.planning/kuhrORubaRY[1-25]
132 gCanvas.addEventListener("DOMMouseScroll", mapEvHandler, false);
133 gCanvas.addEventListener("mousewheel", mapEvHandler, false);
135 document.getElementById("copyright").innerHTML =
136 gMapStyles[gActiveMap].copyright;
138 gLoadingTile = new Image();
139 gLoadingTile.src = "style/loading.png";
142 function resizeAndDraw() {
143 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
144 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
146 var canvasWidth = viewportWidth - 2;
147 var canvasHeight = viewportHeight - 2;
148 gCanvas.style.position = "fixed";
149 gCanvas.width = canvasWidth;
150 gCanvas.height = canvasHeight;
156 if (gPos.z < gMaxZoom) {
169 function gps2xy(aLatitude, aLongitude) {
170 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
171 var convLat = aLatitude * Math.PI / 180;
172 var rawY = (1 - Math.log(Math.tan(convLat) +
173 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
174 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
175 return {x: Math.round(rawX),
176 y: Math.round(rawY)};
179 function xy2gps(aX, aY) {
180 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
181 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
182 return {latitude: 180 / Math.PI *
183 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
184 longitude: aX / maxZoomFactor * 360 - 180};
187 function setMapStyle() {
188 var mapSel = document.getElementById("mapSelector");
189 if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
190 gActiveMap = mapSel.value;
192 document.getElementById("copyright").innerHTML =
193 gMapStyles[gActiveMap].copyright;
199 // A sane mod function that works for negative numbers.
202 return ((a % b) + b) % b;
205 function normaliseIndices(x, y, z) {
206 var zoomFactor = Math.pow(2, z);
207 return {x: mod(x, zoomFactor),
208 y: mod(y, zoomFactor),
212 function tileURL(x, y, z) {
213 var norm = normaliseIndices(x, y, z);
214 return gMapStyles[gActiveMap].url
215 .replace("{x}", norm.x)
216 .replace("{y}", norm.y)
217 .replace("{z}", norm.z)
218 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
219 .replace("[1-4]", 1 + Math.floor(Math.random() * 3));
222 // Returns true if the tile is outside the current view.
223 function isOutsideWindow(t) {
224 var pos = decodeIndex(t);
229 var zoomFactor = Math.pow(2, gMaxZoom - z);
230 var wid = gCanvas.width * zoomFactor;
231 var ht = gCanvas.height * zoomFactor;
236 var sz = gTileSize * zoomFactor;
237 if (x > gPos.x + wid / 2 || y > gPos.y + ht / 2 ||
238 x + sz < gPos.x - wid / 2 || y - sz < gPos.y - ht / 2)
243 function encodeIndex(x, y, z) {
244 var norm = normaliseIndices(x, y, z);
245 return norm.x + "," + norm.y + "," + norm.z;
248 function decodeIndex(encodedIdx) {
249 return encodedIdx.split(",", 3);
253 // Go through all the currently loaded tiles. If we don't want any of them remove them.
254 // for (t in gTiles) {
255 // if (isOutsideWindow(t))
258 document.getElementById("zoomLevel").textContent = gPos.z;
259 gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
260 var wid = gCanvas.width * gZoomFactor; // Width in level 18 pixels.
261 var ht = gCanvas.height * gZoomFactor; // Height in level 18 pixels.
262 var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
264 var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
265 var yMin = gPos.y - ht / 2;
266 var xMax = gPos.x + wid / 2;
267 var yMax = gPos.y + ht / 2;
269 if (gMapPrefsLoaded && mainDB)
270 gPrefs.set("position", gPos);
272 // Go through all the tiles we want.
273 // If any of them aren't loaded or being loaded, do so.
274 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
275 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
276 var xoff = (x * size - xMin) / gZoomFactor;
277 var yoff = (y * size - yMin) / gZoomFactor;
278 var tileKey = encodeIndex(x, y, gPos.z);
279 if (gTiles[tileKey] && gTiles[tileKey].complete) {
280 // Round here is **CRUCIAL** otherwise the images are filtered
281 // and the performance sucks (more than expected).
282 gContext.drawImage(gTiles[tileKey], Math.round(xoff), Math.round(yoff));
285 if (!gTiles[tileKey]) {
286 gTiles[tileKey] = new Image();
287 gTiles[tileKey].src = tileURL(x, y, gPos.z);
288 gTiles[tileKey].onload = function() {
289 // TODO: Just render this tile where it should be.
290 // context.drawImage(gTiles[tileKey], Math.round(xoff), Math.round(yoff)); // Doesn't work for some reason.
294 gContext.drawImage(gLoadingTile, Math.round(xoff), Math.round(yoff));
299 gLastDrawnPoint = null;
300 for (var i = 0; i < gTrack.length; i++) {
301 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
302 (i + 1 >= gTrack.length));
307 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
308 var trackpoint = gps2xy(aLatitude, aLongitude);
309 // lastPoint is for optimizing (not actually executing the draw until the last)
310 trackpoint.optimized = (lastPoint === false);
312 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
313 gContext.strokeStyle = "#FF0000";
314 gContext.fillStyle = gContext.strokeStyle;
315 gContext.lineWidth = 2;
316 gContext.lineCap = "round";
317 gContext.lineJoin = "round";
319 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
320 // This breaks optimiziation, so make sure to close path and reset optimization.
321 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
323 gContext.beginPath();
324 trackpoint.optimized = false;
325 gContext.arc(Math.round((trackpoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
326 Math.round((trackpoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2),
327 gContext.lineWidth, 0, Math.PI * 2, false);
331 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
332 gContext.beginPath();
333 gContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
334 Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2));
336 gContext.lineTo(Math.round((trackpoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
337 Math.round((trackpoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2));
338 if (!trackpoint.optimized)
341 gLastDrawnPoint = trackpoint;
345 handleEvent: function(aEvent) {
346 var touchEvent = aEvent.type.indexOf('touch') != -1;
348 // Bail out on unwanted map moves, but not zoom-changing events.
349 if (aEvent.type != "DOMMouseScroll" && aEvent.type != "mousewheel") {
350 // Bail out if this is neither a touch nor left-click.
351 if (!touchEvent && aEvent.button != 0)
354 // Bail out if the started touch can't be found.
355 if (touchEvent && gDragging &&
356 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
360 var coordObj = touchEvent ?
361 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
364 switch (aEvent.type) {
368 gDragTouchID = aEvent.changedTouches.item(0).identifier;
369 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
371 var x = coordObj.clientX - gCanvas.offsetLeft;
372 var y = coordObj.clientY - gCanvas.offsetTop;
374 if (touchEvent || aEvent.button === 0) {
383 var x = coordObj.clientX - gCanvas.offsetLeft;
384 var y = coordObj.clientY - gCanvas.offsetTop;
385 if (gDragging === true) {
386 var dX = x - gLastMouseX;
387 var dY = y - gLastMouseY;
388 gPos.x -= dX * gZoomFactor;
389 gPos.y -= dY * gZoomFactor;
406 case "DOMMouseScroll":
409 if (aEvent.wheelDelta) {
410 delta = aEvent.wheelDelta / 120;
414 else if (aEvent.detail) {
415 delta = -aEvent.detail / 3;
418 // Calculate new center of the map - same point stays under the mouse.
419 // This means that the pixel distance between the old center and point
420 // must equal the pixel distance of the new center and that point.
421 var x = coordObj.clientX - gCanvas.offsetLeft;
422 var y = coordObj.clientY - gCanvas.offsetTop;
423 // Debug output: "coordinates" of the point the mouse was over.
425 var ptCoord = {x: gPos.x + (x - gCanvas.width / 2) * gZoomFactor,
426 y: gPos.y + (x - gCanvas.height / 2) * gZoomFactor};
427 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
428 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
429 document.getElementById("debug").textContent =
430 ptCoord.x + "/" + ptCoord.y + " - " +
431 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
432 pt2Coord.x + "/" + pt2Coord.y;
434 // Zoom factor after this action.
435 var newZoomFactor = Math.pow(2, gMaxZoom - gPos.z + (delta > 0 ? -1 : 1));
436 gPos.x -= (x - gCanvas.width / 2) * (newZoomFactor - gZoomFactor);
437 gPos.y -= (y - gCanvas.height / 2) * (newZoomFactor - gZoomFactor);
450 lastPos: {x: undefined, y: undefined},
451 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
452 this.tracking = true;
453 var watchCall = function() {
454 // calc new position in lat/lon degrees
455 // 90° on Earth surface are ~10,000 km at the equator,
456 // so try moving at most 10m at a time
457 if (geofake.lastPos.x)
458 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
460 geofake.lastPos.x = 48.208174
461 if (geofake.lastPos.y)
462 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
464 geofake.lastPos.y = 16.373819
465 aSuccessCallback({timestamp: Date.now(),
466 coords: {latitude: geofake.lastPos.x,
467 longitude: geofake.lastPos.y,
469 if (geofake.tracking)
470 setTimeout(watchCall, 1000);
472 setTimeout(watchCall, 1000);
475 clearWatch: function(aID) {
476 this.tracking = false;
480 function setCentering(aCheckbox) {
481 if (gMapPrefsLoaded && mainDB)
482 gPrefs.set("center_map", aCheckbox.checked);
483 gCenterPosition = aCheckbox.checked;
486 function setTracking(aCheckbox) {
487 if (gMapPrefsLoaded && mainDB)
488 gPrefs.set("tracking_enabled", aCheckbox.checked);
489 if (aCheckbox.checked)
495 function startTracking() {
497 var getStoredTrack = function() {
499 gTrackStore.getList(function(aTPoints) {
501 document.getElementById("debug").textContent = aTPoints.length + " points loaded.";
502 if (aTPoints.length) {
507 setTimeout(getStoredTrack, 100);
514 gGeoWatchID = gGeolocation.watchPosition(
516 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
517 var tPoint = {time: position.timestamp,
518 coords: {latitude: position.coords.latitude,
519 longitude: position.coords.longitude,
520 altitude: position.coords.altitude,
521 accuracy: position.coords.accuracy,
522 altitudeAccuracy: position.coords.altitudeAccuracy,
523 heading: position.coords.heading,
524 speed: position.coords.speed},
525 beginSegment: !gLastTrackPoint};
526 gLastTrackPoint = tPoint;
528 try { gTrackStore.push(tPoint); } catch(e) {}
530 if (gCenterPosition) {
531 var posCoord = gps2xy(position.coords.latitude,
532 position.coords.longitude);
533 if (Math.abs(gPos.x - posCoord.x) > gCanvas.width * gZoomFactor / 4 ||
534 Math.abs(gPos.y - posCoord.y) > gCanvas.height * gZoomFactor / 4) {
537 drawMap(); // This draws the current point as well.
542 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
545 // Ignore erros for the moment, but this is good for debugging.
546 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
547 document.getElementById("debug").textContent = error.message;
549 {enableHighAccuracy: true}
554 function endTracking() {
556 gGeolocation.clearWatch(gGeoWatchID);
560 function clearTrack() {