add a comment about crashing with drawing a blob
[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
59// Used as an associative array.
60// The keys have to be strings, ours will be "xindex,yindex,zindex" e.g. "13,245,12".
61var gTiles = {};
62var gLoadingTile;
63
64var gMapPrefsLoaded = false;
65
66var gDragging = false;
67var gDragTouchID;
68
69var gGeoWatchID;
70var gTrack = [];
71var gLastTrackPoint, gLastDrawnPoint;
72var gCenterPosition = true;
73
74var gCurPosMapCache;
75
76function initMap() {
77 gGeolocation = navigator.geolocation;
78 gMapCanvas = document.getElementById("map");
79 gMapContext = gMapCanvas.getContext("2d");
80 gTrackCanvas = document.getElementById("track");
81 gTrackContext = gTrackCanvas.getContext("2d");
82 if (!gActiveMap)
83 gActiveMap = "osm_mapnik";
84
85 //gDebug = true;
86 if (gDebug) {
87 gGeolocation = geofake;
88 var hiddenList = document.getElementsByClassName("debugHide");
89 // last to first - list of elements with that class is changing!
90 for (var i = hiddenList.length - 1; i >= 0; i--) {
91 hiddenList[i].classList.remove("debugHide");
92 }
93 }
94
95 var loopCnt = 0;
96 var getPersistentPrefs = function() {
97 if (mainDB) {
98 gWaitCounter++;
99 gPrefs.get("position", function(aValue) {
100 if (aValue) {
101 gPos = aValue;
102 gWaitCounter--;
103 }
104 });
105 gWaitCounter++;
106 gPrefs.get("center_map", function(aValue) {
107 if (aValue === undefined)
108 document.getElementById("centerCheckbox").checked = true;
109 else
110 document.getElementById("centerCheckbox").checked = aValue;
111 setCentering(document.getElementById("centerCheckbox"));
112 gWaitCounter--;
113 });
114 gWaitCounter++;
115 gPrefs.get("tracking_enabled", function(aValue) {
116 if (aValue === undefined)
117 document.getElementById("trackCheckbox").checked = true;
118 else
119 document.getElementById("trackCheckbox").checked = aValue;
120 gWaitCounter--;
121 });
122 gWaitCounter++;
123 gTrackStore.getList(function(aTPoints) {
124 if (gDebug)
125 document.getElementById("debug").textContent = aTPoints.length + " points loaded.";
126 if (aTPoints.length) {
127 gTrack = aTPoints;
128 }
129 gWaitCounter--;
130 });
131 }
132 else
133 setTimeout(getPersistentPrefs, 100);
134 loopCnt++;
135 if (loopCnt > 50) {
136 document.getElementById("debug").textContent = "Loading prefs failed.";
137 }
138 };
139 getPersistentPrefs();
140
141 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
142 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
143 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
144 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
145
146 gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
147 gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
148 gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
149 gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
150 gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
151
152 // XXX deprecated? see https://groups.google.com/forum/?fromgroups#!topic/mozilla.dev.planning/kuhrORubaRY[1-25]
153 gTrackCanvas.addEventListener("DOMMouseScroll", mapEvHandler, false);
154 gTrackCanvas.addEventListener("mousewheel", mapEvHandler, false);
155
156 document.getElementById("copyright").innerHTML =
157 gMapStyles[gActiveMap].copyright;
158
159 gLoadingTile = new Image();
160 gLoadingTile.src = "style/loading.png";
161 gWaitCounter++;
162 gLoadingTile.onload = function() { gWaitCounter--; };
163}
164
165function resizeAndDraw() {
166 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
167 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
168
169 gMapCanvas.width = viewportWidth;
170 gMapCanvas.height = viewportHeight;
171 gTrackCanvas.width = viewportWidth;
172 gTrackCanvas.height = viewportHeight;
173 drawMap();
174 showUI();
175}
176
177function zoomIn() {
178 if (gPos.z < gMaxZoom) {
179 gPos.z++;
180 drawMap();
181 }
182}
183
184function zoomOut() {
185 if (gPos.z > 0) {
186 gPos.z--;
187 drawMap();
188 }
189}
190
191function gps2xy(aLatitude, aLongitude) {
192 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
193 var convLat = aLatitude * Math.PI / 180;
194 var rawY = (1 - Math.log(Math.tan(convLat) +
195 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
196 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
197 return {x: Math.round(rawX),
198 y: Math.round(rawY)};
199}
200
201function xy2gps(aX, aY) {
202 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
203 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
204 return {latitude: 180 / Math.PI *
205 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
206 longitude: aX / maxZoomFactor * 360 - 180};
207}
208
209function setMapStyle() {
210 var mapSel = document.getElementById("mapSelector");
211 if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
212 gActiveMap = mapSel.value;
213 gTiles = {};
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() {
263 // Go through all the currently loaded tiles. If we don't want any of them remove them.
264 // for (t in gTiles) {
265 // if (isOutsideWindow(t))
266 // delete gTiles[t];
267 // }
268 document.getElementById("zoomLevel").textContent = gPos.z;
269 gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
270 var wid = gMapCanvas.width * gZoomFactor; // Width in level 18 pixels.
271 var ht = gMapCanvas.height * gZoomFactor; // Height in level 18 pixels.
272 var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
273
274 var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
275 var yMin = gPos.y - ht / 2;
276 var xMax = gPos.x + wid / 2;
277 var yMax = gPos.y + ht / 2;
278
279 if (gMapPrefsLoaded && mainDB)
280 gPrefs.set("position", gPos);
281
282 // Go through all the tiles we want.
283 // If any of them aren't loaded or being loaded, do so.
284 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
285 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
286 // Round here is **CRUCIAL** otherwise the images are filtered
287 // and the performance sucks (more than expected).
288 var xoff = Math.round((x * size - xMin) / gZoomFactor);
289 var yoff = Math.round((y * size - yMin) / gZoomFactor);
290 // Draw placeholder, and then initiate loading/drawing of real one.
291 gMapContext.drawImage(gLoadingTile, xoff, yoff);
292
293 gTileService.get(gActiveMap, {x: x, y: y, z: gPos.z}, function(aImage, aStyle, aCoords) {
294 // Only draw if this applies for the current view.
295 if ((aStyle == gActiveMap) && (aCoords.z == gPos.z)) {
296 var ixMin = gPos.x - wid / 2;
297 var iyMin = gPos.y - ht / 2;
298 var ixoff = Math.round((aCoords.x * size - ixMin) / gZoomFactor);
299 var iyoff = Math.round((aCoords.y * size - iyMin) / gZoomFactor);
300 // Would be nice to draw directly from the blob, but that crashes:
301 // gMapContext.drawImage(aImage, ixoff, iyoff);
302 var URL = window.URL;
303 var imgURL = URL.createObjectURL(aImage);
304 var imgObj = new Image();
305 imgObj.src = imgURL;
306 imgObj.onload = function() {
307 gMapContext.drawImage(imgObj, ixoff, iyoff);
308 URL.revokeObjectURL(imgURL);
309 }
310 }
311 });
312 }
313 }
314 gLastDrawnPoint = null;
315 gCurPosMapCache = undefined;
316 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
317 if (gTrack.length) {
318 for (var i = 0; i < gTrack.length; i++) {
319 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
320 (i + 1 >= gTrack.length));
321 }
322 }
323}
324
325function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
326 var trackpoint = gps2xy(aLatitude, aLongitude);
327 // lastPoint is for optimizing (not actually executing the draw until the last)
328 trackpoint.optimized = (lastPoint === false);
329 var mappos = {x: Math.round((trackpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
330 y: Math.round((trackpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
331
332 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
333 gTrackContext.strokeStyle = gTrackColor;
334 gTrackContext.fillStyle = gTrackContext.strokeStyle;
335 gTrackContext.lineWidth = gTrackWidth;
336 gTrackContext.lineCap = "round";
337 gTrackContext.lineJoin = "round";
338 }
339 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
340 // This breaks optimiziation, so make sure to close path and reset optimization.
341 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
342 gTrackContext.stroke();
343 gTrackContext.beginPath();
344 trackpoint.optimized = false;
345 gTrackContext.arc(mappos.x, mappos.y,
346 gTrackContext.lineWidth, 0, Math.PI * 2, false);
347 gTrackContext.fill();
348 }
349 else {
350 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
351 gTrackContext.beginPath();
352 gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
353 Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2));
354 }
355 gTrackContext.lineTo(mappos.x, mappos.y);
356 if (!trackpoint.optimized)
357 gTrackContext.stroke();
358 }
359 gLastDrawnPoint = trackpoint;
360}
361
362function drawCurrentLocation(trackPoint) {
363 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
364 var circleRadius = Math.round(gCurLocSize / 2);
365 var mappos = {x: Math.round((locpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
366 y: Math.round((locpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
367
368 undrawCurrentLocation();
369
370 // Cache overdrawn area.
371 gCurPosMapCache =
372 {point: locpoint,
373 radius: circleRadius,
374 data: gTrackContext.getImageData(mappos.x - circleRadius,
375 mappos.y - circleRadius,
376 circleRadius * 2, circleRadius * 2)};
377
378 gTrackContext.strokeStyle = gCurLocColor;
379 gTrackContext.fillStyle = gTrackContext.strokeStyle;
380 gTrackContext.beginPath();
381 gTrackContext.arc(mappos.x, mappos.y,
382 circleRadius, 0, Math.PI * 2, false);
383 gTrackContext.fill();
384}
385
386function undrawCurrentLocation() {
387 if (gCurPosMapCache) {
388 var oldpoint = gCurPosMapCache.point;
389 var oldmp = {x: Math.round((oldpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
390 y: Math.round((oldpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
391 gTrackContext.putImageData(gCurPosMapCache.data,
392 oldmp.x - gCurPosMapCache.radius,
393 oldmp.y - gCurPosMapCache.radius);
394 gCurPosMapCache = undefined;
395 }
396}
397
398var mapEvHandler = {
399 handleEvent: function(aEvent) {
400 var touchEvent = aEvent.type.indexOf('touch') != -1;
401
402 // Bail out on unwanted map moves, but not zoom-changing events.
403 if (aEvent.type != "DOMMouseScroll" && aEvent.type != "mousewheel") {
404 // Bail out if this is neither a touch nor left-click.
405 if (!touchEvent && aEvent.button != 0)
406 return;
407
408 // Bail out if the started touch can't be found.
409 if (touchEvent && gDragging &&
410 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
411 return;
412 }
413
414 var coordObj = touchEvent ?
415 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
416 aEvent;
417
418 switch (aEvent.type) {
419 case "mousedown":
420 case "touchstart":
421 if (touchEvent) {
422 gDragTouchID = aEvent.changedTouches.item(0).identifier;
423 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
424 }
425 var x = coordObj.clientX - gMapCanvas.offsetLeft;
426 var y = coordObj.clientY - gMapCanvas.offsetTop;
427
428 if (touchEvent || aEvent.button === 0) {
429 gDragging = true;
430 }
431 gLastMouseX = x;
432 gLastMouseY = y;
433 showUI();
434 break;
435 case "mousemove":
436 case "touchmove":
437 var x = coordObj.clientX - gMapCanvas.offsetLeft;
438 var y = coordObj.clientY - gMapCanvas.offsetTop;
439 if (gDragging === true) {
440 var dX = x - gLastMouseX;
441 var dY = y - gLastMouseY;
442 gPos.x -= dX * gZoomFactor;
443 gPos.y -= dY * gZoomFactor;
444 drawMap();
445 showUI();
446 }
447 gLastMouseX = x;
448 gLastMouseY = y;
449 break;
450 case "mouseup":
451 case "touchend":
452 gDragging = false;
453 showUI();
454 break;
455 case "mouseout":
456 case "touchcancel":
457 case "touchleave":
458 //gDragging = false;
459 break;
460 case "DOMMouseScroll":
461 case "mousewheel":
462 var delta = 0;
463 if (aEvent.wheelDelta) {
464 delta = aEvent.wheelDelta / 120;
465 if (window.opera)
466 delta = -delta;
467 }
468 else if (aEvent.detail) {
469 delta = -aEvent.detail / 3;
470 }
471
472 // Debug output: "coordinates" of the point the mouse was over.
473 /*
474 var ptCoord = {x: gPos.x + (x - gMapCanvas.width / 2) * gZoomFactor,
475 y: gPos.y + (x - gMapCanvas.height / 2) * gZoomFactor};
476 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
477 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
478 document.getElementById("debug").textContent =
479 ptCoord.x + "/" + ptCoord.y + " - " +
480 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
481 pt2Coord.x + "/" + pt2Coord.y;
482 */
483
484 var newZoomLevel = gPos.z + (delta > 0 ? 1 : -1);
485 if ((newZoomLevel >= 0) && (newZoomLevel <= gMaxZoom)) {
486 // Calculate new center of the map - same point stays under the mouse.
487 // This means that the pixel distance between the old center and point
488 // must equal the pixel distance of the new center and that point.
489 var x = coordObj.clientX - gMapCanvas.offsetLeft;
490 var y = coordObj.clientY - gMapCanvas.offsetTop;
491
492 // Zoom factor after this action.
493 var newZoomFactor = Math.pow(2, gMaxZoom - newZoomLevel);
494 gPos.x -= (x - gMapCanvas.width / 2) * (newZoomFactor - gZoomFactor);
495 gPos.y -= (y - gMapCanvas.height / 2) * (newZoomFactor - gZoomFactor);
496
497 if (delta > 0)
498 zoomIn();
499 else if (delta < 0)
500 zoomOut();
501 }
502 break;
503 }
504 }
505};
506
507var geofake = {
508 tracking: false,
509 lastPos: {x: undefined, y: undefined},
510 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
511 this.tracking = true;
512 var watchCall = function() {
513 // calc new position in lat/lon degrees
514 // 90° on Earth surface are ~10,000 km at the equator,
515 // so try moving at most 10m at a time
516 if (geofake.lastPos.x)
517 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
518 else
519 geofake.lastPos.x = 48.208174
520 if (geofake.lastPos.y)
521 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
522 else
523 geofake.lastPos.y = 16.373819
524 aSuccessCallback({timestamp: Date.now(),
525 coords: {latitude: geofake.lastPos.x,
526 longitude: geofake.lastPos.y,
527 accuracy: 20}});
528 if (geofake.tracking)
529 setTimeout(watchCall, 1000);
530 };
531 setTimeout(watchCall, 1000);
532 return "foo";
533 },
534 clearWatch: function(aID) {
535 this.tracking = false;
536 }
537}
538
539function setCentering(aCheckbox) {
540 if (gMapPrefsLoaded && mainDB)
541 gPrefs.set("center_map", aCheckbox.checked);
542 gCenterPosition = aCheckbox.checked;
543}
544
545function setTracking(aCheckbox) {
546 if (gMapPrefsLoaded && mainDB)
547 gPrefs.set("tracking_enabled", aCheckbox.checked);
548 if (aCheckbox.checked)
549 startTracking();
550 else
551 endTracking();
552}
553
554function startTracking() {
555 if (gGeolocation) {
556 gGeoWatchID = gGeolocation.watchPosition(
557 function(position) {
558 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
559 var tPoint = {time: position.timestamp,
560 coords: {latitude: position.coords.latitude,
561 longitude: position.coords.longitude,
562 altitude: position.coords.altitude,
563 accuracy: position.coords.accuracy,
564 altitudeAccuracy: position.coords.altitudeAccuracy,
565 heading: position.coords.heading,
566 speed: position.coords.speed},
567 beginSegment: !gLastTrackPoint};
568 // Only add point to track is accuracy is good enough.
569 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
570 gLastTrackPoint = tPoint;
571 gTrack.push(tPoint);
572 try { gTrackStore.push(tPoint); } catch(e) {}
573 var redrawn = false;
574 if (gCenterPosition) {
575 var posCoord = gps2xy(position.coords.latitude,
576 position.coords.longitude);
577 if (Math.abs(gPos.x - posCoord.x) > gMapCanvas.width * gZoomFactor / 4 ||
578 Math.abs(gPos.y - posCoord.y) > gMapCanvas.height * gZoomFactor / 4) {
579 gPos.x = posCoord.x;
580 gPos.y = posCoord.y;
581 drawMap(); // This draws the current point as well.
582 redrawn = true;
583 }
584 }
585 if (!redrawn)
586 undrawCurrentLocation();
587 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
588 }
589 drawCurrentLocation(tPoint);
590 },
591 function(error) {
592 // Ignore erros for the moment, but this is good for debugging.
593 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
594 document.getElementById("debug").textContent = error.message;
595 },
596 {enableHighAccuracy: true}
597 );
598 }
599}
600
601function endTracking() {
602 if (gGeoWatchID) {
603 gGeolocation.clearWatch(gGeoWatchID);
604 }
605}
606
607function clearTrack() {
608 gTrack = [];
609 gTrackStore.clear();
610 drawMap();
611}
612
613var gTileService = {
614 objStore: "tilecache",
615
616 get: function(aStyle, aCoords, aCallback) {
617 var norm = normalizeCoords(aCoords);
618 var dbkey = aStyle + "::" + norm.x + "," + norm.y + "," + norm.z;
619 this.getDBCache(dbkey, function(aResult, aEvent) {
620 if (aResult) {
621 // We did get a cached object.
622 // TODO: Look at the timestamp and trigger a reload when it's too old.
623 aCallback(aResult.image, aStyle, aCoords);
624 }
625 else {
626 // Retrieve image from the web and store it in the cache.
627 var XHR = new XMLHttpRequest();
628 XHR.open("GET",
629 gMapStyles[aStyle].url
630 .replace("{x}", norm.x)
631 .replace("{y}", norm.y)
632 .replace("{z}", norm.z)
633 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
634 .replace("[1-4]", 1 + Math.floor(Math.random() * 3)),
635 true);
636 XHR.responseType = "blob";
637 XHR.addEventListener("load", function () {
638 if (XHR.status === 200) {
639 var blob = XHR.response;
640 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
641 aCallback(blob, aStyle, aCoords);
642 }
643 }, false);
644 XHR.send();
645 }
646 });
647 },
648
649 getDBCache: function(aKey, aCallback) {
650 if (!mainDB)
651 return;
652 var transaction = mainDB.transaction([this.objStore]);
653 var request = transaction.objectStore(this.objStore).get(aKey);
654 request.onsuccess = function(event) {
655 aCallback(request.result, event);
656 };
657 request.onerror = function(event) {
658 // Errors can be handled here.
659 aCallback(undefined, event);
660 };
661 },
662
663 setDBCache: function(aKey, aValue, aCallback) {
664 if (!mainDB)
665 return;
666 var success = false;
667 var transaction = mainDB.transaction([this.objStore], "readwrite");
668 var objStore = transaction.objectStore(this.objStore);
669 var request = objStore.put(aValue, aKey);
670 request.onsuccess = function(event) {
671 success = true;
672 if (aCallback)
673 aCallback(success, event);
674 };
675 request.onerror = function(event) {
676 // Errors can be handled here.
677 if (aCallback)
678 aCallback(success, event);
679 };
680 },
681
682 unsetDBCache: function(aKey, aCallback) {
683 if (!mainDB)
684 return;
685 var success = false;
686 var transaction = mainDB.transaction([this.objStore], "readwrite");
687 var request = transaction.objectStore(this.objStore).delete(aKey);
688 request.onsuccess = function(event) {
689 success = true;
690 if (aCallback)
691 aCallback(success, event);
692 };
693 request.onerror = function(event) {
694 // Errors can be handled here.
695 if (aCallback)
696 aCallback(success, event);
697 }
698 }
699};