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://otile[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.
61 var gMapPrefsLoaded = false;
63 var gDragging = false;
68 var gLastTrackPoint, gLastDrawnPoint;
69 var gCenterPosition = true;
74 gGeolocation = navigator.geolocation;
75 gMapCanvas = document.getElementById("map");
76 gMapContext = gMapCanvas.getContext("2d");
77 gTrackCanvas = document.getElementById("track");
78 gTrackContext = gTrackCanvas.getContext("2d");
80 gActiveMap = "osm_mapnik";
84 gGeolocation = geofake;
85 var hiddenList = document.getElementsByClassName("debugHide");
86 // last to first - list of elements with that class is changing!
87 for (var i = hiddenList.length - 1; i >= 0; i--) {
88 hiddenList[i].classList.remove("debugHide");
92 console.log("map vars set, loading prefs...");
96 function loadPrefs(aEvent) {
97 if (aEvent && aEvent.type == "prefs-step") {
98 console.log("wait: " + gWaitCounter);
99 if (gWaitCounter == 0) {
100 gAction.removeEventListener(aEvent.type, loadPrefs, false);
101 gMapPrefsLoaded = true;
102 console.log("prefs loaded.");
104 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
105 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
106 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
107 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
109 gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
110 gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
111 gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
112 gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
113 gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
115 gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
117 document.getElementById("body").addEventListener("keydown", mapEvHandler, false);
119 document.getElementById("copyright").innerHTML =
120 gMapStyles[gActiveMap].copyright;
122 gLoadingTile = new Image();
123 gLoadingTile.src = "style/loading.png";
124 gLoadingTile.onload = function() {
125 var throwEv = new CustomEvent("mapinit-done");
126 gAction.dispatchEvent(throwEv);
132 gAction.removeEventListener(aEvent.type, loadPrefs, false);
133 gAction.addEventListener("prefs-step", loadPrefs, false);
135 gPrefs.get("position", function(aValue) {
142 gPrefs.get("center_map", function(aValue) {
143 if (aValue === undefined)
144 document.getElementById("centerCheckbox").checked = true;
146 document.getElementById("centerCheckbox").checked = aValue;
147 setCentering(document.getElementById("centerCheckbox"));
149 var throwEv = new CustomEvent("prefs-step");
150 gAction.dispatchEvent(throwEv);
153 gPrefs.get("tracking_enabled", function(aValue) {
154 if (aValue === undefined)
155 document.getElementById("trackCheckbox").checked = true;
157 document.getElementById("trackCheckbox").checked = aValue;
159 var throwEv = new CustomEvent("prefs-step");
160 gAction.dispatchEvent(throwEv);
163 gTrackStore.getList(function(aTPoints) {
165 console.log(aTPoints.length + " points loaded.");
166 if (aTPoints.length) {
170 var throwEv = new CustomEvent("prefs-step");
171 gAction.dispatchEvent(throwEv);
176 function resizeAndDraw() {
177 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
178 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
179 if (gMapCanvas && gTrackCanvas) {
180 gMapCanvas.width = viewportWidth;
181 gMapCanvas.height = viewportHeight;
182 gTrackCanvas.width = viewportWidth;
183 gTrackCanvas.height = viewportHeight;
189 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
190 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
193 if (gPos.z < gMaxZoom) {
206 function zoomTo(aTargetLevel) {
207 aTargetLevel = parseInt(aTargetLevel);
208 if (aTargetLevel >= 0 && aTargetLevel <= gMaxZoom) {
209 gPos.z = aTargetLevel;
214 function gps2xy(aLatitude, aLongitude) {
215 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
216 var convLat = aLatitude * Math.PI / 180;
217 var rawY = (1 - Math.log(Math.tan(convLat) +
218 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
219 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
220 return {x: Math.round(rawX),
221 y: Math.round(rawY)};
224 function xy2gps(aX, aY) {
225 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
226 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
227 return {latitude: 180 / Math.PI *
228 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
229 longitude: aX / maxZoomFactor * 360 - 180};
232 function setMapStyle() {
233 var mapSel = document.getElementById("mapSelector");
234 if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
235 gActiveMap = mapSel.value;
236 document.getElementById("copyright").innerHTML =
237 gMapStyles[gActiveMap].copyright;
243 // A sane mod function that works for negative numbers.
246 return ((a % b) + b) % b;
249 function normalizeCoords(aCoords) {
250 var zoomFactor = Math.pow(2, aCoords.z);
251 return {x: mod(aCoords.x, zoomFactor),
252 y: mod(aCoords.y, zoomFactor),
256 // Returns true if the tile is outside the current view.
257 function isOutsideWindow(t) {
258 var pos = decodeIndex(t);
260 var zoomFactor = Math.pow(2, gMaxZoom - pos.z);
261 var wid = gMapCanvas.width * zoomFactor;
262 var ht = gMapCanvas.height * zoomFactor;
267 var sz = gTileSize * zoomFactor;
268 if (pos.x > gPos.x + wid / 2 || pos.y > gPos.y + ht / 2 ||
269 pos.x + sz < gPos.x - wid / 2 || pos.y - sz < gPos.y - ht / 2)
274 function encodeIndex(x, y, z) {
275 var norm = normalizeCoords({x: x, y: y, z: z});
276 return norm.x + "," + norm.y + "," + norm.z;
279 function decodeIndex(encodedIdx) {
280 var ind = encodedIdx.split(",", 3);
281 return {x: ind[0], y: ind[1], z: ind[2]};
284 function drawMap(aPixels, aOverdraw) {
285 // aPixels is an object with left/right/top/bottom members telling how many
286 // pixels on the borders should actually be drawn.
287 // aOverdraw is a bool that tells if we should draw placeholders or draw
288 // straight over the existing content.
290 aPixels = {left: gMapCanvas.width, right: gMapCanvas.width,
291 top: gMapCanvas.height, bottom: gMapCanvas.height};
295 document.getElementById("zoomLevel").textContent = gPos.z;
296 gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
297 var wid = gMapCanvas.width * gZoomFactor; // Width in level 18 pixels.
298 var ht = gMapCanvas.height * gZoomFactor; // Height in level 18 pixels.
299 var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
301 var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
302 var yMin = gPos.y - ht / 2;
303 var xMax = gPos.x + wid / 2;
304 var yMax = gPos.y + ht / 2;
306 if (gMapPrefsLoaded && mainDB)
307 gPrefs.set("position", gPos);
309 var tiles = {left: Math.ceil((xMin + aPixels.left * gZoomFactor) / size) -
310 (aPixels.left ? 0 : 1),
311 right: Math.floor((xMax - aPixels.right * gZoomFactor) / size) -
312 (aPixels.right ? 1 : 0),
313 top: Math.ceil((yMin + aPixels.top * gZoomFactor) / size) -
314 (aPixels.top ? 0 : 1),
315 bottom: Math.floor((yMax - aPixels.bottom * gZoomFactor) / size) -
316 (aPixels.bottom ? 1 : 0)};
318 // Go through all the tiles in the map, find out if to draw them and do so.
319 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
320 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
321 // Only go to the drawing step if we need to draw this tile.
322 if (x < tiles.left || x > tiles.right ||
323 y < tiles.top || y > tiles.bottom) {
324 // Round here is **CRUCIAL** otherwise the images are filtered
325 // and the performance sucks (more than expected).
326 var xoff = Math.round((x * size - xMin) / gZoomFactor);
327 var yoff = Math.round((y * size - yMin) / gZoomFactor);
328 // Draw placeholder tile unless we overdraw.
330 (x < tiles.left -1 || x > tiles.right + 1 ||
331 y < tiles.top -1 || y > tiles.bottom + 1))
332 gMapContext.drawImage(gLoadingTile, xoff, yoff);
334 // Initiate loading/drawing of the actual tile.
335 gTileService.get(gActiveMap, {x: x, y: y, z: gPos.z},
336 function(aImage, aStyle, aCoords) {
337 // Only draw if this applies for the current view.
338 if ((aStyle == gActiveMap) && (aCoords.z == gPos.z)) {
339 var ixMin = gPos.x - wid / 2;
340 var iyMin = gPos.y - ht / 2;
341 var ixoff = Math.round((aCoords.x * size - ixMin) / gZoomFactor);
342 var iyoff = Math.round((aCoords.y * size - iyMin) / gZoomFactor);
343 var URL = window.URL;
344 var imgURL = URL.createObjectURL(aImage);
345 var imgObj = new Image();
347 imgObj.onload = function() {
348 gMapContext.drawImage(imgObj, ixoff, iyoff);
349 URL.revokeObjectURL(imgURL);
356 gLastDrawnPoint = null;
357 gCurPosMapCache = undefined;
358 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
360 for (var i = 0; i < gTrack.length; i++) {
361 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
362 (i + 1 >= gTrack.length));
367 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
368 var trackpoint = gps2xy(aLatitude, aLongitude);
369 // lastPoint is for optimizing (not actually executing the draw until the last)
370 trackpoint.optimized = (lastPoint === false);
371 var mappos = {x: Math.round((trackpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
372 y: Math.round((trackpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
374 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
375 gTrackContext.strokeStyle = gTrackColor;
376 gTrackContext.fillStyle = gTrackContext.strokeStyle;
377 gTrackContext.lineWidth = gTrackWidth;
378 gTrackContext.lineCap = "round";
379 gTrackContext.lineJoin = "round";
381 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
382 // This breaks optimiziation, so make sure to close path and reset optimization.
383 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
384 gTrackContext.stroke();
385 gTrackContext.beginPath();
386 trackpoint.optimized = false;
387 gTrackContext.arc(mappos.x, mappos.y,
388 gTrackContext.lineWidth, 0, Math.PI * 2, false);
389 gTrackContext.fill();
392 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
393 gTrackContext.beginPath();
394 gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
395 Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2));
397 gTrackContext.lineTo(mappos.x, mappos.y);
398 if (!trackpoint.optimized)
399 gTrackContext.stroke();
401 gLastDrawnPoint = trackpoint;
404 function drawCurrentLocation(trackPoint) {
405 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
406 var circleRadius = Math.round(gCurLocSize / 2);
407 var mappos = {x: Math.round((locpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
408 y: Math.round((locpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
410 undrawCurrentLocation();
412 // Cache overdrawn area.
415 radius: circleRadius,
416 data: gTrackContext.getImageData(mappos.x - circleRadius,
417 mappos.y - circleRadius,
418 circleRadius * 2, circleRadius * 2)};
420 gTrackContext.strokeStyle = gCurLocColor;
421 gTrackContext.fillStyle = gTrackContext.strokeStyle;
422 gTrackContext.beginPath();
423 gTrackContext.arc(mappos.x, mappos.y,
424 circleRadius, 0, Math.PI * 2, false);
425 gTrackContext.fill();
428 function undrawCurrentLocation() {
429 if (gCurPosMapCache) {
430 var oldpoint = gCurPosMapCache.point;
431 var oldmp = {x: Math.round((oldpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
432 y: Math.round((oldpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
433 gTrackContext.putImageData(gCurPosMapCache.data,
434 oldmp.x - gCurPosMapCache.radius,
435 oldmp.y - gCurPosMapCache.radius);
436 gCurPosMapCache = undefined;
441 handleEvent: function(aEvent) {
442 var touchEvent = aEvent.type.indexOf('touch') != -1;
444 // Bail out if the event is happening on an input.
445 if (aEvent.target.tagName.toLowerCase() == "input")
448 // Bail out on unwanted map moves, but not zoom or keyboard events.
449 if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
450 // Bail out if this is neither a touch nor left-click.
451 if (!touchEvent && aEvent.button != 0)
454 // Bail out if the started touch can't be found.
455 if (touchEvent && gDragging &&
456 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
460 var coordObj = touchEvent ?
461 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
464 switch (aEvent.type) {
468 gDragTouchID = aEvent.changedTouches.item(0).identifier;
469 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
471 var x = coordObj.clientX - gMapCanvas.offsetLeft;
472 var y = coordObj.clientY - gMapCanvas.offsetTop;
474 if (touchEvent || aEvent.button === 0) {
483 var x = coordObj.clientX - gMapCanvas.offsetLeft;
484 var y = coordObj.clientY - gMapCanvas.offsetTop;
485 if (gDragging === true) {
486 var dX = x - gLastMouseX;
487 var dY = y - gLastMouseY;
488 gPos.x -= dX * gZoomFactor;
489 gPos.y -= dY * gZoomFactor;
490 if (true) { // use optimized path
491 var mapData = gMapContext.getImageData(0, 0,
494 gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
495 gMapContext.putImageData(mapData, dX, dY);
496 drawMap({left: (dX > 0) ? dX : 0,
497 right: (dX < 0) ? -dX : 0,
498 top: (dY > 0) ? dY : 0,
499 bottom: (dY < 0) ? -dY : 0});
502 drawMap(false, true);
520 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
521 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
523 // Only accept (non-null) deltaY values
527 // Debug output: "coordinates" of the point the mouse was over.
529 var ptCoord = {x: gPos.x + (x - gMapCanvas.width / 2) * gZoomFactor,
530 y: gPos.y + (x - gMapCanvas.height / 2) * gZoomFactor};
531 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
532 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
533 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
534 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
535 pt2Coord.x + "/" + pt2Coord.y);
538 var newZoomLevel = gPos.z + (aEvent.deltaY < 0 ? 1 : -1);
539 if ((newZoomLevel >= 0) && (newZoomLevel <= gMaxZoom)) {
540 // Calculate new center of the map - same point stays under the mouse.
541 // This means that the pixel distance between the old center and point
542 // must equal the pixel distance of the new center and that point.
543 var x = coordObj.clientX - gMapCanvas.offsetLeft;
544 var y = coordObj.clientY - gMapCanvas.offsetTop;
546 // Zoom factor after this action.
547 var newZoomFactor = Math.pow(2, gMaxZoom - newZoomLevel);
548 gPos.x -= (x - gMapCanvas.width / 2) * (newZoomFactor - gZoomFactor);
549 gPos.y -= (y - gMapCanvas.height / 2) * (newZoomFactor - gZoomFactor);
551 if (aEvent.deltaY < 0)
558 // Allow keyboard control to move and zoom the map.
559 // Should use aEvent.key instead of aEvent.which but needs bug 680830.
560 // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
563 switch (aEvent.which) {
577 case 107: // + (numpad)
578 case 171: // + (normal key)
582 case 109: // - (numpad)
583 case 173: // - (normal key)
595 zoomTo(aEvent.which - 38);
600 case 96: // 0 (numpad)
601 case 97: // 1 (numpad)
602 case 98: // 2 (numpad)
603 case 99: // 3 (numpad)
604 case 100: // 4 (numpad)
605 case 101: // 5 (numpad)
606 case 102: // 6 (numpad)
607 case 103: // 7 (numpad)
608 case 104: // 8 (numpad)
609 zoomTo(aEvent.which - 86);
611 case 105: // 9 (numpad)
614 default: // not supported
615 console.log("key not supported: " + aEvent.which);
621 gPos.x -= dX * gZoomFactor;
622 gPos.y -= dY * gZoomFactor;
623 if (true) { // use optimized path
624 var mapData = gMapContext.getImageData(0, 0,
627 gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
628 gMapContext.putImageData(mapData, dX, dY);
629 drawMap({left: (dX > 0) ? dX : 0,
630 right: (dX < 0) ? -dX : 0,
631 top: (dY > 0) ? dY : 0,
632 bottom: (dY < 0) ? -dY : 0});
635 drawMap(false, true);
645 lastPos: {x: undefined, y: undefined},
646 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
647 this.tracking = true;
648 var watchCall = function() {
649 // calc new position in lat/lon degrees
650 // 90° on Earth surface are ~10,000 km at the equator,
651 // so try moving at most 10m at a time
652 if (geofake.lastPos.x)
653 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
655 geofake.lastPos.x = 48.208174
656 if (geofake.lastPos.y)
657 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
659 geofake.lastPos.y = 16.373819
660 aSuccessCallback({timestamp: Date.now(),
661 coords: {latitude: geofake.lastPos.x,
662 longitude: geofake.lastPos.y,
664 if (geofake.tracking)
665 setTimeout(watchCall, 1000);
667 setTimeout(watchCall, 1000);
670 clearWatch: function(aID) {
671 this.tracking = false;
675 function setCentering(aCheckbox) {
676 if (gMapPrefsLoaded && mainDB)
677 gPrefs.set("center_map", aCheckbox.checked);
678 gCenterPosition = aCheckbox.checked;
681 function setTracking(aCheckbox) {
682 if (gMapPrefsLoaded && mainDB)
683 gPrefs.set("tracking_enabled", aCheckbox.checked);
684 if (aCheckbox.checked)
690 function startTracking() {
692 gActionLabel.textContent = "Establishing Position";
693 gAction.style.display = "block";
694 gGeoWatchID = gGeolocation.watchPosition(
696 if (gActionLabel.textContent) {
697 gActionLabel.textContent = "";
698 gAction.style.display = "none";
700 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
701 var tPoint = {time: position.timestamp,
702 coords: {latitude: position.coords.latitude,
703 longitude: position.coords.longitude,
704 altitude: position.coords.altitude,
705 accuracy: position.coords.accuracy,
706 altitudeAccuracy: position.coords.altitudeAccuracy,
707 heading: position.coords.heading,
708 speed: position.coords.speed},
709 beginSegment: !gLastTrackPoint};
710 // Only add point to track is accuracy is good enough.
711 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
712 gLastTrackPoint = tPoint;
714 try { gTrackStore.push(tPoint); } catch(e) {}
716 if (gCenterPosition) {
717 var posCoord = gps2xy(position.coords.latitude,
718 position.coords.longitude);
719 if (Math.abs(gPos.x - posCoord.x) > gMapCanvas.width * gZoomFactor / 4 ||
720 Math.abs(gPos.y - posCoord.y) > gMapCanvas.height * gZoomFactor / 4) {
723 drawMap(); // This draws the current point as well.
728 undrawCurrentLocation();
729 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
731 drawCurrentLocation(tPoint);
734 // Ignore erros for the moment, but this is good for debugging.
735 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
737 console.log(error.message);
739 {enableHighAccuracy: true}
744 function endTracking() {
745 if (gActionLabel.textContent) {
746 gActionLabel.textContent = "";
747 gAction.style.display = "none";
750 gGeolocation.clearWatch(gGeoWatchID);
754 function clearTrack() {
757 drawMap({left: 0, right: 0, top: 0, bottom: 0});
761 objStore: "tilecache",
763 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
765 get: function(aStyle, aCoords, aCallback) {
766 var norm = normalizeCoords(aCoords);
767 var dbkey = aStyle + "::" + norm.x + "," + norm.y + "," + norm.z;
768 this.getDBCache(dbkey, function(aResult, aEvent) {
770 // We did get a cached object.
771 aCallback(aResult.image, aStyle, aCoords);
772 // Look at the timestamp and return if it's not too old.
773 if (aResult.timestamp + gTileService.ageLimit > Date.now())
775 // Reload cached tile otherwise.
776 var oldDate = new Date(aResult.timestamp);
777 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
779 // Retrieve image from the web and store it in the cache.
780 var XHR = new XMLHttpRequest();
782 gMapStyles[aStyle].url
783 .replace("{x}", norm.x)
784 .replace("{y}", norm.y)
785 .replace("{z}", norm.z)
786 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
787 .replace("[1-4]", 1 + Math.floor(Math.random() * 3)),
789 XHR.responseType = "blob";
790 XHR.addEventListener("load", function () {
791 if (XHR.status === 200) {
792 var blob = XHR.response;
793 aCallback(blob, aStyle, aCoords);
794 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
801 getDBCache: function(aKey, aCallback) {
804 var transaction = mainDB.transaction([this.objStore]);
805 var request = transaction.objectStore(this.objStore).get(aKey);
806 request.onsuccess = function(event) {
807 aCallback(request.result, event);
809 request.onerror = function(event) {
810 // Errors can be handled here.
811 aCallback(undefined, event);
815 setDBCache: function(aKey, aValue, aCallback) {
819 var transaction = mainDB.transaction([this.objStore], "readwrite");
820 var objStore = transaction.objectStore(this.objStore);
821 var request = objStore.put(aValue, aKey);
822 request.onsuccess = function(event) {
825 aCallback(success, event);
827 request.onerror = function(event) {
828 // Errors can be handled here.
830 aCallback(success, event);
834 unsetDBCache: function(aKey, aCallback) {
838 var transaction = mainDB.transaction([this.objStore], "readwrite");
839 var request = transaction.objectStore(this.objStore).delete(aKey);
840 request.onsuccess = function(event) {
843 aCallback(success, event);
845 request.onerror = function(event) {
846 // Errors can be handled here.
848 aCallback(success, event);
852 clearDB: function(aCallback) {
856 var transaction = mainDB.transaction([this.objStore], "readwrite");
857 var request = transaction.objectStore(this.objStore).clear();
858 request.onsuccess = function(event) {
861 aCallback(success, event);
863 request.onerror = function(event) {
864 // Errors can be handled here.
866 aCallback(success, event);