umm, turn off debug
[lantea.git] / js / map.js
CommitLineData
a7393a71
RK
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/. */
23cd2dcc 4
4b1d0915 5var gMapCanvas, gMapContext, gTrackCanvas, gTrackContext, gGeolocation;
31f77b93 6var gDebug = false;
23cd2dcc
RK
7
8var gTileSize = 256;
9var gMaxZoom = 18; // The minimum is 0.
10
b054bd48
RK
11var gMinTrackAccuracy = 1000; // meters
12var gTrackWidth = 2; // pixels
13var gTrackColor = "#FF0000";
4b1d0915
RK
14var gCurLocSize = 6; // pixels
15var gCurLocColor = "#A00000";
b054bd48 16
b47b4a65
RK
17var gMapStyles = {
18 // OSM tile usage policy: http://wiki.openstreetmap.org/wiki/Tile_usage_policy
55c4a0b7 19 // Find some more OSM ones at http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers
b47b4a65
RK
20 osm_mapnik:
21 {name: "OpenStreetMap (Mapnik)",
22 url: "http://tile.openstreetmap.org/{z}/{x}/{y}.png",
5a19ec68 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>'},
14e6d3ad
RK
24 osm_cyclemap:
25 {name: "Cycle Map (OSM)",
26 url: "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
5a19ec68 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>'},
14e6d3ad
RK
28 osm_transmap:
29 {name: "Transport Map (OSM)",
30 url: "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png",
5a19ec68 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>'},
b47b4a65 32 mapquest_open:
55c4a0b7 33 {name: "MapQuest OSM",
5a19ec68
RK
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>.'},
55c4a0b7
RK
36 mapquest_aerial:
37 {name: "MapQuest Open Aerial",
5a19ec68
RK
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>.'},
55c4a0b7
RK
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>'},
b47b4a65
RK
48};
49var gActiveMap = "osm_mapnik";
23cd2dcc
RK
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)
b395419b 53 z: 5}; // This could be fractional if supported being between zoom levels.
23cd2dcc
RK
54
55var gLastMouseX = 0;
56var gLastMouseY = 0;
b395419b 57var gZoomFactor;
23cd2dcc 58
3610c22d
RK
59// Used as an associative array.
60// The keys have to be strings, ours will be "xindex,yindex,zindex" e.g. "13,245,12".
23cd2dcc 61var gTiles = {};
b395419b 62var gLoadingTile;
23cd2dcc 63
3610c22d
RK
64var gMapPrefsLoaded = false;
65
23cd2dcc 66var gDragging = false;
4b12da3a 67var gDragTouchID;
23cd2dcc 68
55c4a0b7
RK
69var gGeoWatchID;
70var gTrack = [];
14e6d3ad 71var gLastTrackPoint, gLastDrawnPoint;
05c21757 72var gCenterPosition = true;
55c4a0b7 73
b054bd48
RK
74var gCurPosMapCache;
75
b47b4a65 76function initMap() {
4b12da3a 77 gGeolocation = navigator.geolocation;
4b1d0915
RK
78 gMapCanvas = document.getElementById("map");
79 gMapContext = gMapCanvas.getContext("2d");
80 gTrackCanvas = document.getElementById("track");
81 gTrackContext = gTrackCanvas.getContext("2d");
b47b4a65
RK
82 if (!gActiveMap)
83 gActiveMap = "osm_mapnik";
23cd2dcc 84
4b12da3a
RK
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
3610c22d
RK
95 var loopCnt = 0;
96 var getPersistentPrefs = function() {
97 if (mainDB) {
4b1d0915 98 gWaitCounter++;
3610c22d
RK
99 gPrefs.get("position", function(aValue) {
100 if (aValue) {
101 gPos = aValue;
4b1d0915 102 gWaitCounter--;
3610c22d
RK
103 }
104 });
4b1d0915 105 gWaitCounter++;
3610c22d
RK
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"));
4b1d0915 112 gWaitCounter--;
3610c22d 113 });
4b1d0915 114 gWaitCounter++;
3610c22d
RK
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;
4b1d0915
RK
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--;
3610c22d 130 });
3610c22d
RK
131 }
132 else
133 setTimeout(getPersistentPrefs, 100);
134 loopCnt++;
4b1d0915
RK
135 if (loopCnt > 50) {
136 document.getElementById("debug").textContent = "Loading prefs failed.";
3610c22d
RK
137 }
138 };
139 getPersistentPrefs();
140
4b1d0915
RK
141 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
142 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
143 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
144 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
23cd2dcc 145
4b1d0915
RK
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);
23cd2dcc 151
6de10e15 152 // XXX deprecated? see https://groups.google.com/forum/?fromgroups#!topic/mozilla.dev.planning/kuhrORubaRY[1-25]
4b1d0915
RK
153 gTrackCanvas.addEventListener("DOMMouseScroll", mapEvHandler, false);
154 gTrackCanvas.addEventListener("mousewheel", mapEvHandler, false);
23cd2dcc 155
b47b4a65
RK
156 document.getElementById("copyright").innerHTML =
157 gMapStyles[gActiveMap].copyright;
b395419b
RK
158
159 gLoadingTile = new Image();
160 gLoadingTile.src = "style/loading.png";
4b1d0915
RK
161 gWaitCounter++;
162 gLoadingTile.onload = function() { gWaitCounter--; };
23cd2dcc
RK
163}
164
165function resizeAndDraw() {
321359cd
RK
166 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
167 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
23cd2dcc 168
4b1d0915
RK
169 gMapCanvas.width = viewportWidth;
170 gMapCanvas.height = viewportHeight;
171 gTrackCanvas.width = viewportWidth;
172 gTrackCanvas.height = viewportHeight;
23cd2dcc 173 drawMap();
7a549148 174 showUI();
23cd2dcc
RK
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
55c4a0b7
RK
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
b47b4a65
RK
209function setMapStyle() {
210 var mapSel = document.getElementById("mapSelector");
211 if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
212 gActiveMap = mapSel.value;
213 gTiles = {};
95f49ba7
RK
214 document.getElementById("copyright").innerHTML =
215 gMapStyles[gActiveMap].copyright;
b5c85133 216 showUI();
b47b4a65
RK
217 drawMap();
218 }
219}
220
23cd2dcc
RK
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
a8634d37
RK
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};
23cd2dcc
RK
232}
233
234// Returns true if the tile is outside the current view.
235function isOutsideWindow(t) {
236 var pos = decodeIndex(t);
23cd2dcc 237
4b1d0915
RK
238 var zoomFactor = Math.pow(2, gMaxZoom - pos.z);
239 var wid = gMapCanvas.width * zoomFactor;
240 var ht = gMapCanvas.height * zoomFactor;
23cd2dcc 241
4b1d0915
RK
242 pos.x *= zoomFactor;
243 pos.y *= zoomFactor;
23cd2dcc 244
b395419b 245 var sz = gTileSize * zoomFactor;
4b1d0915
RK
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)
23cd2dcc
RK
248 return true;
249 return false;
250}
251
252function encodeIndex(x, y, z) {
a8634d37 253 var norm = normalizeCoords({x: x, y: y, z: z});
23cd2dcc
RK
254 return norm.x + "," + norm.y + "," + norm.z;
255}
256
257function decodeIndex(encodedIdx) {
4b1d0915
RK
258 var ind = encodedIdx.split(",", 3);
259 return {x: ind[0], y: ind[1], z: ind[2]};
23cd2dcc
RK
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 // }
b395419b
RK
268 document.getElementById("zoomLevel").textContent = gPos.z;
269 gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
4b1d0915
RK
270 var wid = gMapCanvas.width * gZoomFactor; // Width in level 18 pixels.
271 var ht = gMapCanvas.height * gZoomFactor; // Height in level 18 pixels.
b395419b 272 var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
23cd2dcc
RK
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
3610c22d
RK
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.
b47b4a65 284 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
0118cbd3 285 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
4b1d0915
RK
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);
a8634d37
RK
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 var URL = window.URL;
301 var imgURL = URL.createObjectURL(aImage);
302 var imgObj = new Image();
303 imgObj.src = imgURL;
304 gMapContext.drawImage(imgObj, ixoff, iyoff);
305 URL.revokeObjectURL(imgURL);
4b1d0915 306 }
a8634d37 307 });
23cd2dcc
RK
308 }
309 }
4b1d0915
RK
310 gLastDrawnPoint = null;
311 gCurPosMapCache = undefined;
312 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
14e6d3ad 313 if (gTrack.length) {
55c4a0b7 314 for (var i = 0; i < gTrack.length; i++) {
14e6d3ad
RK
315 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
316 (i + 1 >= gTrack.length));
55c4a0b7 317 }
14e6d3ad 318 }
55c4a0b7
RK
319}
320
14e6d3ad 321function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
55c4a0b7 322 var trackpoint = gps2xy(aLatitude, aLongitude);
14e6d3ad
RK
323 // lastPoint is for optimizing (not actually executing the draw until the last)
324 trackpoint.optimized = (lastPoint === false);
4b1d0915
RK
325 var mappos = {x: Math.round((trackpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
326 y: Math.round((trackpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
14e6d3ad
RK
327
328 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
4b1d0915
RK
329 gTrackContext.strokeStyle = gTrackColor;
330 gTrackContext.fillStyle = gTrackContext.strokeStyle;
331 gTrackContext.lineWidth = gTrackWidth;
332 gTrackContext.lineCap = "round";
333 gTrackContext.lineJoin = "round";
14e6d3ad
RK
334 }
335 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
336 // This breaks optimiziation, so make sure to close path and reset optimization.
337 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
4b1d0915
RK
338 gTrackContext.stroke();
339 gTrackContext.beginPath();
14e6d3ad 340 trackpoint.optimized = false;
4b1d0915
RK
341 gTrackContext.arc(mappos.x, mappos.y,
342 gTrackContext.lineWidth, 0, Math.PI * 2, false);
343 gTrackContext.fill();
55c4a0b7
RK
344 }
345 else {
14e6d3ad 346 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
4b1d0915
RK
347 gTrackContext.beginPath();
348 gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
349 Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2));
14e6d3ad 350 }
4b1d0915 351 gTrackContext.lineTo(mappos.x, mappos.y);
14e6d3ad 352 if (!trackpoint.optimized)
4b1d0915 353 gTrackContext.stroke();
55c4a0b7 354 }
14e6d3ad 355 gLastDrawnPoint = trackpoint;
23cd2dcc
RK
356}
357
b054bd48 358function drawCurrentLocation(trackPoint) {
4b1d0915
RK
359 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
360 var circleRadius = Math.round(gCurLocSize / 2);
361 var mappos = {x: Math.round((locpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
362 y: Math.round((locpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
363
364 undrawCurrentLocation();
b054bd48
RK
365
366 // Cache overdrawn area.
4b1d0915
RK
367 gCurPosMapCache =
368 {point: locpoint,
369 radius: circleRadius,
370 data: gTrackContext.getImageData(mappos.x - circleRadius,
371 mappos.y - circleRadius,
372 circleRadius * 2, circleRadius * 2)};
373
374 gTrackContext.strokeStyle = gCurLocColor;
375 gTrackContext.fillStyle = gTrackContext.strokeStyle;
376 gTrackContext.beginPath();
377 gTrackContext.arc(mappos.x, mappos.y,
378 circleRadius, 0, Math.PI * 2, false);
379 gTrackContext.fill();
380}
381
382function undrawCurrentLocation() {
383 if (gCurPosMapCache) {
384 var oldpoint = gCurPosMapCache.point;
385 var oldmp = {x: Math.round((oldpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
386 y: Math.round((oldpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
387 gTrackContext.putImageData(gCurPosMapCache.data,
388 oldmp.x - gCurPosMapCache.radius,
389 oldmp.y - gCurPosMapCache.radius);
390 gCurPosMapCache = undefined;
391 }
b054bd48
RK
392}
393
23cd2dcc
RK
394var mapEvHandler = {
395 handleEvent: function(aEvent) {
396 var touchEvent = aEvent.type.indexOf('touch') != -1;
397
b395419b 398 // Bail out on unwanted map moves, but not zoom-changing events.
23cd2dcc
RK
399 if (aEvent.type != "DOMMouseScroll" && aEvent.type != "mousewheel") {
400 // Bail out if this is neither a touch nor left-click.
401 if (!touchEvent && aEvent.button != 0)
402 return;
403
404 // Bail out if the started touch can't be found.
4b12da3a
RK
405 if (touchEvent && gDragging &&
406 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
23cd2dcc
RK
407 return;
408 }
409
410 var coordObj = touchEvent ?
4b12da3a 411 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
23cd2dcc
RK
412 aEvent;
413
414 switch (aEvent.type) {
415 case "mousedown":
416 case "touchstart":
417 if (touchEvent) {
4b12da3a
RK
418 gDragTouchID = aEvent.changedTouches.item(0).identifier;
419 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
23cd2dcc 420 }
4b1d0915
RK
421 var x = coordObj.clientX - gMapCanvas.offsetLeft;
422 var y = coordObj.clientY - gMapCanvas.offsetTop;
b395419b 423
23cd2dcc
RK
424 if (touchEvent || aEvent.button === 0) {
425 gDragging = true;
426 }
427 gLastMouseX = x;
428 gLastMouseY = y;
7a549148 429 showUI();
23cd2dcc
RK
430 break;
431 case "mousemove":
432 case "touchmove":
4b1d0915
RK
433 var x = coordObj.clientX - gMapCanvas.offsetLeft;
434 var y = coordObj.clientY - gMapCanvas.offsetTop;
23cd2dcc
RK
435 if (gDragging === true) {
436 var dX = x - gLastMouseX;
437 var dY = y - gLastMouseY;
b395419b
RK
438 gPos.x -= dX * gZoomFactor;
439 gPos.y -= dY * gZoomFactor;
23cd2dcc 440 drawMap();
7a549148 441 showUI();
23cd2dcc
RK
442 }
443 gLastMouseX = x;
444 gLastMouseY = y;
445 break;
446 case "mouseup":
447 case "touchend":
448 gDragging = false;
7a549148 449 showUI();
23cd2dcc
RK
450 break;
451 case "mouseout":
452 case "touchcancel":
453 case "touchleave":
454 //gDragging = false;
455 break;
456 case "DOMMouseScroll":
457 case "mousewheel":
458 var delta = 0;
459 if (aEvent.wheelDelta) {
460 delta = aEvent.wheelDelta / 120;
461 if (window.opera)
462 delta = -delta;
463 }
464 else if (aEvent.detail) {
465 delta = -aEvent.detail / 3;
466 }
467
55c4a0b7
RK
468 // Debug output: "coordinates" of the point the mouse was over.
469 /*
4b1d0915
RK
470 var ptCoord = {x: gPos.x + (x - gMapCanvas.width / 2) * gZoomFactor,
471 y: gPos.y + (x - gMapCanvas.height / 2) * gZoomFactor};
55c4a0b7
RK
472 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
473 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
474 document.getElementById("debug").textContent =
475 ptCoord.x + "/" + ptCoord.y + " - " +
476 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
477 pt2Coord.x + "/" + pt2Coord.y;
478 */
4b1d0915
RK
479
480 var newZoomLevel = gPos.z + (delta > 0 ? 1 : -1);
481 if ((newZoomLevel >= 0) && (newZoomLevel <= gMaxZoom)) {
482 // Calculate new center of the map - same point stays under the mouse.
483 // This means that the pixel distance between the old center and point
484 // must equal the pixel distance of the new center and that point.
485 var x = coordObj.clientX - gMapCanvas.offsetLeft;
486 var y = coordObj.clientY - gMapCanvas.offsetTop;
487
488 // Zoom factor after this action.
489 var newZoomFactor = Math.pow(2, gMaxZoom - newZoomLevel);
490 gPos.x -= (x - gMapCanvas.width / 2) * (newZoomFactor - gZoomFactor);
491 gPos.y -= (y - gMapCanvas.height / 2) * (newZoomFactor - gZoomFactor);
492
493 if (delta > 0)
494 zoomIn();
495 else if (delta < 0)
496 zoomOut();
497 }
23cd2dcc
RK
498 break;
499 }
500 }
501};
55c4a0b7 502
993fd081 503var geofake = {
55c4a0b7 504 tracking: false,
4b12da3a 505 lastPos: {x: undefined, y: undefined},
55c4a0b7
RK
506 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
507 this.tracking = true;
508 var watchCall = function() {
4b12da3a
RK
509 // calc new position in lat/lon degrees
510 // 90° on Earth surface are ~10,000 km at the equator,
511 // so try moving at most 10m at a time
512 if (geofake.lastPos.x)
513 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
514 else
515 geofake.lastPos.x = 48.208174
516 if (geofake.lastPos.y)
517 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
518 else
519 geofake.lastPos.y = 16.373819
55c4a0b7 520 aSuccessCallback({timestamp: Date.now(),
4b12da3a
RK
521 coords: {latitude: geofake.lastPos.x,
522 longitude: geofake.lastPos.y,
55c4a0b7
RK
523 accuracy: 20}});
524 if (geofake.tracking)
525 setTimeout(watchCall, 1000);
526 };
527 setTimeout(watchCall, 1000);
528 return "foo";
529 },
530 clearWatch: function(aID) {
531 this.tracking = false;
532 }
533}
534
3610c22d
RK
535function setCentering(aCheckbox) {
536 if (gMapPrefsLoaded && mainDB)
537 gPrefs.set("center_map", aCheckbox.checked);
538 gCenterPosition = aCheckbox.checked;
539}
540
541function setTracking(aCheckbox) {
542 if (gMapPrefsLoaded && mainDB)
543 gPrefs.set("tracking_enabled", aCheckbox.checked);
544 if (aCheckbox.checked)
545 startTracking();
546 else
547 endTracking();
548}
549
55c4a0b7 550function startTracking() {
31f0fe16 551 if (gGeolocation) {
4b12da3a 552 gGeoWatchID = gGeolocation.watchPosition(
55c4a0b7
RK
553 function(position) {
554 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
993fd081 555 var tPoint = {time: position.timestamp,
31f0fe16
RK
556 coords: {latitude: position.coords.latitude,
557 longitude: position.coords.longitude,
558 altitude: position.coords.altitude,
559 accuracy: position.coords.accuracy,
560 altitudeAccuracy: position.coords.altitudeAccuracy,
561 heading: position.coords.heading,
562 speed: position.coords.speed},
993fd081 563 beginSegment: !gLastTrackPoint};
b054bd48
RK
564 // Only add point to track is accuracy is good enough.
565 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
566 gLastTrackPoint = tPoint;
567 gTrack.push(tPoint);
568 try { gTrackStore.push(tPoint); } catch(e) {}
569 var redrawn = false;
570 if (gCenterPosition) {
571 var posCoord = gps2xy(position.coords.latitude,
572 position.coords.longitude);
4b1d0915
RK
573 if (Math.abs(gPos.x - posCoord.x) > gMapCanvas.width * gZoomFactor / 4 ||
574 Math.abs(gPos.y - posCoord.y) > gMapCanvas.height * gZoomFactor / 4) {
b054bd48
RK
575 gPos.x = posCoord.x;
576 gPos.y = posCoord.y;
577 drawMap(); // This draws the current point as well.
578 redrawn = true;
579 }
99631a75 580 }
b054bd48 581 if (!redrawn)
4b1d0915 582 undrawCurrentLocation();
b054bd48 583 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
05c21757 584 }
b054bd48 585 drawCurrentLocation(tPoint);
55c4a0b7
RK
586 },
587 function(error) {
588 // Ignore erros for the moment, but this is good for debugging.
589 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
590 document.getElementById("debug").textContent = error.message;
591 },
592 {enableHighAccuracy: true}
593 );
594 }
595}
596
597function endTracking() {
598 if (gGeoWatchID) {
4b12da3a 599 gGeolocation.clearWatch(gGeoWatchID);
55c4a0b7
RK
600 }
601}
993fd081
RK
602
603function clearTrack() {
604 gTrack = [];
605 gTrackStore.clear();
606 drawMap();
607}
a8634d37
RK
608
609var gTileService = {
610 objStore: "tilecache",
611
612 get: function(aStyle, aCoords, aCallback) {
613 var norm = normalizeCoords(aCoords);
614 var dbkey = aStyle + "::" + norm.x + "," + norm.y + "," + norm.z;
615 this.getDBCache(dbkey, function(aResult, aEvent) {
616 if (aResult) {
617 // We did get a cached object.
618 // TODO: Look at the timestamp and trigger a reload when it's too old.
619 aCallback(aResult.image, aStyle, aCoords);
620 }
621 else {
622 // Retrieve image from the web and store it in the cache.
623 var XHR = new XMLHttpRequest();
624 XHR.open("GET",
625 gMapStyles[aStyle].url
626 .replace("{x}", norm.x)
627 .replace("{y}", norm.y)
628 .replace("{z}", norm.z)
629 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
630 .replace("[1-4]", 1 + Math.floor(Math.random() * 3)),
631 true);
632 XHR.responseType = "blob";
633 XHR.addEventListener("load", function () {
634 if (XHR.status === 200) {
635 var blob = XHR.response;
636 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
637 aCallback(blob, aStyle, aCoords);
638 }
639 }, false);
640 XHR.send();
641 }
642 });
643 },
644
645 getDBCache: function(aKey, aCallback) {
646 if (!mainDB)
647 return;
648 var transaction = mainDB.transaction([this.objStore]);
649 var request = transaction.objectStore(this.objStore).get(aKey);
650 request.onsuccess = function(event) {
651 aCallback(request.result, event);
652 };
653 request.onerror = function(event) {
654 // Errors can be handled here.
655 aCallback(undefined, event);
656 };
657 },
658
659 setDBCache: function(aKey, aValue, aCallback) {
660 if (!mainDB)
661 return;
662 var success = false;
663 var transaction = mainDB.transaction([this.objStore], "readwrite");
664 var objStore = transaction.objectStore(this.objStore);
665 var request = objStore.put(aValue, aKey);
666 request.onsuccess = function(event) {
667 success = true;
668 if (aCallback)
669 aCallback(success, event);
670 };
671 request.onerror = function(event) {
672 // Errors can be handled here.
673 if (aCallback)
674 aCallback(success, event);
675 };
676 },
677
678 unsetDBCache: function(aKey, aCallback) {
679 if (!mainDB)
680 return;
681 var success = false;
682 var transaction = mainDB.transaction([this.objStore], "readwrite");
683 var request = transaction.objectStore(this.objStore).delete(aKey);
684 request.onsuccess = function(event) {
685 success = true;
686 if (aCallback)
687 aCallback(success, event);
688 };
689 request.onerror = function(event) {
690 // Errors can be handled here.
691 if (aCallback)
692 aCallback(success, event);
693 }
694 }
695};