optimize panning, and some cleanup
[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://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.'},
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 // XXX deprecated? see https://groups.google.com/forum/?fromgroups#!topic/mozilla.dev.planning/kuhrORubaRY[1-25]
150 gTrackCanvas.addEventListener("DOMMouseScroll", mapEvHandler, false);
151 gTrackCanvas.addEventListener("mousewheel", mapEvHandler, false);
152
153 document.getElementById("copyright").innerHTML =
154 gMapStyles[gActiveMap].copyright;
155
156 gLoadingTile = new Image();
157 gLoadingTile.src = "style/loading.png";
158 gWaitCounter++;
159 gLoadingTile.onload = function() { gWaitCounter--; };
160}
161
162function 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;
170 drawMap();
171 showUI();
172 }
173}
174
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
177
178function zoomIn() {
179 if (gPos.z < gMaxZoom) {
180 gPos.z++;
181 drawMap();
182 }
183}
184
185function zoomOut() {
186 if (gPos.z > 0) {
187 gPos.z--;
188 drawMap();
189 }
190}
191
192function gps2xy(aLatitude, aLongitude) {
193 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
194 var convLat = aLatitude * Math.PI / 180;
195 var rawY = (1 - Math.log(Math.tan(convLat) +
196 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
197 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
198 return {x: Math.round(rawX),
199 y: Math.round(rawY)};
200}
201
202function xy2gps(aX, aY) {
203 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
204 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
205 return {latitude: 180 / Math.PI *
206 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
207 longitude: aX / maxZoomFactor * 360 - 180};
208}
209
210function setMapStyle() {
211 var mapSel = document.getElementById("mapSelector");
212 if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
213 gActiveMap = mapSel.value;
214 document.getElementById("copyright").innerHTML =
215 gMapStyles[gActiveMap].copyright;
216 showUI();
217 drawMap();
218 }
219}
220
221// A sane mod function that works for negative numbers.
222// Returns a % b.
223function mod(a, b) {
224 return ((a % b) + b) % b;
225}
226
227function normalizeCoords(aCoords) {
228 var zoomFactor = Math.pow(2, aCoords.z);
229 return {x: mod(aCoords.x, zoomFactor),
230 y: mod(aCoords.y, zoomFactor),
231 z: aCoords.z};
232}
233
234// Returns true if the tile is outside the current view.
235function isOutsideWindow(t) {
236 var pos = decodeIndex(t);
237
238 var zoomFactor = Math.pow(2, gMaxZoom - pos.z);
239 var wid = gMapCanvas.width * zoomFactor;
240 var ht = gMapCanvas.height * zoomFactor;
241
242 pos.x *= zoomFactor;
243 pos.y *= zoomFactor;
244
245 var sz = gTileSize * zoomFactor;
246 if (pos.x > gPos.x + wid / 2 || pos.y > gPos.y + ht / 2 ||
247 pos.x + sz < gPos.x - wid / 2 || pos.y - sz < gPos.y - ht / 2)
248 return true;
249 return false;
250}
251
252function encodeIndex(x, y, z) {
253 var norm = normalizeCoords({x: x, y: y, z: z});
254 return norm.x + "," + norm.y + "," + norm.z;
255}
256
257function decodeIndex(encodedIdx) {
258 var ind = encodedIdx.split(",", 3);
259 return {x: ind[0], y: ind[1], z: ind[2]};
260}
261
262function drawMap(aPixels, aOverdraw) {
263 // aPixels is an object with left/right/top/bottom members telling how many
264 // pixels on the borders should actually be drawn.
265 // aOverdraw is a bool that tells if we should draw placeholders or draw
266 // straight over the existing content.
267 if (!aPixels)
268 aPixels = {left: gMapCanvas.width, right: gMapCanvas.width,
269 top: gMapCanvas.height, bottom: gMapCanvas.height};
270 if (!aOverdraw)
271 aOverdraw = false;
272
273 document.getElementById("zoomLevel").textContent = gPos.z;
274 gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
275 var wid = gMapCanvas.width * gZoomFactor; // Width in level 18 pixels.
276 var ht = gMapCanvas.height * gZoomFactor; // Height in level 18 pixels.
277 var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
278
279 var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
280 var yMin = gPos.y - ht / 2;
281 var xMax = gPos.x + wid / 2;
282 var yMax = gPos.y + ht / 2;
283
284 if (gMapPrefsLoaded && mainDB)
285 gPrefs.set("position", gPos);
286
287 var tiles = {left: Math.ceil((xMin + aPixels.left * gZoomFactor) / size) -
288 (aPixels.left ? 0 : 1),
289 right: Math.floor((xMax - aPixels.right * gZoomFactor) / size) -
290 (aPixels.right ? 1 : 0),
291 top: Math.ceil((yMin + aPixels.top * gZoomFactor) / size) -
292 (aPixels.top ? 0 : 1),
293 bottom: Math.floor((yMax - aPixels.bottom * gZoomFactor) / size) -
294 (aPixels.bottom ? 1 : 0)};
295
296 // Go through all the tiles in the map, find out if to draw them and do so.
297 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
298 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
299 // Only go to the drawing step if we need to draw this tile.
300 if (x < tiles.left || x > tiles.right || y < tiles.top || y > tiles.bottom) {
301 // Round here is **CRUCIAL** otherwise the images are filtered
302 // and the performance sucks (more than expected).
303 var xoff = Math.round((x * size - xMin) / gZoomFactor);
304 var yoff = Math.round((y * size - yMin) / gZoomFactor);
305 // Draw placeholder tile unless we overdraw.
306 if (!aOverdraw)
307 gMapContext.drawImage(gLoadingTile, xoff, yoff);
308
309 // Initiate loading/drawing of the actual tile.
310 gTileService.get(gActiveMap, {x: x, y: y, z: gPos.z},
311 function(aImage, aStyle, aCoords) {
312 // Only draw if this applies for the current view.
313 if ((aStyle == gActiveMap) && (aCoords.z == gPos.z)) {
314 var ixMin = gPos.x - wid / 2;
315 var iyMin = gPos.y - ht / 2;
316 var ixoff = Math.round((aCoords.x * size - ixMin) / gZoomFactor);
317 var iyoff = Math.round((aCoords.y * size - iyMin) / gZoomFactor);
318 var URL = window.URL;
319 var imgURL = URL.createObjectURL(aImage);
320 var imgObj = new Image();
321 imgObj.src = imgURL;
322 imgObj.onload = function() {
323 gMapContext.drawImage(imgObj, ixoff, iyoff);
324 URL.revokeObjectURL(imgURL);
325 }
326 }
327 });
328 }
329 }
330 }
331 gLastDrawnPoint = null;
332 gCurPosMapCache = undefined;
333 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
334 if (gTrack.length) {
335 for (var i = 0; i < gTrack.length; i++) {
336 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
337 (i + 1 >= gTrack.length));
338 }
339 }
340}
341
342function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
343 var trackpoint = gps2xy(aLatitude, aLongitude);
344 // lastPoint is for optimizing (not actually executing the draw until the last)
345 trackpoint.optimized = (lastPoint === false);
346 var mappos = {x: Math.round((trackpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
347 y: Math.round((trackpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
348
349 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
350 gTrackContext.strokeStyle = gTrackColor;
351 gTrackContext.fillStyle = gTrackContext.strokeStyle;
352 gTrackContext.lineWidth = gTrackWidth;
353 gTrackContext.lineCap = "round";
354 gTrackContext.lineJoin = "round";
355 }
356 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
357 // This breaks optimiziation, so make sure to close path and reset optimization.
358 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
359 gTrackContext.stroke();
360 gTrackContext.beginPath();
361 trackpoint.optimized = false;
362 gTrackContext.arc(mappos.x, mappos.y,
363 gTrackContext.lineWidth, 0, Math.PI * 2, false);
364 gTrackContext.fill();
365 }
366 else {
367 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
368 gTrackContext.beginPath();
369 gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
370 Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2));
371 }
372 gTrackContext.lineTo(mappos.x, mappos.y);
373 if (!trackpoint.optimized)
374 gTrackContext.stroke();
375 }
376 gLastDrawnPoint = trackpoint;
377}
378
379function drawCurrentLocation(trackPoint) {
380 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
381 var circleRadius = Math.round(gCurLocSize / 2);
382 var mappos = {x: Math.round((locpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
383 y: Math.round((locpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
384
385 undrawCurrentLocation();
386
387 // Cache overdrawn area.
388 gCurPosMapCache =
389 {point: locpoint,
390 radius: circleRadius,
391 data: gTrackContext.getImageData(mappos.x - circleRadius,
392 mappos.y - circleRadius,
393 circleRadius * 2, circleRadius * 2)};
394
395 gTrackContext.strokeStyle = gCurLocColor;
396 gTrackContext.fillStyle = gTrackContext.strokeStyle;
397 gTrackContext.beginPath();
398 gTrackContext.arc(mappos.x, mappos.y,
399 circleRadius, 0, Math.PI * 2, false);
400 gTrackContext.fill();
401}
402
403function undrawCurrentLocation() {
404 if (gCurPosMapCache) {
405 var oldpoint = gCurPosMapCache.point;
406 var oldmp = {x: Math.round((oldpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
407 y: Math.round((oldpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
408 gTrackContext.putImageData(gCurPosMapCache.data,
409 oldmp.x - gCurPosMapCache.radius,
410 oldmp.y - gCurPosMapCache.radius);
411 gCurPosMapCache = undefined;
412 }
413}
414
415var mapEvHandler = {
416 handleEvent: function(aEvent) {
417 var touchEvent = aEvent.type.indexOf('touch') != -1;
418
419 // Bail out on unwanted map moves, but not zoom-changing events.
420 if (aEvent.type != "DOMMouseScroll" && aEvent.type != "mousewheel") {
421 // Bail out if this is neither a touch nor left-click.
422 if (!touchEvent && aEvent.button != 0)
423 return;
424
425 // Bail out if the started touch can't be found.
426 if (touchEvent && gDragging &&
427 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
428 return;
429 }
430
431 var coordObj = touchEvent ?
432 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
433 aEvent;
434
435 switch (aEvent.type) {
436 case "mousedown":
437 case "touchstart":
438 if (touchEvent) {
439 gDragTouchID = aEvent.changedTouches.item(0).identifier;
440 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
441 }
442 var x = coordObj.clientX - gMapCanvas.offsetLeft;
443 var y = coordObj.clientY - gMapCanvas.offsetTop;
444
445 if (touchEvent || aEvent.button === 0) {
446 gDragging = true;
447 }
448 gLastMouseX = x;
449 gLastMouseY = y;
450 showUI();
451 break;
452 case "mousemove":
453 case "touchmove":
454 var x = coordObj.clientX - gMapCanvas.offsetLeft;
455 var y = coordObj.clientY - gMapCanvas.offsetTop;
456 if (gDragging === true) {
457 var dX = x - gLastMouseX;
458 var dY = y - gLastMouseY;
459 gPos.x -= dX * gZoomFactor;
460 gPos.y -= dY * gZoomFactor;
461 var mapData = gMapContext.getImageData(0, 0, gMapCanvas.width, gMapCanvas.height);
462 gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
463 gMapContext.putImageData(mapData, dX, dY);
464 drawMap({left: (dX > 0) ? dX : 0,
465 right: (dX < 0) ? -dX : 0,
466 top: (dY > 0) ? dY : 0,
467 bottom: (dY < 0) ? -dY : 0});
468 showUI();
469 }
470 gLastMouseX = x;
471 gLastMouseY = y;
472 break;
473 case "mouseup":
474 case "touchend":
475 gDragging = false;
476 showUI();
477 break;
478 case "mouseout":
479 case "touchcancel":
480 case "touchleave":
481 //gDragging = false;
482 break;
483 case "DOMMouseScroll":
484 case "mousewheel":
485 var delta = 0;
486 if (aEvent.wheelDelta) {
487 delta = aEvent.wheelDelta / 120;
488 if (window.opera)
489 delta = -delta;
490 }
491 else if (aEvent.detail) {
492 delta = -aEvent.detail / 3;
493 }
494
495 // Debug output: "coordinates" of the point the mouse was over.
496 /*
497 var ptCoord = {x: gPos.x + (x - gMapCanvas.width / 2) * gZoomFactor,
498 y: gPos.y + (x - gMapCanvas.height / 2) * gZoomFactor};
499 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
500 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
501 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
502 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
503 pt2Coord.x + "/" + pt2Coord.y);
504 */
505
506 var newZoomLevel = gPos.z + (delta > 0 ? 1 : -1);
507 if ((newZoomLevel >= 0) && (newZoomLevel <= gMaxZoom)) {
508 // Calculate new center of the map - same point stays under the mouse.
509 // This means that the pixel distance between the old center and point
510 // must equal the pixel distance of the new center and that point.
511 var x = coordObj.clientX - gMapCanvas.offsetLeft;
512 var y = coordObj.clientY - gMapCanvas.offsetTop;
513
514 // Zoom factor after this action.
515 var newZoomFactor = Math.pow(2, gMaxZoom - newZoomLevel);
516 gPos.x -= (x - gMapCanvas.width / 2) * (newZoomFactor - gZoomFactor);
517 gPos.y -= (y - gMapCanvas.height / 2) * (newZoomFactor - gZoomFactor);
518
519 if (delta > 0)
520 zoomIn();
521 else if (delta < 0)
522 zoomOut();
523 }
524 break;
525 }
526 }
527};
528
529var geofake = {
530 tracking: false,
531 lastPos: {x: undefined, y: undefined},
532 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
533 this.tracking = true;
534 var watchCall = function() {
535 // calc new position in lat/lon degrees
536 // 90° on Earth surface are ~10,000 km at the equator,
537 // so try moving at most 10m at a time
538 if (geofake.lastPos.x)
539 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
540 else
541 geofake.lastPos.x = 48.208174
542 if (geofake.lastPos.y)
543 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
544 else
545 geofake.lastPos.y = 16.373819
546 aSuccessCallback({timestamp: Date.now(),
547 coords: {latitude: geofake.lastPos.x,
548 longitude: geofake.lastPos.y,
549 accuracy: 20}});
550 if (geofake.tracking)
551 setTimeout(watchCall, 1000);
552 };
553 setTimeout(watchCall, 1000);
554 return "foo";
555 },
556 clearWatch: function(aID) {
557 this.tracking = false;
558 }
559}
560
561function setCentering(aCheckbox) {
562 if (gMapPrefsLoaded && mainDB)
563 gPrefs.set("center_map", aCheckbox.checked);
564 gCenterPosition = aCheckbox.checked;
565}
566
567function setTracking(aCheckbox) {
568 if (gMapPrefsLoaded && mainDB)
569 gPrefs.set("tracking_enabled", aCheckbox.checked);
570 if (aCheckbox.checked)
571 startTracking();
572 else
573 endTracking();
574}
575
576function startTracking() {
577 if (gGeolocation) {
578 gGeoWatchID = gGeolocation.watchPosition(
579 function(position) {
580 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
581 var tPoint = {time: position.timestamp,
582 coords: {latitude: position.coords.latitude,
583 longitude: position.coords.longitude,
584 altitude: position.coords.altitude,
585 accuracy: position.coords.accuracy,
586 altitudeAccuracy: position.coords.altitudeAccuracy,
587 heading: position.coords.heading,
588 speed: position.coords.speed},
589 beginSegment: !gLastTrackPoint};
590 // Only add point to track is accuracy is good enough.
591 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
592 gLastTrackPoint = tPoint;
593 gTrack.push(tPoint);
594 try { gTrackStore.push(tPoint); } catch(e) {}
595 var redrawn = false;
596 if (gCenterPosition) {
597 var posCoord = gps2xy(position.coords.latitude,
598 position.coords.longitude);
599 if (Math.abs(gPos.x - posCoord.x) > gMapCanvas.width * gZoomFactor / 4 ||
600 Math.abs(gPos.y - posCoord.y) > gMapCanvas.height * gZoomFactor / 4) {
601 gPos.x = posCoord.x;
602 gPos.y = posCoord.y;
603 drawMap(); // This draws the current point as well.
604 redrawn = true;
605 }
606 }
607 if (!redrawn)
608 undrawCurrentLocation();
609 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
610 }
611 drawCurrentLocation(tPoint);
612 },
613 function(error) {
614 // Ignore erros for the moment, but this is good for debugging.
615 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
616 if (gDebug)
617 console.log(error.message);
618 },
619 {enableHighAccuracy: true}
620 );
621 }
622}
623
624function endTracking() {
625 if (gGeoWatchID) {
626 gGeolocation.clearWatch(gGeoWatchID);
627 }
628}
629
630function clearTrack() {
631 gTrack = [];
632 gTrackStore.clear();
633 drawMap();
634}
635
636var gTileService = {
637 objStore: "tilecache",
638
639 get: function(aStyle, aCoords, aCallback) {
640 var norm = normalizeCoords(aCoords);
641 var dbkey = aStyle + "::" + norm.x + "," + norm.y + "," + norm.z;
642 this.getDBCache(dbkey, function(aResult, aEvent) {
643 if (aResult) {
644 // We did get a cached object.
645 // TODO: Look at the timestamp and trigger a reload when it's too old.
646 aCallback(aResult.image, aStyle, aCoords);
647 }
648 else {
649 // Retrieve image from the web and store it in the cache.
650 var XHR = new XMLHttpRequest();
651 XHR.open("GET",
652 gMapStyles[aStyle].url
653 .replace("{x}", norm.x)
654 .replace("{y}", norm.y)
655 .replace("{z}", norm.z)
656 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
657 .replace("[1-4]", 1 + Math.floor(Math.random() * 3)),
658 true);
659 XHR.responseType = "blob";
660 XHR.addEventListener("load", function () {
661 if (XHR.status === 200) {
662 var blob = XHR.response;
663 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
664 aCallback(blob, aStyle, aCoords);
665 }
666 }, false);
667 XHR.send();
668 }
669 });
670 },
671
672 getDBCache: function(aKey, aCallback) {
673 if (!mainDB)
674 return;
675 var transaction = mainDB.transaction([this.objStore]);
676 var request = transaction.objectStore(this.objStore).get(aKey);
677 request.onsuccess = function(event) {
678 aCallback(request.result, event);
679 };
680 request.onerror = function(event) {
681 // Errors can be handled here.
682 aCallback(undefined, event);
683 };
684 },
685
686 setDBCache: function(aKey, aValue, aCallback) {
687 if (!mainDB)
688 return;
689 var success = false;
690 var transaction = mainDB.transaction([this.objStore], "readwrite");
691 var objStore = transaction.objectStore(this.objStore);
692 var request = objStore.put(aValue, aKey);
693 request.onsuccess = function(event) {
694 success = true;
695 if (aCallback)
696 aCallback(success, event);
697 };
698 request.onerror = function(event) {
699 // Errors can be handled here.
700 if (aCallback)
701 aCallback(success, event);
702 };
703 },
704
705 unsetDBCache: function(aKey, aCallback) {
706 if (!mainDB)
707 return;
708 var success = false;
709 var transaction = mainDB.transaction([this.objStore], "readwrite");
710 var request = transaction.objectStore(this.objStore).delete(aKey);
711 request.onsuccess = function(event) {
712 success = true;
713 if (aCallback)
714 aCallback(success, event);
715 };
716 request.onerror = function(event) {
717 // Errors can be handled here.
718 if (aCallback)
719 aCallback(success, event);
720 }
721 }
722};