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 gCanvas.addEventListener("DOMMouseScroll", mapEvHandler, false);
128 gCanvas.addEventListener("mousewheel", mapEvHandler, false);
130 document.getElementById("copyright").innerHTML =
131 gMapStyles[gActiveMap].copyright;
133 gLoadingTile = new Image();
134 gLoadingTile.src = "style/loading.png";
137 function resizeAndDraw() {
138 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
139 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
141 var canvasWidth = viewportWidth - 2;
142 var canvasHeight = viewportHeight - 2;
143 gCanvas.style.position = "fixed";
144 gCanvas.width = canvasWidth;
145 gCanvas.height = canvasHeight;
150 if (gPos.z < gMaxZoom) {
163 function gps2xy(aLatitude, aLongitude) {
164 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
165 var convLat = aLatitude * Math.PI / 180;
166 var rawY = (1 - Math.log(Math.tan(convLat) +
167 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
168 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
169 return {x: Math.round(rawX),
170 y: Math.round(rawY)};
173 function xy2gps(aX, aY) {
174 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
175 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
176 return {latitude: 180 / Math.PI *
177 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
178 longitude: aX / maxZoomFactor * 360 - 180};
181 function setMapStyle() {
182 var mapSel = document.getElementById("mapSelector");
183 if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
184 gActiveMap = mapSel.value;
190 // A sane mod function that works for negative numbers.
193 return ((a % b) + b) % b;
196 function normaliseIndices(x, y, z) {
197 var zoomFactor = Math.pow(2, z);
198 return {x: mod(x, zoomFactor),
199 y: mod(y, zoomFactor),
203 function tileURL(x, y, z) {
204 var norm = normaliseIndices(x, y, z);
205 return gMapStyles[gActiveMap].url
206 .replace("{x}", norm.x)
207 .replace("{y}", norm.y)
208 .replace("{z}", norm.z)
209 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)));
212 // Returns true if the tile is outside the current view.
213 function isOutsideWindow(t) {
214 var pos = decodeIndex(t);
219 var zoomFactor = Math.pow(2, gMaxZoom - z);
220 var wid = gCanvas.width * zoomFactor;
221 var ht = gCanvas.height * zoomFactor;
226 var sz = gTileSize * zoomFactor;
227 if (x > gPos.x + wid / 2 || y > gPos.y + ht / 2 ||
228 x + sz < gPos.x - wid / 2 || y - sz < gPos.y - ht / 2)
233 function encodeIndex(x, y, z) {
234 var norm = normaliseIndices(x, y, z);
235 return norm.x + "," + norm.y + "," + norm.z;
238 function decodeIndex(encodedIdx) {
239 return encodedIdx.split(",", 3);
243 // Go through all the currently loaded tiles. If we don't want any of them remove them.
244 // for (t in gTiles) {
245 // if (isOutsideWindow(t))
248 document.getElementById("zoomLevel").textContent = gPos.z;
249 gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
250 var wid = gCanvas.width * gZoomFactor; // Width in level 18 pixels.
251 var ht = gCanvas.height * gZoomFactor; // Height in level 18 pixels.
252 var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
254 var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
255 var yMin = gPos.y - ht / 2;
256 var xMax = gPos.x + wid / 2;
257 var yMax = gPos.y + ht / 2;
259 if (gMapPrefsLoaded && mainDB)
260 gPrefs.set("position", gPos);
262 // Go through all the tiles we want.
263 // If any of them aren't loaded or being loaded, do so.
264 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
265 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) {
266 var xoff = (x * size - xMin) / gZoomFactor;
267 var yoff = (y * size - yMin) / gZoomFactor;
268 var tileKey = encodeIndex(x, y, gPos.z);
269 if (gTiles[tileKey] && gTiles[tileKey].complete) {
270 // Round here is **CRUCIAL** otherwise the images are filtered
271 // and the performance sucks (more than expected).
272 gContext.drawImage(gTiles[tileKey], Math.round(xoff), Math.round(yoff));
275 if (!gTiles[tileKey]) {
276 gTiles[tileKey] = new Image();
277 gTiles[tileKey].src = tileURL(x, y, gPos.z);
278 gTiles[tileKey].onload = function() {
279 // TODO: Just render this tile where it should be.
280 // context.drawImage(gTiles[tileKey], Math.round(xoff), Math.round(yoff)); // Doesn't work for some reason.
284 gContext.drawImage(gLoadingTile, Math.round(xoff), Math.round(yoff));
289 gLastDrawnPoint = null;
290 for (var i = 0; i < gTrack.length; i++) {
291 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
292 (i + 1 >= gTrack.length));
297 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
298 var trackpoint = gps2xy(aLatitude, aLongitude);
299 // lastPoint is for optimizing (not actually executing the draw until the last)
300 trackpoint.optimized = (lastPoint === false);
302 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
303 gContext.strokeStyle = "#FF0000";
304 gContext.fillStyle = gContext.strokeStyle;
305 gContext.lineWidth = 2;
306 gContext.lineCap = "round";
307 gContext.lineJoin = "round";
309 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
310 // This breaks optimiziation, so make sure to close path and reset optimization.
311 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
313 gContext.beginPath();
314 trackpoint.optimized = false;
315 gContext.arc(Math.round((trackpoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
316 Math.round((trackpoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2),
317 gContext.lineWidth, 0, Math.PI * 2, false);
321 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
322 gContext.beginPath();
323 gContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
324 Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2));
326 gContext.lineTo(Math.round((trackpoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
327 Math.round((trackpoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2));
328 if (!trackpoint.optimized)
331 gLastDrawnPoint = trackpoint;
335 handleEvent: function(aEvent) {
336 var touchEvent = aEvent.type.indexOf('touch') != -1;
338 // Bail out on unwanted map moves, but not zoom-changing events.
339 if (aEvent.type != "DOMMouseScroll" && aEvent.type != "mousewheel") {
340 // Bail out if this is neither a touch nor left-click.
341 if (!touchEvent && aEvent.button != 0)
344 // Bail out if the started touch can't be found.
345 if (touchEvent && gDragging &&
346 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
350 var coordObj = touchEvent ?
351 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
354 switch (aEvent.type) {
358 gDragTouchID = aEvent.changedTouches.item(0).identifier;
359 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
361 var x = coordObj.clientX - gCanvas.offsetLeft;
362 var y = coordObj.clientY - gCanvas.offsetTop;
364 if (touchEvent || aEvent.button === 0) {
372 var x = coordObj.clientX - gCanvas.offsetLeft;
373 var y = coordObj.clientY - gCanvas.offsetTop;
374 if (gDragging === true) {
375 var dX = x - gLastMouseX;
376 var dY = y - gLastMouseY;
377 gPos.x -= dX * gZoomFactor;
378 gPos.y -= dY * gZoomFactor;
393 case "DOMMouseScroll":
396 if (aEvent.wheelDelta) {
397 delta = aEvent.wheelDelta / 120;
401 else if (aEvent.detail) {
402 delta = -aEvent.detail / 3;
405 // Calculate new center of the map - same point stays under the mouse.
406 // This means that the pixel distance between the old center and point
407 // must equal the pixel distance of the new center and that point.
408 var x = coordObj.clientX - gCanvas.offsetLeft;
409 var y = coordObj.clientY - gCanvas.offsetTop;
410 // Debug output: "coordinates" of the point the mouse was over.
412 var ptCoord = {x: gPos.x + (x - gCanvas.width / 2) * gZoomFactor,
413 y: gPos.y + (x - gCanvas.height / 2) * gZoomFactor};
414 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
415 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
416 document.getElementById("debug").textContent =
417 ptCoord.x + "/" + ptCoord.y + " - " +
418 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
419 pt2Coord.x + "/" + pt2Coord.y;
421 // Zoom factor after this action.
422 var newZoomFactor = Math.pow(2, gMaxZoom - gPos.z + (delta > 0 ? -1 : 1));
423 gPos.x -= (x - gCanvas.width / 2) * (newZoomFactor - gZoomFactor);
424 gPos.y -= (y - gCanvas.height / 2) * (newZoomFactor - gZoomFactor);
437 lastPos: {x: undefined, y: undefined},
438 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
439 this.tracking = true;
440 var watchCall = function() {
441 // calc new position in lat/lon degrees
442 // 90° on Earth surface are ~10,000 km at the equator,
443 // so try moving at most 10m at a time
444 if (geofake.lastPos.x)
445 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
447 geofake.lastPos.x = 48.208174
448 if (geofake.lastPos.y)
449 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
451 geofake.lastPos.y = 16.373819
452 aSuccessCallback({timestamp: Date.now(),
453 coords: {latitude: geofake.lastPos.x,
454 longitude: geofake.lastPos.y,
456 if (geofake.tracking)
457 setTimeout(watchCall, 1000);
459 setTimeout(watchCall, 1000);
462 clearWatch: function(aID) {
463 this.tracking = false;
467 function setCentering(aCheckbox) {
468 if (gMapPrefsLoaded && mainDB)
469 gPrefs.set("center_map", aCheckbox.checked);
470 gCenterPosition = aCheckbox.checked;
473 function setTracking(aCheckbox) {
474 if (gMapPrefsLoaded && mainDB)
475 gPrefs.set("tracking_enabled", aCheckbox.checked);
476 if (aCheckbox.checked)
482 function startTracking() {
484 var getStoredTrack = function() {
486 gTrackStore.getList(function(aTPoints) {
488 document.getElementById("debug").textContent = aTPoints.length + " points loaded.";
489 if (aTPoints.length) {
494 setTimeout(getStoredTrack, 100);
501 gGeoWatchID = gGeolocation.watchPosition(
503 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
504 var tPoint = {time: position.timestamp,
505 coords: {latitude: position.coords.latitude,
506 longitude: position.coords.longitude,
507 altitude: position.coords.altitude,
508 accuracy: position.coords.accuracy,
509 altitudeAccuracy: position.coords.altitudeAccuracy,
510 heading: position.coords.heading,
511 speed: position.coords.speed},
512 beginSegment: !gLastTrackPoint};
513 gLastTrackPoint = tPoint;
515 try { gTrackStore.push(tPoint); } catch(e) {}
517 if (gCenterPosition) {
518 var posCoord = gps2xy(position.coords.latitude,
519 position.coords.longitude);
520 if (Math.abs(gPos.x - posCoord.x) > gCanvas.width * gZoomFactor / 4 ||
521 Math.abs(gPos.y - posCoord.y) > gCanvas.height * gZoomFactor / 4) {
524 drawMap(); // This draws the current point as well.
529 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
532 // Ignore erros for the moment, but this is good for debugging.
533 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
534 document.getElementById("debug").textContent = error.message;
536 {enableHighAccuracy: true}
541 function endTracking() {
543 gGeolocation.clearWatch(gGeoWatchID);
547 function clearTrack() {