don't clear the map when clearing the track
[lantea.git] / js / map.js
... / ...
CommitLineData
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/. */
4
5var gMapCanvas, gMapContext, gTrackCanvas, gTrackContext, gGeolocation;
6var gDebug = false;
7
8var gTileSize = 256;
9var gMaxZoom = 18; // The minimum is 0.
10
11var gMinTrackAccuracy = 1000; // meters
12var gTrackWidth = 2; // pixels
13var gTrackColor = "#FF0000";
14var gCurLocSize = 6; // pixels
15var gCurLocColor = "#A00000";
16
17var gMapStyles = {
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
20 osm_mapnik:
21 {name: "OpenStreetMap (Mapnik)",
22 url: "http://tile.openstreetmap.org/{z}/{x}/{y}.png",
23 copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
24 osm_cyclemap:
25 {name: "Cycle Map (OSM)",
26 url: "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
27 copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
28 osm_transmap:
29 {name: "Transport Map (OSM)",
30 url: "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png",
31 copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
32 mapquest_open:
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 &copy; <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>.'},
36 mapquest_aerial:
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.'},
40 opengeoserver_arial:
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>.'},
44 google_map:
45 {name: "Google Maps",
46 url: " http://mt1.google.com/vt/x={x}&y={y}&z={z}",
47 copyright: 'Map data and imagery &copy; <a href="http://maps.google.com/">Google</a>'},
48};
49var gActiveMap = "osm_mapnik";
50
51var 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.
54
55var gLastMouseX = 0;
56var gLastMouseY = 0;
57var gZoomFactor;
58
59var gLoadingTile;
60
61var gMapPrefsLoaded = false;
62
63var gDragging = false;
64var gDragTouchID;
65
66var gGeoWatchID;
67var gTrack = [];
68var gLastTrackPoint, gLastDrawnPoint;
69var gCenterPosition = true;
70
71var gCurPosMapCache;
72
73function initMap() {
74 gGeolocation = navigator.geolocation;
75 gMapCanvas = document.getElementById("map");
76 gMapContext = gMapCanvas.getContext("2d");
77 gTrackCanvas = document.getElementById("track");
78 gTrackContext = gTrackCanvas.getContext("2d");
79 if (!gActiveMap)
80 gActiveMap = "osm_mapnik";
81
82 //gDebug = true;
83 if (gDebug) {
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");
89 }
90 }
91
92 var loopCnt = 0;
93 var getPersistentPrefs = function() {
94 if (mainDB) {
95 gWaitCounter++;
96 gPrefs.get("position", function(aValue) {
97 if (aValue) {
98 gPos = aValue;
99 gWaitCounter--;
100 }
101 });
102 gWaitCounter++;
103 gPrefs.get("center_map", function(aValue) {
104 if (aValue === undefined)
105 document.getElementById("centerCheckbox").checked = true;
106 else
107 document.getElementById("centerCheckbox").checked = aValue;
108 setCentering(document.getElementById("centerCheckbox"));
109 gWaitCounter--;
110 });
111 gWaitCounter++;
112 gPrefs.get("tracking_enabled", function(aValue) {
113 if (aValue === undefined)
114 document.getElementById("trackCheckbox").checked = true;
115 else
116 document.getElementById("trackCheckbox").checked = aValue;
117 gWaitCounter--;
118 });
119 gWaitCounter++;
120 gTrackStore.getList(function(aTPoints) {
121 if (gDebug)
122 console.log(aTPoints.length + " points loaded.");
123 if (aTPoints.length) {
124 gTrack = aTPoints;
125 }
126 gWaitCounter--;
127 });
128 }
129 else
130 setTimeout(getPersistentPrefs, 100);
131 loopCnt++;
132 if (loopCnt > 50) {
133 console.log("Loading prefs failed.");
134 }
135 };
136 getPersistentPrefs();
137
138 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
139 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
140 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
141 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
142
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);
148
149 gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
150
151 document.getElementById("copyright").innerHTML =
152 gMapStyles[gActiveMap].copyright;
153
154 gLoadingTile = new Image();
155 gLoadingTile.src = "style/loading.png";
156 gWaitCounter++;
157 gLoadingTile.onload = function() { gWaitCounter--; };
158}
159
160function resizeAndDraw() {
161 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
162 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
163 if (gMapCanvas && gTrackCanvas) {
164 gMapCanvas.width = viewportWidth;
165 gMapCanvas.height = viewportHeight;
166 gTrackCanvas.width = viewportWidth;
167 gTrackCanvas.height = viewportHeight;
168 drawMap();
169 showUI();
170 }
171}
172
173// Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
174// See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
175
176function zoomIn() {
177 if (gPos.z < gMaxZoom) {
178 gPos.z++;
179 drawMap();
180 }
181}
182
183function zoomOut() {
184 if (gPos.z > 0) {
185 gPos.z--;
186 drawMap();
187 }
188}
189
190function gps2xy(aLatitude, aLongitude) {
191 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
192 var convLat = aLatitude * Math.PI / 180;
193 var rawY = (1 - Math.log(Math.tan(convLat) +
194 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
195 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
196 return {x: Math.round(rawX),
197 y: Math.round(rawY)};
198}
199
200function xy2gps(aX, aY) {
201 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
202 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
203 return {latitude: 180 / Math.PI *
204 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
205 longitude: aX / maxZoomFactor * 360 - 180};
206}
207
208function setMapStyle() {
209 var mapSel = document.getElementById("mapSelector");
210 if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
211 gActiveMap = mapSel.value;
212 document.getElementById("copyright").innerHTML =
213 gMapStyles[gActiveMap].copyright;
214 showUI();
215 drawMap();
216 }
217}
218
219// A sane mod function that works for negative numbers.
220// Returns a % b.
221function mod(a, b) {
222 return ((a % b) + b) % b;
223}
224
225function normalizeCoords(aCoords) {
226 var zoomFactor = Math.pow(2, aCoords.z);
227 return {x: mod(aCoords.x, zoomFactor),
228 y: mod(aCoords.y, zoomFactor),
229 z: aCoords.z};
230}
231
232// Returns true if the tile is outside the current view.
233function isOutsideWindow(t) {
234 var pos = decodeIndex(t);
235
236 var zoomFactor = Math.pow(2, gMaxZoom - pos.z);
237 var wid = gMapCanvas.width * zoomFactor;
238 var ht = gMapCanvas.height * zoomFactor;
239
240 pos.x *= zoomFactor;
241 pos.y *= zoomFactor;
242
243 var sz = gTileSize * zoomFactor;
244 if (pos.x > gPos.x + wid / 2 || pos.y > gPos.y + ht / 2 ||
245 pos.x + sz < gPos.x - wid / 2 || pos.y - sz < gPos.y - ht / 2)
246 return true;
247 return false;
248}
249
250function encodeIndex(x, y, z) {
251 var norm = normalizeCoords({x: x, y: y, z: z});
252 return norm.x + "," + norm.y + "," + norm.z;
253}
254
255function decodeIndex(encodedIdx) {
256 var ind = encodedIdx.split(",", 3);
257 return {x: ind[0], y: ind[1], z: ind[2]};
258}
259
260function drawMap(aPixels, aOverdraw) {
261 // aPixels is an object with left/right/top/bottom members telling how many
262 // pixels on the borders should actually be drawn.
263 // aOverdraw is a bool that tells if we should draw placeholders or draw
264 // straight over the existing content.
265 if (!aPixels)
266 aPixels = {left: gMapCanvas.width, right: gMapCanvas.width,
267 top: gMapCanvas.height, bottom: gMapCanvas.height};
268 if (!aOverdraw)
269 aOverdraw = false;
270
271 document.getElementById("zoomLevel").textContent = gPos.z;
272 gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
273 var wid = gMapCanvas.width * gZoomFactor; // Width in level 18 pixels.
274 var ht = gMapCanvas.height * gZoomFactor; // Height in level 18 pixels.
275 var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
276
277 var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
278 var yMin = gPos.y - ht / 2;
279 var xMax = gPos.x + wid / 2;
280 var yMax = gPos.y + ht / 2;
281
282 if (gMapPrefsLoaded && mainDB)
283 gPrefs.set("position", gPos);
284
285 var tiles = {left: Math.ceil((xMin + aPixels.left * gZoomFactor) / size) -
286 (aPixels.left ? 0 : 1),
287 right: Math.floor((xMax - aPixels.right * gZoomFactor) / size) -
288 (aPixels.right ? 1 : 0),
289 top: Math.ceil((yMin + aPixels.top * gZoomFactor) / size) -
290 (aPixels.top ? 0 : 1),
291 bottom: Math.floor((yMax - aPixels.bottom * gZoomFactor) / size) -
292 (aPixels.bottom ? 1 : 0)};
293
294 // Go through all the tiles in the map, find out if to draw them and do so.
295 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
296 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
297 // Only go to the drawing step if we need to draw this tile.
298 if (x < tiles.left || x > tiles.right ||
299 y < tiles.top || y > tiles.bottom) {
300 // Round here is **CRUCIAL** otherwise the images are filtered
301 // and the performance sucks (more than expected).
302 var xoff = Math.round((x * size - xMin) / gZoomFactor);
303 var yoff = Math.round((y * size - yMin) / gZoomFactor);
304 // Draw placeholder tile unless we overdraw.
305 if (!aOverdraw &&
306 (x < tiles.left -1 || x > tiles.right + 1 ||
307 y < tiles.top -1 || y > tiles.bottom + 1))
308 gMapContext.drawImage(gLoadingTile, xoff, yoff);
309
310 // Initiate loading/drawing of the actual tile.
311 gTileService.get(gActiveMap, {x: x, y: y, z: gPos.z},
312 function(aImage, aStyle, aCoords) {
313 // Only draw if this applies for the current view.
314 if ((aStyle == gActiveMap) && (aCoords.z == gPos.z)) {
315 var ixMin = gPos.x - wid / 2;
316 var iyMin = gPos.y - ht / 2;
317 var ixoff = Math.round((aCoords.x * size - ixMin) / gZoomFactor);
318 var iyoff = Math.round((aCoords.y * size - iyMin) / gZoomFactor);
319 var URL = window.URL;
320 var imgURL = URL.createObjectURL(aImage);
321 var imgObj = new Image();
322 imgObj.src = imgURL;
323 imgObj.onload = function() {
324 gMapContext.drawImage(imgObj, ixoff, iyoff);
325 URL.revokeObjectURL(imgURL);
326 }
327 }
328 });
329 }
330 }
331 }
332 gLastDrawnPoint = null;
333 gCurPosMapCache = undefined;
334 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
335 if (gTrack.length) {
336 for (var i = 0; i < gTrack.length; i++) {
337 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
338 (i + 1 >= gTrack.length));
339 }
340 }
341}
342
343function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
344 var trackpoint = gps2xy(aLatitude, aLongitude);
345 // lastPoint is for optimizing (not actually executing the draw until the last)
346 trackpoint.optimized = (lastPoint === false);
347 var mappos = {x: Math.round((trackpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
348 y: Math.round((trackpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
349
350 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
351 gTrackContext.strokeStyle = gTrackColor;
352 gTrackContext.fillStyle = gTrackContext.strokeStyle;
353 gTrackContext.lineWidth = gTrackWidth;
354 gTrackContext.lineCap = "round";
355 gTrackContext.lineJoin = "round";
356 }
357 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
358 // This breaks optimiziation, so make sure to close path and reset optimization.
359 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
360 gTrackContext.stroke();
361 gTrackContext.beginPath();
362 trackpoint.optimized = false;
363 gTrackContext.arc(mappos.x, mappos.y,
364 gTrackContext.lineWidth, 0, Math.PI * 2, false);
365 gTrackContext.fill();
366 }
367 else {
368 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
369 gTrackContext.beginPath();
370 gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
371 Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2));
372 }
373 gTrackContext.lineTo(mappos.x, mappos.y);
374 if (!trackpoint.optimized)
375 gTrackContext.stroke();
376 }
377 gLastDrawnPoint = trackpoint;
378}
379
380function drawCurrentLocation(trackPoint) {
381 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
382 var circleRadius = Math.round(gCurLocSize / 2);
383 var mappos = {x: Math.round((locpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
384 y: Math.round((locpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
385
386 undrawCurrentLocation();
387
388 // Cache overdrawn area.
389 gCurPosMapCache =
390 {point: locpoint,
391 radius: circleRadius,
392 data: gTrackContext.getImageData(mappos.x - circleRadius,
393 mappos.y - circleRadius,
394 circleRadius * 2, circleRadius * 2)};
395
396 gTrackContext.strokeStyle = gCurLocColor;
397 gTrackContext.fillStyle = gTrackContext.strokeStyle;
398 gTrackContext.beginPath();
399 gTrackContext.arc(mappos.x, mappos.y,
400 circleRadius, 0, Math.PI * 2, false);
401 gTrackContext.fill();
402}
403
404function undrawCurrentLocation() {
405 if (gCurPosMapCache) {
406 var oldpoint = gCurPosMapCache.point;
407 var oldmp = {x: Math.round((oldpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
408 y: Math.round((oldpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
409 gTrackContext.putImageData(gCurPosMapCache.data,
410 oldmp.x - gCurPosMapCache.radius,
411 oldmp.y - gCurPosMapCache.radius);
412 gCurPosMapCache = undefined;
413 }
414}
415
416var mapEvHandler = {
417 handleEvent: function(aEvent) {
418 var touchEvent = aEvent.type.indexOf('touch') != -1;
419
420 // Bail out on unwanted map moves, but not zoom-changing events.
421 if (aEvent.type != "DOMMouseScroll" && aEvent.type != "mousewheel") {
422 // Bail out if this is neither a touch nor left-click.
423 if (!touchEvent && aEvent.button != 0)
424 return;
425
426 // Bail out if the started touch can't be found.
427 if (touchEvent && gDragging &&
428 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
429 return;
430 }
431
432 var coordObj = touchEvent ?
433 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
434 aEvent;
435
436 switch (aEvent.type) {
437 case "mousedown":
438 case "touchstart":
439 if (touchEvent) {
440 gDragTouchID = aEvent.changedTouches.item(0).identifier;
441 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
442 }
443 var x = coordObj.clientX - gMapCanvas.offsetLeft;
444 var y = coordObj.clientY - gMapCanvas.offsetTop;
445
446 if (touchEvent || aEvent.button === 0) {
447 gDragging = true;
448 }
449 gLastMouseX = x;
450 gLastMouseY = y;
451 showUI();
452 break;
453 case "mousemove":
454 case "touchmove":
455 var x = coordObj.clientX - gMapCanvas.offsetLeft;
456 var y = coordObj.clientY - gMapCanvas.offsetTop;
457 if (gDragging === true) {
458 var dX = x - gLastMouseX;
459 var dY = y - gLastMouseY;
460 gPos.x -= dX * gZoomFactor;
461 gPos.y -= dY * gZoomFactor;
462 var mapData = gMapContext.getImageData(0, 0, gMapCanvas.width, gMapCanvas.height);
463 gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
464 gMapContext.putImageData(mapData, dX, dY);
465 drawMap({left: (dX > 0) ? dX : 0,
466 right: (dX < 0) ? -dX : 0,
467 top: (dY > 0) ? dY : 0,
468 bottom: (dY < 0) ? -dY : 0});
469 showUI();
470 }
471 gLastMouseX = x;
472 gLastMouseY = y;
473 break;
474 case "mouseup":
475 case "touchend":
476 gDragging = false;
477 showUI();
478 break;
479 case "mouseout":
480 case "touchcancel":
481 case "touchleave":
482 //gDragging = false;
483 break;
484 case "wheel":
485 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
486 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
487
488 // Only accept (non-null) deltaY values
489 if (!aEvent.deltaY)
490 break;
491
492 // Debug output: "coordinates" of the point the mouse was over.
493 /*
494 var ptCoord = {x: gPos.x + (x - gMapCanvas.width / 2) * gZoomFactor,
495 y: gPos.y + (x - gMapCanvas.height / 2) * gZoomFactor};
496 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
497 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
498 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
499 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
500 pt2Coord.x + "/" + pt2Coord.y);
501 */
502
503 var newZoomLevel = gPos.z + (aEvent.deltaY < 0 ? 1 : -1);
504 if ((newZoomLevel >= 0) && (newZoomLevel <= gMaxZoom)) {
505 // Calculate new center of the map - same point stays under the mouse.
506 // This means that the pixel distance between the old center and point
507 // must equal the pixel distance of the new center and that point.
508 var x = coordObj.clientX - gMapCanvas.offsetLeft;
509 var y = coordObj.clientY - gMapCanvas.offsetTop;
510
511 // Zoom factor after this action.
512 var newZoomFactor = Math.pow(2, gMaxZoom - newZoomLevel);
513 gPos.x -= (x - gMapCanvas.width / 2) * (newZoomFactor - gZoomFactor);
514 gPos.y -= (y - gMapCanvas.height / 2) * (newZoomFactor - gZoomFactor);
515
516 if (aEvent.deltaY < 0)
517 zoomIn();
518 else
519 zoomOut();
520 }
521 break;
522 }
523 }
524};
525
526var geofake = {
527 tracking: false,
528 lastPos: {x: undefined, y: undefined},
529 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
530 this.tracking = true;
531 var watchCall = function() {
532 // calc new position in lat/lon degrees
533 // 90° on Earth surface are ~10,000 km at the equator,
534 // so try moving at most 10m at a time
535 if (geofake.lastPos.x)
536 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
537 else
538 geofake.lastPos.x = 48.208174
539 if (geofake.lastPos.y)
540 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
541 else
542 geofake.lastPos.y = 16.373819
543 aSuccessCallback({timestamp: Date.now(),
544 coords: {latitude: geofake.lastPos.x,
545 longitude: geofake.lastPos.y,
546 accuracy: 20}});
547 if (geofake.tracking)
548 setTimeout(watchCall, 1000);
549 };
550 setTimeout(watchCall, 1000);
551 return "foo";
552 },
553 clearWatch: function(aID) {
554 this.tracking = false;
555 }
556}
557
558function setCentering(aCheckbox) {
559 if (gMapPrefsLoaded && mainDB)
560 gPrefs.set("center_map", aCheckbox.checked);
561 gCenterPosition = aCheckbox.checked;
562}
563
564function setTracking(aCheckbox) {
565 if (gMapPrefsLoaded && mainDB)
566 gPrefs.set("tracking_enabled", aCheckbox.checked);
567 if (aCheckbox.checked)
568 startTracking();
569 else
570 endTracking();
571}
572
573function startTracking() {
574 if (gGeolocation) {
575 gActionLabel.textContent = "Establishing Position";
576 gAction.style.display = "block";
577 gGeoWatchID = gGeolocation.watchPosition(
578 function(position) {
579 if (gActionLabel.textContent) {
580 gActionLabel.textContent = "";
581 gAction.style.display = "none";
582 }
583 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
584 var tPoint = {time: position.timestamp,
585 coords: {latitude: position.coords.latitude,
586 longitude: position.coords.longitude,
587 altitude: position.coords.altitude,
588 accuracy: position.coords.accuracy,
589 altitudeAccuracy: position.coords.altitudeAccuracy,
590 heading: position.coords.heading,
591 speed: position.coords.speed},
592 beginSegment: !gLastTrackPoint};
593 // Only add point to track is accuracy is good enough.
594 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
595 gLastTrackPoint = tPoint;
596 gTrack.push(tPoint);
597 try { gTrackStore.push(tPoint); } catch(e) {}
598 var redrawn = false;
599 if (gCenterPosition) {
600 var posCoord = gps2xy(position.coords.latitude,
601 position.coords.longitude);
602 if (Math.abs(gPos.x - posCoord.x) > gMapCanvas.width * gZoomFactor / 4 ||
603 Math.abs(gPos.y - posCoord.y) > gMapCanvas.height * gZoomFactor / 4) {
604 gPos.x = posCoord.x;
605 gPos.y = posCoord.y;
606 drawMap(); // This draws the current point as well.
607 redrawn = true;
608 }
609 }
610 if (!redrawn)
611 undrawCurrentLocation();
612 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
613 }
614 drawCurrentLocation(tPoint);
615 },
616 function(error) {
617 // Ignore erros for the moment, but this is good for debugging.
618 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
619 if (gDebug)
620 console.log(error.message);
621 },
622 {enableHighAccuracy: true}
623 );
624 }
625}
626
627function endTracking() {
628 if (gActionLabel.textContent) {
629 gActionLabel.textContent = "";
630 gAction.style.display = "none";
631 }
632 if (gGeoWatchID) {
633 gGeolocation.clearWatch(gGeoWatchID);
634 }
635}
636
637function clearTrack() {
638 gTrack = [];
639 gTrackStore.clear();
640 drawMap({left: 0, right: 0, top: 0, bottom: 0});
641}
642
643var gTileService = {
644 objStore: "tilecache",
645
646 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
647
648 get: function(aStyle, aCoords, aCallback) {
649 var norm = normalizeCoords(aCoords);
650 var dbkey = aStyle + "::" + norm.x + "," + norm.y + "," + norm.z;
651 this.getDBCache(dbkey, function(aResult, aEvent) {
652 if (aResult) {
653 // We did get a cached object.
654 aCallback(aResult.image, aStyle, aCoords);
655 // Look at the timestamp and return if it's not too old.
656 if (aResult.timestamp + gTileService.ageLimit > Date.now())
657 return;
658 // Reload cached tile otherwise.
659 var oldDate = new Date(aResult.timestamp);
660 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
661 }
662 // Retrieve image from the web and store it in the cache.
663 var XHR = new XMLHttpRequest();
664 XHR.open("GET",
665 gMapStyles[aStyle].url
666 .replace("{x}", norm.x)
667 .replace("{y}", norm.y)
668 .replace("{z}", norm.z)
669 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
670 .replace("[1-4]", 1 + Math.floor(Math.random() * 3)),
671 true);
672 XHR.responseType = "blob";
673 XHR.addEventListener("load", function () {
674 if (XHR.status === 200) {
675 var blob = XHR.response;
676 aCallback(blob, aStyle, aCoords);
677 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
678 }
679 }, false);
680 XHR.send();
681 });
682 },
683
684 getDBCache: function(aKey, aCallback) {
685 if (!mainDB)
686 return;
687 var transaction = mainDB.transaction([this.objStore]);
688 var request = transaction.objectStore(this.objStore).get(aKey);
689 request.onsuccess = function(event) {
690 aCallback(request.result, event);
691 };
692 request.onerror = function(event) {
693 // Errors can be handled here.
694 aCallback(undefined, event);
695 };
696 },
697
698 setDBCache: function(aKey, aValue, aCallback) {
699 if (!mainDB)
700 return;
701 var success = false;
702 var transaction = mainDB.transaction([this.objStore], "readwrite");
703 var objStore = transaction.objectStore(this.objStore);
704 var request = objStore.put(aValue, aKey);
705 request.onsuccess = function(event) {
706 success = true;
707 if (aCallback)
708 aCallback(success, event);
709 };
710 request.onerror = function(event) {
711 // Errors can be handled here.
712 if (aCallback)
713 aCallback(success, event);
714 };
715 },
716
717 unsetDBCache: function(aKey, aCallback) {
718 if (!mainDB)
719 return;
720 var success = false;
721 var transaction = mainDB.transaction([this.objStore], "readwrite");
722 var request = transaction.objectStore(this.objStore).delete(aKey);
723 request.onsuccess = function(event) {
724 success = true;
725 if (aCallback)
726 aCallback(success, event);
727 };
728 request.onerror = function(event) {
729 // Errors can be handled here.
730 if (aCallback)
731 aCallback(success, event);
732 }
733 },
734
735 clearDB: function(aCallback) {
736 if (!mainDB)
737 return;
738 var success = false;
739 var transaction = mainDB.transaction([this.objStore], "readwrite");
740 var request = transaction.objectStore(this.objStore).clear();
741 request.onsuccess = function(event) {
742 success = true;
743 if (aCallback)
744 aCallback(success, event);
745 };
746 request.onerror = function(event) {
747 // Errors can be handled here.
748 if (aCallback)
749 aCallback(success, event);
750 }
751 }
752};