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 gMapCanvas, gMapContext, gTrackCanvas, gTrackContext, 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 = 6; // pixels
15 var gCurLocColor = "#A00000";
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 gMapCanvas = document.getElementById("map");
79 gMapContext = gMapCanvas.getContext("2d");
80 gTrackCanvas = document.getElementById("track");
81 gTrackContext = gTrackCanvas.getContext("2d");
83 gActiveMap = "osm_mapnik";
87 gGeolocation = geofake;
88 var hiddenList = document.getElementsByClassName("debugHide");
89 // last to first - list of elements with that class is changing!
90 for (var i = hiddenList.length - 1; i >= 0; i--) {
91 hiddenList[i].classList.remove("debugHide");
96 var getPersistentPrefs = function() {
99 gPrefs.get("position", function(aValue) {
106 gPrefs.get("center_map", function(aValue) {
107 if (aValue === undefined)
108 document.getElementById("centerCheckbox").checked = true;
110 document.getElementById("centerCheckbox").checked = aValue;
111 setCentering(document.getElementById("centerCheckbox"));
115 gPrefs.get("tracking_enabled", function(aValue) {
116 if (aValue === undefined)
117 document.getElementById("trackCheckbox").checked = true;
119 document.getElementById("trackCheckbox").checked = aValue;
123 gTrackStore.getList(function(aTPoints) {
125 document.getElementById("debug").textContent = aTPoints.length + " points loaded.";
126 if (aTPoints.length) {
133 setTimeout(getPersistentPrefs, 100);
136 document.getElementById("debug").textContent = "Loading prefs failed.";
139 getPersistentPrefs();
141 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
142 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
143 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
144 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
146 gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
147 gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
148 gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
149 gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
150 gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
152 // XXX deprecated? see https://groups.google.com/forum/?fromgroups#!topic/mozilla.dev.planning/kuhrORubaRY[1-25]
153 gTrackCanvas.addEventListener("DOMMouseScroll", mapEvHandler, false);
154 gTrackCanvas.addEventListener("mousewheel", mapEvHandler, false);
156 document.getElementById("copyright").innerHTML =
157 gMapStyles[gActiveMap].copyright;
159 gLoadingTile = new Image();
160 gLoadingTile.src = "style/loading.png";
162 gLoadingTile.onload = function() { gWaitCounter--; };
165 function resizeAndDraw() {
166 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
167 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
169 gMapCanvas.width = viewportWidth;
170 gMapCanvas.height = viewportHeight;
171 gTrackCanvas.width = viewportWidth;
172 gTrackCanvas.height = viewportHeight;
178 if (gPos.z < gMaxZoom) {
191 function gps2xy(aLatitude, aLongitude) {
192 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
193 var convLat = aLatitude * Math.PI / 180;
194 var rawY = (1 - Math.log(Math.tan(convLat) +
195 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
196 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
197 return {x: Math.round(rawX),
198 y: Math.round(rawY)};
201 function xy2gps(aX, aY) {
202 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
203 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
204 return {latitude: 180 / Math.PI *
205 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
206 longitude: aX / maxZoomFactor * 360 - 180};
209 function setMapStyle() {
210 var mapSel = document.getElementById("mapSelector");
211 if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
212 gActiveMap = mapSel.value;
214 document.getElementById("copyright").innerHTML =
215 gMapStyles[gActiveMap].copyright;
221 // A sane mod function that works for negative numbers.
224 return ((a % b) + b) % b;
227 function normaliseIndices(x, y, z) {
228 var zoomFactor = Math.pow(2, z);
229 return {x: mod(x, zoomFactor),
230 y: mod(y, zoomFactor),
234 function tileURL(x, y, z) {
235 var norm = normaliseIndices(x, y, z);
236 return gMapStyles[gActiveMap].url
237 .replace("{x}", norm.x)
238 .replace("{y}", norm.y)
239 .replace("{z}", norm.z)
240 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
241 .replace("[1-4]", 1 + Math.floor(Math.random() * 3));
244 // Returns true if the tile is outside the current view.
245 function isOutsideWindow(t) {
246 var pos = decodeIndex(t);
248 var zoomFactor = Math.pow(2, gMaxZoom - pos.z);
249 var wid = gMapCanvas.width * zoomFactor;
250 var ht = gMapCanvas.height * zoomFactor;
255 var sz = gTileSize * zoomFactor;
256 if (pos.x > gPos.x + wid / 2 || pos.y > gPos.y + ht / 2 ||
257 pos.x + sz < gPos.x - wid / 2 || pos.y - sz < gPos.y - ht / 2)
262 function encodeIndex(x, y, z) {
263 var norm = normaliseIndices(x, y, z);
264 return norm.x + "," + norm.y + "," + norm.z;
267 function decodeIndex(encodedIdx) {
268 var ind = encodedIdx.split(",", 3);
269 return {x: ind[0], y: ind[1], z: ind[2]};
273 // Go through all the currently loaded tiles. If we don't want any of them remove them.
274 // for (t in gTiles) {
275 // if (isOutsideWindow(t))
278 document.getElementById("zoomLevel").textContent = gPos.z;
279 gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
280 var wid = gMapCanvas.width * gZoomFactor; // Width in level 18 pixels.
281 var ht = gMapCanvas.height * gZoomFactor; // Height in level 18 pixels.
282 var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
284 var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
285 var yMin = gPos.y - ht / 2;
286 var xMax = gPos.x + wid / 2;
287 var yMax = gPos.y + ht / 2;
289 if (gMapPrefsLoaded && mainDB)
290 gPrefs.set("position", gPos);
292 // Go through all the tiles we want.
293 // If any of them aren't loaded or being loaded, do so.
294 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
295 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
296 // Round here is **CRUCIAL** otherwise the images are filtered
297 // and the performance sucks (more than expected).
298 var xoff = Math.round((x * size - xMin) / gZoomFactor);
299 var yoff = Math.round((y * size - yMin) / gZoomFactor);
300 var tileKey = encodeIndex(x, y, gPos.z);
301 if (gTiles[tileKey] && gTiles[tileKey].complete) {
302 gMapContext.drawImage(gTiles[tileKey], xoff, yoff);
305 // Draw placeholder, and then initiate loading/drawing of real one.
306 gMapContext.drawImage(gLoadingTile, xoff, yoff);
307 if (!gTiles[tileKey]) {
308 gTiles[tileKey] = new Image();
309 // Use alt field to communicate info to .onload.
310 gTiles[tileKey].alt = gPos.z + ":" + xoff + ":" + yoff;
311 gTiles[tileKey].src = tileURL(x, y, gPos.z);
312 gTiles[tileKey].onload = function() {
313 var tdata = this.alt.split(":", 3);
314 // Draw the tile if we're still looking at the same zoom.
315 if (tdata[0] == gPos.z) {
316 gMapContext.drawImage(this, tdata[1], tdata[2]);
322 // Update position to draw this image to when loaded.
323 gTiles[tileKey].alt = gPos.z + ":" + xoff + ":" + yoff;
328 gLastDrawnPoint = null;
329 gCurPosMapCache = undefined;
330 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
332 for (var i = 0; i < gTrack.length; i++) {
333 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
334 (i + 1 >= gTrack.length));
339 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
340 var trackpoint = gps2xy(aLatitude, aLongitude);
341 // lastPoint is for optimizing (not actually executing the draw until the last)
342 trackpoint.optimized = (lastPoint === false);
343 var mappos = {x: Math.round((trackpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
344 y: Math.round((trackpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
346 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
347 gTrackContext.strokeStyle = gTrackColor;
348 gTrackContext.fillStyle = gTrackContext.strokeStyle;
349 gTrackContext.lineWidth = gTrackWidth;
350 gTrackContext.lineCap = "round";
351 gTrackContext.lineJoin = "round";
353 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
354 // This breaks optimiziation, so make sure to close path and reset optimization.
355 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
356 gTrackContext.stroke();
357 gTrackContext.beginPath();
358 trackpoint.optimized = false;
359 gTrackContext.arc(mappos.x, mappos.y,
360 gTrackContext.lineWidth, 0, Math.PI * 2, false);
361 gTrackContext.fill();
364 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
365 gTrackContext.beginPath();
366 gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
367 Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2));
369 gTrackContext.lineTo(mappos.x, mappos.y);
370 if (!trackpoint.optimized)
371 gTrackContext.stroke();
373 gLastDrawnPoint = trackpoint;
376 function drawCurrentLocation(trackPoint) {
377 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
378 var circleRadius = Math.round(gCurLocSize / 2);
379 var mappos = {x: Math.round((locpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
380 y: Math.round((locpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
382 undrawCurrentLocation();
384 // Cache overdrawn area.
387 radius: circleRadius,
388 data: gTrackContext.getImageData(mappos.x - circleRadius,
389 mappos.y - circleRadius,
390 circleRadius * 2, circleRadius * 2)};
392 gTrackContext.strokeStyle = gCurLocColor;
393 gTrackContext.fillStyle = gTrackContext.strokeStyle;
394 gTrackContext.beginPath();
395 gTrackContext.arc(mappos.x, mappos.y,
396 circleRadius, 0, Math.PI * 2, false);
397 gTrackContext.fill();
400 function undrawCurrentLocation() {
401 if (gCurPosMapCache) {
402 var oldpoint = gCurPosMapCache.point;
403 var oldmp = {x: Math.round((oldpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
404 y: Math.round((oldpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
405 gTrackContext.putImageData(gCurPosMapCache.data,
406 oldmp.x - gCurPosMapCache.radius,
407 oldmp.y - gCurPosMapCache.radius);
408 gCurPosMapCache = undefined;
413 handleEvent: function(aEvent) {
414 var touchEvent = aEvent.type.indexOf('touch') != -1;
416 // Bail out on unwanted map moves, but not zoom-changing events.
417 if (aEvent.type != "DOMMouseScroll" && aEvent.type != "mousewheel") {
418 // Bail out if this is neither a touch nor left-click.
419 if (!touchEvent && aEvent.button != 0)
422 // Bail out if the started touch can't be found.
423 if (touchEvent && gDragging &&
424 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
428 var coordObj = touchEvent ?
429 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
432 switch (aEvent.type) {
436 gDragTouchID = aEvent.changedTouches.item(0).identifier;
437 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
439 var x = coordObj.clientX - gMapCanvas.offsetLeft;
440 var y = coordObj.clientY - gMapCanvas.offsetTop;
442 if (touchEvent || aEvent.button === 0) {
451 var x = coordObj.clientX - gMapCanvas.offsetLeft;
452 var y = coordObj.clientY - gMapCanvas.offsetTop;
453 if (gDragging === true) {
454 var dX = x - gLastMouseX;
455 var dY = y - gLastMouseY;
456 gPos.x -= dX * gZoomFactor;
457 gPos.y -= dY * gZoomFactor;
474 case "DOMMouseScroll":
477 if (aEvent.wheelDelta) {
478 delta = aEvent.wheelDelta / 120;
482 else if (aEvent.detail) {
483 delta = -aEvent.detail / 3;
486 // Debug output: "coordinates" of the point the mouse was over.
488 var ptCoord = {x: gPos.x + (x - gMapCanvas.width / 2) * gZoomFactor,
489 y: gPos.y + (x - gMapCanvas.height / 2) * gZoomFactor};
490 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
491 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
492 document.getElementById("debug").textContent =
493 ptCoord.x + "/" + ptCoord.y + " - " +
494 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
495 pt2Coord.x + "/" + pt2Coord.y;
498 var newZoomLevel = gPos.z + (delta > 0 ? 1 : -1);
499 if ((newZoomLevel >= 0) && (newZoomLevel <= gMaxZoom)) {
500 // Calculate new center of the map - same point stays under the mouse.
501 // This means that the pixel distance between the old center and point
502 // must equal the pixel distance of the new center and that point.
503 var x = coordObj.clientX - gMapCanvas.offsetLeft;
504 var y = coordObj.clientY - gMapCanvas.offsetTop;
506 // Zoom factor after this action.
507 var newZoomFactor = Math.pow(2, gMaxZoom - newZoomLevel);
508 gPos.x -= (x - gMapCanvas.width / 2) * (newZoomFactor - gZoomFactor);
509 gPos.y -= (y - gMapCanvas.height / 2) * (newZoomFactor - gZoomFactor);
523 lastPos: {x: undefined, y: undefined},
524 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
525 this.tracking = true;
526 var watchCall = function() {
527 // calc new position in lat/lon degrees
528 // 90° on Earth surface are ~10,000 km at the equator,
529 // so try moving at most 10m at a time
530 if (geofake.lastPos.x)
531 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
533 geofake.lastPos.x = 48.208174
534 if (geofake.lastPos.y)
535 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
537 geofake.lastPos.y = 16.373819
538 aSuccessCallback({timestamp: Date.now(),
539 coords: {latitude: geofake.lastPos.x,
540 longitude: geofake.lastPos.y,
542 if (geofake.tracking)
543 setTimeout(watchCall, 1000);
545 setTimeout(watchCall, 1000);
548 clearWatch: function(aID) {
549 this.tracking = false;
553 function setCentering(aCheckbox) {
554 if (gMapPrefsLoaded && mainDB)
555 gPrefs.set("center_map", aCheckbox.checked);
556 gCenterPosition = aCheckbox.checked;
559 function setTracking(aCheckbox) {
560 if (gMapPrefsLoaded && mainDB)
561 gPrefs.set("tracking_enabled", aCheckbox.checked);
562 if (aCheckbox.checked)
568 function startTracking() {
570 gGeoWatchID = gGeolocation.watchPosition(
572 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
573 var tPoint = {time: position.timestamp,
574 coords: {latitude: position.coords.latitude,
575 longitude: position.coords.longitude,
576 altitude: position.coords.altitude,
577 accuracy: position.coords.accuracy,
578 altitudeAccuracy: position.coords.altitudeAccuracy,
579 heading: position.coords.heading,
580 speed: position.coords.speed},
581 beginSegment: !gLastTrackPoint};
582 // Only add point to track is accuracy is good enough.
583 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
584 gLastTrackPoint = tPoint;
586 try { gTrackStore.push(tPoint); } catch(e) {}
588 if (gCenterPosition) {
589 var posCoord = gps2xy(position.coords.latitude,
590 position.coords.longitude);
591 if (Math.abs(gPos.x - posCoord.x) > gMapCanvas.width * gZoomFactor / 4 ||
592 Math.abs(gPos.y - posCoord.y) > gMapCanvas.height * gZoomFactor / 4) {
595 drawMap(); // This draws the current point as well.
600 undrawCurrentLocation();
601 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
603 drawCurrentLocation(tPoint);
606 // Ignore erros for the moment, but this is good for debugging.
607 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
608 document.getElementById("debug").textContent = error.message;
610 {enableHighAccuracy: true}
615 function endTracking() {
617 gGeolocation.clearWatch(gGeoWatchID);
621 function clearTrack() {