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;
151 if (gPos.z < gMaxZoom) {
164 function gps2xy(aLatitude, aLongitude) {
165 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
166 var convLat = aLatitude * Math.PI / 180;
167 var rawY = (1 - Math.log(Math.tan(convLat) +
168 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
169 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
170 return {x: Math.round(rawX),
171 y: Math.round(rawY)};
174 function xy2gps(aX, aY) {
175 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
176 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
177 return {latitude: 180 / Math.PI *
178 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
179 longitude: aX / maxZoomFactor * 360 - 180};
182 function setMapStyle() {
183 var mapSel = document.getElementById("mapSelector");
184 if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
185 gActiveMap = mapSel.value;
191 // A sane mod function that works for negative numbers.
194 return ((a % b) + b) % b;
197 function normaliseIndices(x, y, z) {
198 var zoomFactor = Math.pow(2, z);
199 return {x: mod(x, zoomFactor),
200 y: mod(y, zoomFactor),
204 function tileURL(x, y, z) {
205 var norm = normaliseIndices(x, y, z);
206 return gMapStyles[gActiveMap].url
207 .replace("{x}", norm.x)
208 .replace("{y}", norm.y)
209 .replace("{z}", norm.z)
210 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)));
213 // Returns true if the tile is outside the current view.
214 function isOutsideWindow(t) {
215 var pos = decodeIndex(t);
220 var zoomFactor = Math.pow(2, gMaxZoom - z);
221 var wid = gCanvas.width * zoomFactor;
222 var ht = gCanvas.height * zoomFactor;
227 var sz = gTileSize * zoomFactor;
228 if (x > gPos.x + wid / 2 || y > gPos.y + ht / 2 ||
229 x + sz < gPos.x - wid / 2 || y - sz < gPos.y - ht / 2)
234 function encodeIndex(x, y, z) {
235 var norm = normaliseIndices(x, y, z);
236 return norm.x + "," + norm.y + "," + norm.z;
239 function decodeIndex(encodedIdx) {
240 return encodedIdx.split(",", 3);
244 // Go through all the currently loaded tiles. If we don't want any of them remove them.
245 // for (t in gTiles) {
246 // if (isOutsideWindow(t))
249 document.getElementById("zoomLevel").textContent = gPos.z;
250 gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
251 var wid = gCanvas.width * gZoomFactor; // Width in level 18 pixels.
252 var ht = gCanvas.height * gZoomFactor; // Height in level 18 pixels.
253 var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
255 var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
256 var yMin = gPos.y - ht / 2;
257 var xMax = gPos.x + wid / 2;
258 var yMax = gPos.y + ht / 2;
260 if (gMapPrefsLoaded && mainDB)
261 gPrefs.set("position", gPos);
263 // Go through all the tiles we want.
264 // If any of them aren't loaded or being loaded, do so.
265 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
266 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) {
267 var xoff = (x * size - xMin) / gZoomFactor;
268 var yoff = (y * size - yMin) / gZoomFactor;
269 var tileKey = encodeIndex(x, y, gPos.z);
270 if (gTiles[tileKey] && gTiles[tileKey].complete) {
271 // Round here is **CRUCIAL** otherwise the images are filtered
272 // and the performance sucks (more than expected).
273 gContext.drawImage(gTiles[tileKey], Math.round(xoff), Math.round(yoff));
276 if (!gTiles[tileKey]) {
277 gTiles[tileKey] = new Image();
278 gTiles[tileKey].src = tileURL(x, y, gPos.z);
279 gTiles[tileKey].onload = function() {
280 // TODO: Just render this tile where it should be.
281 // context.drawImage(gTiles[tileKey], Math.round(xoff), Math.round(yoff)); // Doesn't work for some reason.
285 gContext.drawImage(gLoadingTile, Math.round(xoff), Math.round(yoff));
290 gLastDrawnPoint = null;
291 for (var i = 0; i < gTrack.length; i++) {
292 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
293 (i + 1 >= gTrack.length));
298 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
299 var trackpoint = gps2xy(aLatitude, aLongitude);
300 // lastPoint is for optimizing (not actually executing the draw until the last)
301 trackpoint.optimized = (lastPoint === false);
303 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
304 gContext.strokeStyle = "#FF0000";
305 gContext.fillStyle = gContext.strokeStyle;
306 gContext.lineWidth = 2;
307 gContext.lineCap = "round";
308 gContext.lineJoin = "round";
310 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
311 // This breaks optimiziation, so make sure to close path and reset optimization.
312 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
314 gContext.beginPath();
315 trackpoint.optimized = false;
316 gContext.arc(Math.round((trackpoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
317 Math.round((trackpoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2),
318 gContext.lineWidth, 0, Math.PI * 2, false);
322 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
323 gContext.beginPath();
324 gContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
325 Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2));
327 gContext.lineTo(Math.round((trackpoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
328 Math.round((trackpoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2));
329 if (!trackpoint.optimized)
332 gLastDrawnPoint = trackpoint;
336 handleEvent: function(aEvent) {
337 var touchEvent = aEvent.type.indexOf('touch') != -1;
339 // Bail out on unwanted map moves, but not zoom-changing events.
340 if (aEvent.type != "DOMMouseScroll" && aEvent.type != "mousewheel") {
341 // Bail out if this is neither a touch nor left-click.
342 if (!touchEvent && aEvent.button != 0)
345 // Bail out if the started touch can't be found.
346 if (touchEvent && gDragging &&
347 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
351 var coordObj = touchEvent ?
352 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
355 switch (aEvent.type) {
359 gDragTouchID = aEvent.changedTouches.item(0).identifier;
360 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
362 var x = coordObj.clientX - gCanvas.offsetLeft;
363 var y = coordObj.clientY - gCanvas.offsetTop;
365 if (touchEvent || aEvent.button === 0) {
373 var x = coordObj.clientX - gCanvas.offsetLeft;
374 var y = coordObj.clientY - gCanvas.offsetTop;
375 if (gDragging === true) {
376 var dX = x - gLastMouseX;
377 var dY = y - gLastMouseY;
378 gPos.x -= dX * gZoomFactor;
379 gPos.y -= dY * gZoomFactor;
394 case "DOMMouseScroll":
397 if (aEvent.wheelDelta) {
398 delta = aEvent.wheelDelta / 120;
402 else if (aEvent.detail) {
403 delta = -aEvent.detail / 3;
406 // Calculate new center of the map - same point stays under the mouse.
407 // This means that the pixel distance between the old center and point
408 // must equal the pixel distance of the new center and that point.
409 var x = coordObj.clientX - gCanvas.offsetLeft;
410 var y = coordObj.clientY - gCanvas.offsetTop;
411 // Debug output: "coordinates" of the point the mouse was over.
413 var ptCoord = {x: gPos.x + (x - gCanvas.width / 2) * gZoomFactor,
414 y: gPos.y + (x - gCanvas.height / 2) * gZoomFactor};
415 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
416 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
417 document.getElementById("debug").textContent =
418 ptCoord.x + "/" + ptCoord.y + " - " +
419 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
420 pt2Coord.x + "/" + pt2Coord.y;
422 // Zoom factor after this action.
423 var newZoomFactor = Math.pow(2, gMaxZoom - gPos.z + (delta > 0 ? -1 : 1));
424 gPos.x -= (x - gCanvas.width / 2) * (newZoomFactor - gZoomFactor);
425 gPos.y -= (y - gCanvas.height / 2) * (newZoomFactor - gZoomFactor);
438 lastPos: {x: undefined, y: undefined},
439 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
440 this.tracking = true;
441 var watchCall = function() {
442 // calc new position in lat/lon degrees
443 // 90° on Earth surface are ~10,000 km at the equator,
444 // so try moving at most 10m at a time
445 if (geofake.lastPos.x)
446 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
448 geofake.lastPos.x = 48.208174
449 if (geofake.lastPos.y)
450 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
452 geofake.lastPos.y = 16.373819
453 aSuccessCallback({timestamp: Date.now(),
454 coords: {latitude: geofake.lastPos.x,
455 longitude: geofake.lastPos.y,
457 if (geofake.tracking)
458 setTimeout(watchCall, 1000);
460 setTimeout(watchCall, 1000);
463 clearWatch: function(aID) {
464 this.tracking = false;
468 function setCentering(aCheckbox) {
469 if (gMapPrefsLoaded && mainDB)
470 gPrefs.set("center_map", aCheckbox.checked);
471 gCenterPosition = aCheckbox.checked;
474 function setTracking(aCheckbox) {
475 if (gMapPrefsLoaded && mainDB)
476 gPrefs.set("tracking_enabled", aCheckbox.checked);
477 if (aCheckbox.checked)
483 function startTracking() {
485 var getStoredTrack = function() {
487 gTrackStore.getList(function(aTPoints) {
489 document.getElementById("debug").textContent = aTPoints.length + " points loaded.";
490 if (aTPoints.length) {
495 setTimeout(getStoredTrack, 100);
502 gGeoWatchID = gGeolocation.watchPosition(
504 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
505 var tPoint = {time: position.timestamp,
506 coords: {latitude: position.coords.latitude,
507 longitude: position.coords.longitude,
508 altitude: position.coords.altitude,
509 accuracy: position.coords.accuracy,
510 altitudeAccuracy: position.coords.altitudeAccuracy,
511 heading: position.coords.heading,
512 speed: position.coords.speed},
513 beginSegment: !gLastTrackPoint};
514 gLastTrackPoint = tPoint;
516 try { gTrackStore.push(tPoint); } catch(e) {}
518 if (gCenterPosition) {
519 var posCoord = gps2xy(position.coords.latitude,
520 position.coords.longitude);
521 if (Math.abs(gPos.x - posCoord.x) > gCanvas.width * gZoomFactor / 4 ||
522 Math.abs(gPos.y - posCoord.y) > gCanvas.height * gZoomFactor / 4) {
525 drawMap(); // This draws the current point as well.
530 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
533 // Ignore erros for the moment, but this is good for debugging.
534 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
535 document.getElementById("debug").textContent = error.message;
537 {enableHighAccuracy: true}
542 function endTracking() {
544 gGeolocation.clearWatch(gGeoWatchID);
548 function clearTrack() {