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.
11 var gMinTrackAccuracy = 1000; // meters
12 var gTrackWidth = 2; // pixels
13 var gTrackColor = "#FF0000";
14 var gCurLocSize = 5; // pixels
15 var gCurLocColor = "#800000";
18 // OSM tile usage policy: http://wiki.openstreetmap.org/wiki/Tile_usage_policy
19 // Find some more OSM ones at http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers
21 {name: "OpenStreetMap (Mapnik)",
22 url: "http://tile.openstreetmap.org/{z}/{x}/{y}.png",
23 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>'},
25 {name: "Cycle Map (OSM)",
26 url: "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
27 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>'},
29 {name: "Transport Map (OSM)",
30 url: "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png",
31 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>'},
33 {name: "MapQuest OSM",
34 url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png",
35 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>.'},
37 {name: "MapQuest Open Aerial",
38 url: "http://oatile[1-4].mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg",
39 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.'},
41 {name: "OpenGeoServer Aerial",
42 url: "http://services.opengeoserver.org/tiles/1.0.0/globe.aerial_EPSG3857/{z}/{x}/{y}.png?origin=nw",
43 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>.'},
46 url: " http://mt1.google.com/vt/x={x}&y={y}&z={z}",
47 copyright: 'Map data and imagery © <a href="http://maps.google.com/">Google</a>'},
49 var gActiveMap = "osm_mapnik";
51 var gPos = {x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
52 y: 23670000.0, // The range is 0-67108864 (2^gMaxZoom * gTileSize)
53 z: 5}; // This could be fractional if supported being between zoom levels.
59 // Used as an associative array.
60 // The keys have to be strings, ours will be "xindex,yindex,zindex" e.g. "13,245,12".
64 var gMapPrefsLoaded = false;
66 var gDragging = false;
71 var gLastTrackPoint, gLastDrawnPoint;
72 var gCenterPosition = true;
77 gGeolocation = navigator.geolocation;
78 gCanvas = document.getElementById("map");
79 gContext = gCanvas.getContext("2d");
81 gActiveMap = "osm_mapnik";
85 gGeolocation = geofake;
86 var hiddenList = document.getElementsByClassName("debugHide");
87 // last to first - list of elements with that class is changing!
88 for (var i = hiddenList.length - 1; i >= 0; i--) {
89 hiddenList[i].classList.remove("debugHide");
94 var getPersistentPrefs = function() {
96 gPrefs.get("position", function(aValue) {
102 gPrefs.get("center_map", function(aValue) {
103 if (aValue === undefined)
104 document.getElementById("centerCheckbox").checked = true;
106 document.getElementById("centerCheckbox").checked = aValue;
107 setCentering(document.getElementById("centerCheckbox"));
109 gPrefs.get("tracking_enabled", function(aValue) {
110 if (aValue === undefined)
111 document.getElementById("trackCheckbox").checked = true;
113 document.getElementById("trackCheckbox").checked = aValue;
114 setTracking(document.getElementById("trackCheckbox"));
116 gMapPrefsLoaded = true;
119 setTimeout(getPersistentPrefs, 100);
122 gMapPrefsLoaded = true;
126 getPersistentPrefs();
128 gCanvas.addEventListener("mouseup", mapEvHandler, false);
129 gCanvas.addEventListener("mousemove", mapEvHandler, false);
130 gCanvas.addEventListener("mousedown", mapEvHandler, false);
131 gCanvas.addEventListener("mouseout", mapEvHandler, false);
133 gCanvas.addEventListener("touchstart", mapEvHandler, false);
134 gCanvas.addEventListener("touchmove", mapEvHandler, false);
135 gCanvas.addEventListener("touchend", mapEvHandler, false);
136 gCanvas.addEventListener("touchcancel", mapEvHandler, false);
137 gCanvas.addEventListener("touchleave", mapEvHandler, false);
139 // XXX deprecated? see https://groups.google.com/forum/?fromgroups#!topic/mozilla.dev.planning/kuhrORubaRY[1-25]
140 gCanvas.addEventListener("DOMMouseScroll", mapEvHandler, false);
141 gCanvas.addEventListener("mousewheel", mapEvHandler, false);
143 document.getElementById("copyright").innerHTML =
144 gMapStyles[gActiveMap].copyright;
146 gLoadingTile = new Image();
147 gLoadingTile.src = "style/loading.png";
150 function resizeAndDraw() {
151 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
152 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
154 var canvasWidth = viewportWidth - 2;
155 var canvasHeight = viewportHeight - 2;
156 gCanvas.style.position = "fixed";
157 gCanvas.width = canvasWidth;
158 gCanvas.height = canvasHeight;
164 if (gPos.z < gMaxZoom) {
177 function gps2xy(aLatitude, aLongitude) {
178 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
179 var convLat = aLatitude * Math.PI / 180;
180 var rawY = (1 - Math.log(Math.tan(convLat) +
181 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
182 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
183 return {x: Math.round(rawX),
184 y: Math.round(rawY)};
187 function xy2gps(aX, aY) {
188 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
189 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
190 return {latitude: 180 / Math.PI *
191 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
192 longitude: aX / maxZoomFactor * 360 - 180};
195 function setMapStyle() {
196 var mapSel = document.getElementById("mapSelector");
197 if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
198 gActiveMap = mapSel.value;
200 document.getElementById("copyright").innerHTML =
201 gMapStyles[gActiveMap].copyright;
207 // A sane mod function that works for negative numbers.
210 return ((a % b) + b) % b;
213 function normaliseIndices(x, y, z) {
214 var zoomFactor = Math.pow(2, z);
215 return {x: mod(x, zoomFactor),
216 y: mod(y, zoomFactor),
220 function tileURL(x, y, z) {
221 var norm = normaliseIndices(x, y, z);
222 return gMapStyles[gActiveMap].url
223 .replace("{x}", norm.x)
224 .replace("{y}", norm.y)
225 .replace("{z}", norm.z)
226 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
227 .replace("[1-4]", 1 + Math.floor(Math.random() * 3));
230 // Returns true if the tile is outside the current view.
231 function isOutsideWindow(t) {
232 var pos = decodeIndex(t);
237 var zoomFactor = Math.pow(2, gMaxZoom - z);
238 var wid = gCanvas.width * zoomFactor;
239 var ht = gCanvas.height * zoomFactor;
244 var sz = gTileSize * zoomFactor;
245 if (x > gPos.x + wid / 2 || y > gPos.y + ht / 2 ||
246 x + sz < gPos.x - wid / 2 || y - sz < gPos.y - ht / 2)
251 function encodeIndex(x, y, z) {
252 var norm = normaliseIndices(x, y, z);
253 return norm.x + "," + norm.y + "," + norm.z;
256 function decodeIndex(encodedIdx) {
257 return encodedIdx.split(",", 3);
261 // Go through all the currently loaded tiles. If we don't want any of them remove them.
262 // for (t in gTiles) {
263 // if (isOutsideWindow(t))
266 document.getElementById("zoomLevel").textContent = gPos.z;
267 gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
268 var wid = gCanvas.width * gZoomFactor; // Width in level 18 pixels.
269 var ht = gCanvas.height * gZoomFactor; // Height in level 18 pixels.
270 var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
272 var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
273 var yMin = gPos.y - ht / 2;
274 var xMax = gPos.x + wid / 2;
275 var yMax = gPos.y + ht / 2;
277 if (gMapPrefsLoaded && mainDB)
278 gPrefs.set("position", gPos);
280 // Go through all the tiles we want.
281 // If any of them aren't loaded or being loaded, do so.
282 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
283 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
284 var xoff = (x * size - xMin) / gZoomFactor;
285 var yoff = (y * size - yMin) / gZoomFactor;
286 var tileKey = encodeIndex(x, y, gPos.z);
287 if (gTiles[tileKey] && gTiles[tileKey].complete) {
288 // Round here is **CRUCIAL** otherwise the images are filtered
289 // and the performance sucks (more than expected).
290 gContext.drawImage(gTiles[tileKey], Math.round(xoff), Math.round(yoff));
293 if (!gTiles[tileKey]) {
294 gTiles[tileKey] = new Image();
295 gTiles[tileKey].src = tileURL(x, y, gPos.z);
296 gTiles[tileKey].onload = function() {
297 // TODO: Just render this tile where it should be.
298 // context.drawImage(gTiles[tileKey], Math.round(xoff), Math.round(yoff)); // Doesn't work for some reason.
302 gContext.drawImage(gLoadingTile, Math.round(xoff), Math.round(yoff));
307 gLastDrawnPoint = null;
308 for (var i = 0; i < gTrack.length; i++) {
309 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
310 (i + 1 >= gTrack.length));
315 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
316 var trackpoint = gps2xy(aLatitude, aLongitude);
317 // lastPoint is for optimizing (not actually executing the draw until the last)
318 trackpoint.optimized = (lastPoint === false);
319 var mappos = {x: Math.round((trackpoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
320 y: Math.round((trackpoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2)};
322 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
323 gContext.strokeStyle = gTrackColor;
324 gContext.fillStyle = gContext.strokeStyle;
325 gContext.lineWidth = gTrackWidth;
326 gContext.lineCap = "round";
327 gContext.lineJoin = "round";
329 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
330 // This breaks optimiziation, so make sure to close path and reset optimization.
331 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
333 gContext.beginPath();
334 trackpoint.optimized = false;
335 gContext.arc(mappos.x, mappos.y,
336 gContext.lineWidth, 0, Math.PI * 2, false);
340 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
341 gContext.beginPath();
342 gContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
343 Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2));
345 gContext.lineTo(mappos.x, mappos.y);
346 if (!trackpoint.optimized)
349 gLastDrawnPoint = trackpoint;
352 function drawCurrentLocation(trackPoint) {
353 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.ccords.longitude);
354 var circleSize = gCurLocSize;
355 var mappos = {x: Math.round((locpoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
356 y: Math.round((locpoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2)};
358 // Initialize or draw cache.
359 if (!gCurPosMapCache)
360 gCurPosMapCache = {point: locpoint,
361 data: context.createImageData(circleSize, circleSize)};
363 gContext.putImageData(gCurPosMapCache, mappos.x - circleSize / 2,
364 mappos.y - circleSize / 2);
366 // Cache overdrawn area.
367 gCurPosMapCache = gContext.getImageData(mappos.x - circleSize / 2,
368 mappos.y - circleSize / 2,
369 circleSize, circleSize);
371 gContext.strokeStyle = gCurLocColor;
372 gContext.fillStyle = gContext.strokeStyle;
373 gContext.beginPath();
374 gContext.arc(mappos.x, mappos.y,
375 circleSize, 0, Math.PI * 2, false);
380 handleEvent: function(aEvent) {
381 var touchEvent = aEvent.type.indexOf('touch') != -1;
383 // Bail out on unwanted map moves, but not zoom-changing events.
384 if (aEvent.type != "DOMMouseScroll" && aEvent.type != "mousewheel") {
385 // Bail out if this is neither a touch nor left-click.
386 if (!touchEvent && aEvent.button != 0)
389 // Bail out if the started touch can't be found.
390 if (touchEvent && gDragging &&
391 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
395 var coordObj = touchEvent ?
396 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
399 switch (aEvent.type) {
403 gDragTouchID = aEvent.changedTouches.item(0).identifier;
404 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
406 var x = coordObj.clientX - gCanvas.offsetLeft;
407 var y = coordObj.clientY - gCanvas.offsetTop;
409 if (touchEvent || aEvent.button === 0) {
418 var x = coordObj.clientX - gCanvas.offsetLeft;
419 var y = coordObj.clientY - gCanvas.offsetTop;
420 if (gDragging === true) {
421 var dX = x - gLastMouseX;
422 var dY = y - gLastMouseY;
423 gPos.x -= dX * gZoomFactor;
424 gPos.y -= dY * gZoomFactor;
441 case "DOMMouseScroll":
444 if (aEvent.wheelDelta) {
445 delta = aEvent.wheelDelta / 120;
449 else if (aEvent.detail) {
450 delta = -aEvent.detail / 3;
453 // Calculate new center of the map - same point stays under the mouse.
454 // This means that the pixel distance between the old center and point
455 // must equal the pixel distance of the new center and that point.
456 var x = coordObj.clientX - gCanvas.offsetLeft;
457 var y = coordObj.clientY - gCanvas.offsetTop;
458 // Debug output: "coordinates" of the point the mouse was over.
460 var ptCoord = {x: gPos.x + (x - gCanvas.width / 2) * gZoomFactor,
461 y: gPos.y + (x - gCanvas.height / 2) * gZoomFactor};
462 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
463 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
464 document.getElementById("debug").textContent =
465 ptCoord.x + "/" + ptCoord.y + " - " +
466 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
467 pt2Coord.x + "/" + pt2Coord.y;
469 // Zoom factor after this action.
470 var newZoomFactor = Math.pow(2, gMaxZoom - gPos.z + (delta > 0 ? -1 : 1));
471 gPos.x -= (x - gCanvas.width / 2) * (newZoomFactor - gZoomFactor);
472 gPos.y -= (y - gCanvas.height / 2) * (newZoomFactor - gZoomFactor);
485 lastPos: {x: undefined, y: undefined},
486 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
487 this.tracking = true;
488 var watchCall = function() {
489 // calc new position in lat/lon degrees
490 // 90° on Earth surface are ~10,000 km at the equator,
491 // so try moving at most 10m at a time
492 if (geofake.lastPos.x)
493 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
495 geofake.lastPos.x = 48.208174
496 if (geofake.lastPos.y)
497 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
499 geofake.lastPos.y = 16.373819
500 aSuccessCallback({timestamp: Date.now(),
501 coords: {latitude: geofake.lastPos.x,
502 longitude: geofake.lastPos.y,
504 if (geofake.tracking)
505 setTimeout(watchCall, 1000);
507 setTimeout(watchCall, 1000);
510 clearWatch: function(aID) {
511 this.tracking = false;
515 function setCentering(aCheckbox) {
516 if (gMapPrefsLoaded && mainDB)
517 gPrefs.set("center_map", aCheckbox.checked);
518 gCenterPosition = aCheckbox.checked;
521 function setTracking(aCheckbox) {
522 if (gMapPrefsLoaded && mainDB)
523 gPrefs.set("tracking_enabled", aCheckbox.checked);
524 if (aCheckbox.checked)
530 function startTracking() {
532 var getStoredTrack = function() {
534 gTrackStore.getList(function(aTPoints) {
536 document.getElementById("debug").textContent = aTPoints.length + " points loaded.";
537 if (aTPoints.length) {
542 setTimeout(getStoredTrack, 100);
549 gGeoWatchID = gGeolocation.watchPosition(
551 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
552 var tPoint = {time: position.timestamp,
553 coords: {latitude: position.coords.latitude,
554 longitude: position.coords.longitude,
555 altitude: position.coords.altitude,
556 accuracy: position.coords.accuracy,
557 altitudeAccuracy: position.coords.altitudeAccuracy,
558 heading: position.coords.heading,
559 speed: position.coords.speed},
560 beginSegment: !gLastTrackPoint};
561 // Only add point to track is accuracy is good enough.
562 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
563 gLastTrackPoint = tPoint;
565 try { gTrackStore.push(tPoint); } catch(e) {}
567 if (gCenterPosition) {
568 var posCoord = gps2xy(position.coords.latitude,
569 position.coords.longitude);
570 if (Math.abs(gPos.x - posCoord.x) > gCanvas.width * gZoomFactor / 4 ||
571 Math.abs(gPos.y - posCoord.y) > gCanvas.height * gZoomFactor / 4) {
574 drawMap(); // This draws the current point as well.
579 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
581 drawCurrentLocation(tPoint);
584 // Ignore erros for the moment, but this is good for debugging.
585 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
586 document.getElementById("debug").textContent = error.message;
588 {enableHighAccuracy: true}
593 function endTracking() {
595 gGeolocation.clearWatch(gGeoWatchID);
599 function clearTrack() {