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");
93 var getPersistentPrefs = function() {
96 gPrefs.get("position", function(aValue) {
103 gPrefs.get("center_map", function(aValue) {
104 if (aValue === undefined)
105 document.getElementById("centerCheckbox").checked = true;
107 document.getElementById("centerCheckbox").checked = aValue;
108 setCentering(document.getElementById("centerCheckbox"));
112 gPrefs.get("tracking_enabled", function(aValue) {
113 if (aValue === undefined)
114 document.getElementById("trackCheckbox").checked = true;
116 document.getElementById("trackCheckbox").checked = aValue;
120 gTrackStore.getList(function(aTPoints) {
122 console.log(aTPoints.length + " points loaded.");
123 if (aTPoints.length) {
130 setTimeout(getPersistentPrefs, 100);
133 console.log("Loading prefs failed.");
136 getPersistentPrefs();
138 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
139 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
140 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
141 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
143 gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
144 gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
145 gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
146 gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
147 gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
149 gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
151 document.getElementById("body").addEventListener("keydown", mapEvHandler, false);
153 document.getElementById("copyright").innerHTML =
154 gMapStyles[gActiveMap].copyright;
156 gLoadingTile = new Image();
157 gLoadingTile.src = "style/loading.png";
159 gLoadingTile.onload = function() { gWaitCounter--; };
162 function resizeAndDraw() {
163 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
164 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
165 if (gMapCanvas && gTrackCanvas) {
166 gMapCanvas.width = viewportWidth;
167 gMapCanvas.height = viewportHeight;
168 gTrackCanvas.width = viewportWidth;
169 gTrackCanvas.height = viewportHeight;
175 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
176 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
179 if (gPos.z < gMaxZoom) {
192 function zoomTo(aTargetLevel) {
193 aTargetLevel = parseInt(aTargetLevel);
194 if (aTargetLevel >= 0 && aTargetLevel <= gMaxZoom) {
195 gPos.z = aTargetLevel;
200 function gps2xy(aLatitude, aLongitude) {
201 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
202 var convLat = aLatitude * Math.PI / 180;
203 var rawY = (1 - Math.log(Math.tan(convLat) +
204 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
205 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
206 return {x: Math.round(rawX),
207 y: Math.round(rawY)};
210 function xy2gps(aX, aY) {
211 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
212 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
213 return {latitude: 180 / Math.PI *
214 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
215 longitude: aX / maxZoomFactor * 360 - 180};
218 function setMapStyle() {
219 var mapSel = document.getElementById("mapSelector");
220 if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
221 gActiveMap = mapSel.value;
222 document.getElementById("copyright").innerHTML =
223 gMapStyles[gActiveMap].copyright;
229 // A sane mod function that works for negative numbers.
232 return ((a % b) + b) % b;
235 function normalizeCoords(aCoords) {
236 var zoomFactor = Math.pow(2, aCoords.z);
237 return {x: mod(aCoords.x, zoomFactor),
238 y: mod(aCoords.y, zoomFactor),
242 // Returns true if the tile is outside the current view.
243 function isOutsideWindow(t) {
244 var pos = decodeIndex(t);
246 var zoomFactor = Math.pow(2, gMaxZoom - pos.z);
247 var wid = gMapCanvas.width * zoomFactor;
248 var ht = gMapCanvas.height * zoomFactor;
253 var sz = gTileSize * zoomFactor;
254 if (pos.x > gPos.x + wid / 2 || pos.y > gPos.y + ht / 2 ||
255 pos.x + sz < gPos.x - wid / 2 || pos.y - sz < gPos.y - ht / 2)
260 function encodeIndex(x, y, z) {
261 var norm = normalizeCoords({x: x, y: y, z: z});
262 return norm.x + "," + norm.y + "," + norm.z;
265 function decodeIndex(encodedIdx) {
266 var ind = encodedIdx.split(",", 3);
267 return {x: ind[0], y: ind[1], z: ind[2]};
270 function drawMap(aPixels, aOverdraw) {
271 // aPixels is an object with left/right/top/bottom members telling how many
272 // pixels on the borders should actually be drawn.
273 // aOverdraw is a bool that tells if we should draw placeholders or draw
274 // straight over the existing content.
276 aPixels = {left: gMapCanvas.width, right: gMapCanvas.width,
277 top: gMapCanvas.height, bottom: gMapCanvas.height};
281 document.getElementById("zoomLevel").textContent = gPos.z;
282 gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
283 var wid = gMapCanvas.width * gZoomFactor; // Width in level 18 pixels.
284 var ht = gMapCanvas.height * gZoomFactor; // Height in level 18 pixels.
285 var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
287 var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
288 var yMin = gPos.y - ht / 2;
289 var xMax = gPos.x + wid / 2;
290 var yMax = gPos.y + ht / 2;
292 if (gMapPrefsLoaded && mainDB)
293 gPrefs.set("position", gPos);
295 var tiles = {left: Math.ceil((xMin + aPixels.left * gZoomFactor) / size) -
296 (aPixels.left ? 0 : 1),
297 right: Math.floor((xMax - aPixels.right * gZoomFactor) / size) -
298 (aPixels.right ? 1 : 0),
299 top: Math.ceil((yMin + aPixels.top * gZoomFactor) / size) -
300 (aPixels.top ? 0 : 1),
301 bottom: Math.floor((yMax - aPixels.bottom * gZoomFactor) / size) -
302 (aPixels.bottom ? 1 : 0)};
304 // Go through all the tiles in the map, find out if to draw them and do so.
305 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
306 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
307 // Only go to the drawing step if we need to draw this tile.
308 if (x < tiles.left || x > tiles.right ||
309 y < tiles.top || y > tiles.bottom) {
310 // Round here is **CRUCIAL** otherwise the images are filtered
311 // and the performance sucks (more than expected).
312 var xoff = Math.round((x * size - xMin) / gZoomFactor);
313 var yoff = Math.round((y * size - yMin) / gZoomFactor);
314 // Draw placeholder tile unless we overdraw.
316 (x < tiles.left -1 || x > tiles.right + 1 ||
317 y < tiles.top -1 || y > tiles.bottom + 1))
318 gMapContext.drawImage(gLoadingTile, xoff, yoff);
320 // Initiate loading/drawing of the actual tile.
321 gTileService.get(gActiveMap, {x: x, y: y, z: gPos.z},
322 function(aImage, aStyle, aCoords) {
323 // Only draw if this applies for the current view.
324 if ((aStyle == gActiveMap) && (aCoords.z == gPos.z)) {
325 var ixMin = gPos.x - wid / 2;
326 var iyMin = gPos.y - ht / 2;
327 var ixoff = Math.round((aCoords.x * size - ixMin) / gZoomFactor);
328 var iyoff = Math.round((aCoords.y * size - iyMin) / gZoomFactor);
329 var URL = window.URL;
330 var imgURL = URL.createObjectURL(aImage);
331 var imgObj = new Image();
333 imgObj.onload = function() {
334 gMapContext.drawImage(imgObj, ixoff, iyoff);
335 URL.revokeObjectURL(imgURL);
342 gLastDrawnPoint = null;
343 gCurPosMapCache = undefined;
344 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
346 for (var i = 0; i < gTrack.length; i++) {
347 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
348 (i + 1 >= gTrack.length));
353 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
354 var trackpoint = gps2xy(aLatitude, aLongitude);
355 // lastPoint is for optimizing (not actually executing the draw until the last)
356 trackpoint.optimized = (lastPoint === false);
357 var mappos = {x: Math.round((trackpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
358 y: Math.round((trackpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
360 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
361 gTrackContext.strokeStyle = gTrackColor;
362 gTrackContext.fillStyle = gTrackContext.strokeStyle;
363 gTrackContext.lineWidth = gTrackWidth;
364 gTrackContext.lineCap = "round";
365 gTrackContext.lineJoin = "round";
367 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
368 // This breaks optimiziation, so make sure to close path and reset optimization.
369 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
370 gTrackContext.stroke();
371 gTrackContext.beginPath();
372 trackpoint.optimized = false;
373 gTrackContext.arc(mappos.x, mappos.y,
374 gTrackContext.lineWidth, 0, Math.PI * 2, false);
375 gTrackContext.fill();
378 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
379 gTrackContext.beginPath();
380 gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
381 Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2));
383 gTrackContext.lineTo(mappos.x, mappos.y);
384 if (!trackpoint.optimized)
385 gTrackContext.stroke();
387 gLastDrawnPoint = trackpoint;
390 function drawCurrentLocation(trackPoint) {
391 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
392 var circleRadius = Math.round(gCurLocSize / 2);
393 var mappos = {x: Math.round((locpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
394 y: Math.round((locpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
396 undrawCurrentLocation();
398 // Cache overdrawn area.
401 radius: circleRadius,
402 data: gTrackContext.getImageData(mappos.x - circleRadius,
403 mappos.y - circleRadius,
404 circleRadius * 2, circleRadius * 2)};
406 gTrackContext.strokeStyle = gCurLocColor;
407 gTrackContext.fillStyle = gTrackContext.strokeStyle;
408 gTrackContext.beginPath();
409 gTrackContext.arc(mappos.x, mappos.y,
410 circleRadius, 0, Math.PI * 2, false);
411 gTrackContext.fill();
414 function undrawCurrentLocation() {
415 if (gCurPosMapCache) {
416 var oldpoint = gCurPosMapCache.point;
417 var oldmp = {x: Math.round((oldpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
418 y: Math.round((oldpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
419 gTrackContext.putImageData(gCurPosMapCache.data,
420 oldmp.x - gCurPosMapCache.radius,
421 oldmp.y - gCurPosMapCache.radius);
422 gCurPosMapCache = undefined;
427 handleEvent: function(aEvent) {
428 var touchEvent = aEvent.type.indexOf('touch') != -1;
430 // Bail out if the event is happening on an input.
431 if (aEvent.target.tagName.toLowerCase() == "input")
434 // Bail out on unwanted map moves, but not zoom or keyboard events.
435 if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
436 // Bail out if this is neither a touch nor left-click.
437 if (!touchEvent && aEvent.button != 0)
440 // Bail out if the started touch can't be found.
441 if (touchEvent && gDragging &&
442 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
446 var coordObj = touchEvent ?
447 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
450 switch (aEvent.type) {
454 gDragTouchID = aEvent.changedTouches.item(0).identifier;
455 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
457 var x = coordObj.clientX - gMapCanvas.offsetLeft;
458 var y = coordObj.clientY - gMapCanvas.offsetTop;
460 if (touchEvent || aEvent.button === 0) {
469 var x = coordObj.clientX - gMapCanvas.offsetLeft;
470 var y = coordObj.clientY - gMapCanvas.offsetTop;
471 if (gDragging === true) {
472 var dX = x - gLastMouseX;
473 var dY = y - gLastMouseY;
474 gPos.x -= dX * gZoomFactor;
475 gPos.y -= dY * gZoomFactor;
476 if (true) { // use optimized path
477 var mapData = gMapContext.getImageData(0, 0,
480 gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
481 gMapContext.putImageData(mapData, dX, dY);
482 drawMap({left: (dX > 0) ? dX : 0,
483 right: (dX < 0) ? -dX : 0,
484 top: (dY > 0) ? dY : 0,
485 bottom: (dY < 0) ? -dY : 0});
488 drawMap(false, true);
506 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
507 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
509 // Only accept (non-null) deltaY values
513 // Debug output: "coordinates" of the point the mouse was over.
515 var ptCoord = {x: gPos.x + (x - gMapCanvas.width / 2) * gZoomFactor,
516 y: gPos.y + (x - gMapCanvas.height / 2) * gZoomFactor};
517 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
518 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
519 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
520 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
521 pt2Coord.x + "/" + pt2Coord.y);
524 var newZoomLevel = gPos.z + (aEvent.deltaY < 0 ? 1 : -1);
525 if ((newZoomLevel >= 0) && (newZoomLevel <= gMaxZoom)) {
526 // Calculate new center of the map - same point stays under the mouse.
527 // This means that the pixel distance between the old center and point
528 // must equal the pixel distance of the new center and that point.
529 var x = coordObj.clientX - gMapCanvas.offsetLeft;
530 var y = coordObj.clientY - gMapCanvas.offsetTop;
532 // Zoom factor after this action.
533 var newZoomFactor = Math.pow(2, gMaxZoom - newZoomLevel);
534 gPos.x -= (x - gMapCanvas.width / 2) * (newZoomFactor - gZoomFactor);
535 gPos.y -= (y - gMapCanvas.height / 2) * (newZoomFactor - gZoomFactor);
537 if (aEvent.deltaY < 0)
544 // Allow keyboard control to move and zoom the map.
545 // Should use aEvent.key instead of aEvent.which but needs bug 680830.
546 // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
549 switch (aEvent.which) {
563 case 107: // + (numpad)
564 case 171: // + (normal key)
568 case 109: // - (numpad)
569 case 173: // - (normal key)
581 zoomTo(aEvent.which - 38);
586 case 96: // 0 (numpad)
587 case 97: // 1 (numpad)
588 case 98: // 2 (numpad)
589 case 99: // 3 (numpad)
590 case 100: // 4 (numpad)
591 case 101: // 5 (numpad)
592 case 102: // 6 (numpad)
593 case 103: // 7 (numpad)
594 case 104: // 8 (numpad)
595 zoomTo(aEvent.which - 86);
597 case 105: // 9 (numpad)
600 default: // not supported
601 console.log("key not supported: " + aEvent.which);
607 gPos.x -= dX * gZoomFactor;
608 gPos.y -= dY * gZoomFactor;
609 if (true) { // use optimized path
610 var mapData = gMapContext.getImageData(0, 0,
613 gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
614 gMapContext.putImageData(mapData, dX, dY);
615 drawMap({left: (dX > 0) ? dX : 0,
616 right: (dX < 0) ? -dX : 0,
617 top: (dY > 0) ? dY : 0,
618 bottom: (dY < 0) ? -dY : 0});
621 drawMap(false, true);
631 lastPos: {x: undefined, y: undefined},
632 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
633 this.tracking = true;
634 var watchCall = function() {
635 // calc new position in lat/lon degrees
636 // 90° on Earth surface are ~10,000 km at the equator,
637 // so try moving at most 10m at a time
638 if (geofake.lastPos.x)
639 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
641 geofake.lastPos.x = 48.208174
642 if (geofake.lastPos.y)
643 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
645 geofake.lastPos.y = 16.373819
646 aSuccessCallback({timestamp: Date.now(),
647 coords: {latitude: geofake.lastPos.x,
648 longitude: geofake.lastPos.y,
650 if (geofake.tracking)
651 setTimeout(watchCall, 1000);
653 setTimeout(watchCall, 1000);
656 clearWatch: function(aID) {
657 this.tracking = false;
661 function setCentering(aCheckbox) {
662 if (gMapPrefsLoaded && mainDB)
663 gPrefs.set("center_map", aCheckbox.checked);
664 gCenterPosition = aCheckbox.checked;
667 function setTracking(aCheckbox) {
668 if (gMapPrefsLoaded && mainDB)
669 gPrefs.set("tracking_enabled", aCheckbox.checked);
670 if (aCheckbox.checked)
676 function startTracking() {
678 gActionLabel.textContent = "Establishing Position";
679 gAction.style.display = "block";
680 gGeoWatchID = gGeolocation.watchPosition(
682 if (gActionLabel.textContent) {
683 gActionLabel.textContent = "";
684 gAction.style.display = "none";
686 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
687 var tPoint = {time: position.timestamp,
688 coords: {latitude: position.coords.latitude,
689 longitude: position.coords.longitude,
690 altitude: position.coords.altitude,
691 accuracy: position.coords.accuracy,
692 altitudeAccuracy: position.coords.altitudeAccuracy,
693 heading: position.coords.heading,
694 speed: position.coords.speed},
695 beginSegment: !gLastTrackPoint};
696 // Only add point to track is accuracy is good enough.
697 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
698 gLastTrackPoint = tPoint;
700 try { gTrackStore.push(tPoint); } catch(e) {}
702 if (gCenterPosition) {
703 var posCoord = gps2xy(position.coords.latitude,
704 position.coords.longitude);
705 if (Math.abs(gPos.x - posCoord.x) > gMapCanvas.width * gZoomFactor / 4 ||
706 Math.abs(gPos.y - posCoord.y) > gMapCanvas.height * gZoomFactor / 4) {
709 drawMap(); // This draws the current point as well.
714 undrawCurrentLocation();
715 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
717 drawCurrentLocation(tPoint);
720 // Ignore erros for the moment, but this is good for debugging.
721 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
723 console.log(error.message);
725 {enableHighAccuracy: true}
730 function endTracking() {
731 if (gActionLabel.textContent) {
732 gActionLabel.textContent = "";
733 gAction.style.display = "none";
736 gGeolocation.clearWatch(gGeoWatchID);
740 function clearTrack() {
743 drawMap({left: 0, right: 0, top: 0, bottom: 0});
747 objStore: "tilecache",
749 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
751 get: function(aStyle, aCoords, aCallback) {
752 var norm = normalizeCoords(aCoords);
753 var dbkey = aStyle + "::" + norm.x + "," + norm.y + "," + norm.z;
754 this.getDBCache(dbkey, function(aResult, aEvent) {
756 // We did get a cached object.
757 aCallback(aResult.image, aStyle, aCoords);
758 // Look at the timestamp and return if it's not too old.
759 if (aResult.timestamp + gTileService.ageLimit > Date.now())
761 // Reload cached tile otherwise.
762 var oldDate = new Date(aResult.timestamp);
763 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
765 // Retrieve image from the web and store it in the cache.
766 var XHR = new XMLHttpRequest();
768 gMapStyles[aStyle].url
769 .replace("{x}", norm.x)
770 .replace("{y}", norm.y)
771 .replace("{z}", norm.z)
772 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
773 .replace("[1-4]", 1 + Math.floor(Math.random() * 3)),
775 XHR.responseType = "blob";
776 XHR.addEventListener("load", function () {
777 if (XHR.status === 200) {
778 var blob = XHR.response;
779 aCallback(blob, aStyle, aCoords);
780 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
787 getDBCache: function(aKey, aCallback) {
790 var transaction = mainDB.transaction([this.objStore]);
791 var request = transaction.objectStore(this.objStore).get(aKey);
792 request.onsuccess = function(event) {
793 aCallback(request.result, event);
795 request.onerror = function(event) {
796 // Errors can be handled here.
797 aCallback(undefined, event);
801 setDBCache: function(aKey, aValue, aCallback) {
805 var transaction = mainDB.transaction([this.objStore], "readwrite");
806 var objStore = transaction.objectStore(this.objStore);
807 var request = objStore.put(aValue, aKey);
808 request.onsuccess = function(event) {
811 aCallback(success, event);
813 request.onerror = function(event) {
814 // Errors can be handled here.
816 aCallback(success, event);
820 unsetDBCache: function(aKey, aCallback) {
824 var transaction = mainDB.transaction([this.objStore], "readwrite");
825 var request = transaction.objectStore(this.objStore).delete(aKey);
826 request.onsuccess = function(event) {
829 aCallback(success, event);
831 request.onerror = function(event) {
832 // Errors can be handled here.
834 aCallback(success, event);
838 clearDB: function(aCallback) {
842 var transaction = mainDB.transaction([this.objStore], "readwrite");
843 var request = transaction.objectStore(this.objStore).clear();
844 request.onsuccess = function(event) {
847 aCallback(success, event);
849 request.onerror = function(event) {
850 // Errors can be handled here.
852 aCallback(success, event);