make tile cache aging/reloading actually work
[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",
68afcd96 38 url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg",
5a19ec68
RK
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
b395419b 59var gLoadingTile;
23cd2dcc 60
3610c22d
RK
61var gMapPrefsLoaded = false;
62
23cd2dcc 63var gDragging = false;
4b12da3a 64var gDragTouchID;
23cd2dcc 65
55c4a0b7
RK
66var gGeoWatchID;
67var gTrack = [];
14e6d3ad 68var gLastTrackPoint, gLastDrawnPoint;
05c21757 69var gCenterPosition = true;
55c4a0b7 70
b054bd48
RK
71var gCurPosMapCache;
72
b47b4a65 73function initMap() {
4b12da3a 74 gGeolocation = navigator.geolocation;
4b1d0915
RK
75 gMapCanvas = document.getElementById("map");
76 gMapContext = gMapCanvas.getContext("2d");
77 gTrackCanvas = document.getElementById("track");
78 gTrackContext = gTrackCanvas.getContext("2d");
b47b4a65
RK
79 if (!gActiveMap)
80 gActiveMap = "osm_mapnik";
23cd2dcc 81
4b12da3a
RK
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
3610c22d
RK
92 var loopCnt = 0;
93 var getPersistentPrefs = function() {
94 if (mainDB) {
4b1d0915 95 gWaitCounter++;
3610c22d
RK
96 gPrefs.get("position", function(aValue) {
97 if (aValue) {
98 gPos = aValue;
4b1d0915 99 gWaitCounter--;
3610c22d
RK
100 }
101 });
4b1d0915 102 gWaitCounter++;
3610c22d
RK
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"));
4b1d0915 109 gWaitCounter--;
3610c22d 110 });
4b1d0915 111 gWaitCounter++;
3610c22d
RK
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;
4b1d0915
RK
117 gWaitCounter--;
118 });
119 gWaitCounter++;
120 gTrackStore.getList(function(aTPoints) {
121 if (gDebug)
915d4271 122 console.log(aTPoints.length + " points loaded.");
4b1d0915
RK
123 if (aTPoints.length) {
124 gTrack = aTPoints;
125 }
126 gWaitCounter--;
3610c22d 127 });
3610c22d
RK
128 }
129 else
130 setTimeout(getPersistentPrefs, 100);
131 loopCnt++;
4b1d0915 132 if (loopCnt > 50) {
915d4271 133 console.log("Loading prefs failed.");
3610c22d
RK
134 }
135 };
136 getPersistentPrefs();
137
4b1d0915
RK
138 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
139 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
140 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
141 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
23cd2dcc 142
4b1d0915
RK
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);
23cd2dcc 148
6de10e15 149 // XXX deprecated? see https://groups.google.com/forum/?fromgroups#!topic/mozilla.dev.planning/kuhrORubaRY[1-25]
4b1d0915
RK
150 gTrackCanvas.addEventListener("DOMMouseScroll", mapEvHandler, false);
151 gTrackCanvas.addEventListener("mousewheel", mapEvHandler, false);
23cd2dcc 152
b47b4a65
RK
153 document.getElementById("copyright").innerHTML =
154 gMapStyles[gActiveMap].copyright;
b395419b
RK
155
156 gLoadingTile = new Image();
157 gLoadingTile.src = "style/loading.png";
4b1d0915
RK
158 gWaitCounter++;
159 gLoadingTile.onload = function() { gWaitCounter--; };
23cd2dcc
RK
160}
161
162function resizeAndDraw() {
321359cd
RK
163 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
164 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
915d4271
RK
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 }
23cd2dcc
RK
173}
174
b5e49b95
RK
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
23cd2dcc
RK
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
55c4a0b7
RK
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
b47b4a65
RK
210function setMapStyle() {
211 var mapSel = document.getElementById("mapSelector");
212 if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
213 gActiveMap = mapSel.value;
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
b5e49b95
RK
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
b395419b
RK
273 document.getElementById("zoomLevel").textContent = gPos.z;
274 gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
4b1d0915
RK
275 var wid = gMapCanvas.width * gZoomFactor; // Width in level 18 pixels.
276 var ht = gMapCanvas.height * gZoomFactor; // Height in level 18 pixels.
b395419b 277 var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
23cd2dcc
RK
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
3610c22d
RK
284 if (gMapPrefsLoaded && mainDB)
285 gPrefs.set("position", gPos);
286
b5e49b95
RK
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.
b47b4a65 297 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
0118cbd3 298 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
b5e49b95 299 // Only go to the drawing step if we need to draw this tile.
68afcd96
RK
300 if (x < tiles.left || x > tiles.right ||
301 y < tiles.top || y > tiles.bottom) {
b5e49b95
RK
302 // Round here is **CRUCIAL** otherwise the images are filtered
303 // and the performance sucks (more than expected).
304 var xoff = Math.round((x * size - xMin) / gZoomFactor);
305 var yoff = Math.round((y * size - yMin) / gZoomFactor);
306 // Draw placeholder tile unless we overdraw.
68afcd96
RK
307 if (!aOverdraw &&
308 (x < tiles.left -1 || x > tiles.right + 1 ||
309 y < tiles.top -1 || y > tiles.bottom + 1))
b5e49b95
RK
310 gMapContext.drawImage(gLoadingTile, xoff, yoff);
311
312 // Initiate loading/drawing of the actual tile.
313 gTileService.get(gActiveMap, {x: x, y: y, z: gPos.z},
314 function(aImage, aStyle, aCoords) {
315 // Only draw if this applies for the current view.
316 if ((aStyle == gActiveMap) && (aCoords.z == gPos.z)) {
317 var ixMin = gPos.x - wid / 2;
318 var iyMin = gPos.y - ht / 2;
319 var ixoff = Math.round((aCoords.x * size - ixMin) / gZoomFactor);
320 var iyoff = Math.round((aCoords.y * size - iyMin) / gZoomFactor);
321 var URL = window.URL;
322 var imgURL = URL.createObjectURL(aImage);
323 var imgObj = new Image();
324 imgObj.src = imgURL;
325 imgObj.onload = function() {
326 gMapContext.drawImage(imgObj, ixoff, iyoff);
327 URL.revokeObjectURL(imgURL);
328 }
a2131f63 329 }
b5e49b95
RK
330 });
331 }
23cd2dcc
RK
332 }
333 }
4b1d0915
RK
334 gLastDrawnPoint = null;
335 gCurPosMapCache = undefined;
336 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
14e6d3ad 337 if (gTrack.length) {
55c4a0b7 338 for (var i = 0; i < gTrack.length; i++) {
14e6d3ad
RK
339 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
340 (i + 1 >= gTrack.length));
55c4a0b7 341 }
14e6d3ad 342 }
55c4a0b7
RK
343}
344
14e6d3ad 345function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
55c4a0b7 346 var trackpoint = gps2xy(aLatitude, aLongitude);
14e6d3ad
RK
347 // lastPoint is for optimizing (not actually executing the draw until the last)
348 trackpoint.optimized = (lastPoint === false);
4b1d0915
RK
349 var mappos = {x: Math.round((trackpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
350 y: Math.round((trackpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
14e6d3ad
RK
351
352 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
4b1d0915
RK
353 gTrackContext.strokeStyle = gTrackColor;
354 gTrackContext.fillStyle = gTrackContext.strokeStyle;
355 gTrackContext.lineWidth = gTrackWidth;
356 gTrackContext.lineCap = "round";
357 gTrackContext.lineJoin = "round";
14e6d3ad
RK
358 }
359 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
360 // This breaks optimiziation, so make sure to close path and reset optimization.
361 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
4b1d0915
RK
362 gTrackContext.stroke();
363 gTrackContext.beginPath();
14e6d3ad 364 trackpoint.optimized = false;
4b1d0915
RK
365 gTrackContext.arc(mappos.x, mappos.y,
366 gTrackContext.lineWidth, 0, Math.PI * 2, false);
367 gTrackContext.fill();
55c4a0b7
RK
368 }
369 else {
14e6d3ad 370 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
4b1d0915
RK
371 gTrackContext.beginPath();
372 gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
373 Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2));
14e6d3ad 374 }
4b1d0915 375 gTrackContext.lineTo(mappos.x, mappos.y);
14e6d3ad 376 if (!trackpoint.optimized)
4b1d0915 377 gTrackContext.stroke();
55c4a0b7 378 }
14e6d3ad 379 gLastDrawnPoint = trackpoint;
23cd2dcc
RK
380}
381
b054bd48 382function drawCurrentLocation(trackPoint) {
4b1d0915
RK
383 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
384 var circleRadius = Math.round(gCurLocSize / 2);
385 var mappos = {x: Math.round((locpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
386 y: Math.round((locpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
387
388 undrawCurrentLocation();
b054bd48
RK
389
390 // Cache overdrawn area.
4b1d0915
RK
391 gCurPosMapCache =
392 {point: locpoint,
393 radius: circleRadius,
394 data: gTrackContext.getImageData(mappos.x - circleRadius,
395 mappos.y - circleRadius,
396 circleRadius * 2, circleRadius * 2)};
397
398 gTrackContext.strokeStyle = gCurLocColor;
399 gTrackContext.fillStyle = gTrackContext.strokeStyle;
400 gTrackContext.beginPath();
401 gTrackContext.arc(mappos.x, mappos.y,
402 circleRadius, 0, Math.PI * 2, false);
403 gTrackContext.fill();
404}
405
406function undrawCurrentLocation() {
407 if (gCurPosMapCache) {
408 var oldpoint = gCurPosMapCache.point;
409 var oldmp = {x: Math.round((oldpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
410 y: Math.round((oldpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
411 gTrackContext.putImageData(gCurPosMapCache.data,
412 oldmp.x - gCurPosMapCache.radius,
413 oldmp.y - gCurPosMapCache.radius);
414 gCurPosMapCache = undefined;
415 }
b054bd48
RK
416}
417
23cd2dcc
RK
418var mapEvHandler = {
419 handleEvent: function(aEvent) {
420 var touchEvent = aEvent.type.indexOf('touch') != -1;
421
b395419b 422 // Bail out on unwanted map moves, but not zoom-changing events.
23cd2dcc
RK
423 if (aEvent.type != "DOMMouseScroll" && aEvent.type != "mousewheel") {
424 // Bail out if this is neither a touch nor left-click.
425 if (!touchEvent && aEvent.button != 0)
426 return;
427
428 // Bail out if the started touch can't be found.
4b12da3a
RK
429 if (touchEvent && gDragging &&
430 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
23cd2dcc
RK
431 return;
432 }
433
434 var coordObj = touchEvent ?
4b12da3a 435 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
23cd2dcc
RK
436 aEvent;
437
438 switch (aEvent.type) {
439 case "mousedown":
440 case "touchstart":
441 if (touchEvent) {
4b12da3a
RK
442 gDragTouchID = aEvent.changedTouches.item(0).identifier;
443 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
23cd2dcc 444 }
4b1d0915
RK
445 var x = coordObj.clientX - gMapCanvas.offsetLeft;
446 var y = coordObj.clientY - gMapCanvas.offsetTop;
b395419b 447
23cd2dcc
RK
448 if (touchEvent || aEvent.button === 0) {
449 gDragging = true;
450 }
451 gLastMouseX = x;
452 gLastMouseY = y;
7a549148 453 showUI();
23cd2dcc
RK
454 break;
455 case "mousemove":
456 case "touchmove":
4b1d0915
RK
457 var x = coordObj.clientX - gMapCanvas.offsetLeft;
458 var y = coordObj.clientY - gMapCanvas.offsetTop;
23cd2dcc
RK
459 if (gDragging === true) {
460 var dX = x - gLastMouseX;
461 var dY = y - gLastMouseY;
b395419b
RK
462 gPos.x -= dX * gZoomFactor;
463 gPos.y -= dY * gZoomFactor;
b5e49b95
RK
464 var mapData = gMapContext.getImageData(0, 0, gMapCanvas.width, gMapCanvas.height);
465 gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
466 gMapContext.putImageData(mapData, dX, dY);
467 drawMap({left: (dX > 0) ? dX : 0,
468 right: (dX < 0) ? -dX : 0,
469 top: (dY > 0) ? dY : 0,
470 bottom: (dY < 0) ? -dY : 0});
7a549148 471 showUI();
23cd2dcc
RK
472 }
473 gLastMouseX = x;
474 gLastMouseY = y;
475 break;
476 case "mouseup":
477 case "touchend":
478 gDragging = false;
7a549148 479 showUI();
23cd2dcc
RK
480 break;
481 case "mouseout":
482 case "touchcancel":
483 case "touchleave":
484 //gDragging = false;
485 break;
486 case "DOMMouseScroll":
487 case "mousewheel":
488 var delta = 0;
489 if (aEvent.wheelDelta) {
490 delta = aEvent.wheelDelta / 120;
491 if (window.opera)
492 delta = -delta;
493 }
494 else if (aEvent.detail) {
495 delta = -aEvent.detail / 3;
496 }
497
55c4a0b7
RK
498 // Debug output: "coordinates" of the point the mouse was over.
499 /*
4b1d0915
RK
500 var ptCoord = {x: gPos.x + (x - gMapCanvas.width / 2) * gZoomFactor,
501 y: gPos.y + (x - gMapCanvas.height / 2) * gZoomFactor};
55c4a0b7
RK
502 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
503 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
915d4271
RK
504 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
505 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
506 pt2Coord.x + "/" + pt2Coord.y);
55c4a0b7 507 */
4b1d0915
RK
508
509 var newZoomLevel = gPos.z + (delta > 0 ? 1 : -1);
510 if ((newZoomLevel >= 0) && (newZoomLevel <= gMaxZoom)) {
511 // Calculate new center of the map - same point stays under the mouse.
512 // This means that the pixel distance between the old center and point
513 // must equal the pixel distance of the new center and that point.
514 var x = coordObj.clientX - gMapCanvas.offsetLeft;
515 var y = coordObj.clientY - gMapCanvas.offsetTop;
516
517 // Zoom factor after this action.
518 var newZoomFactor = Math.pow(2, gMaxZoom - newZoomLevel);
519 gPos.x -= (x - gMapCanvas.width / 2) * (newZoomFactor - gZoomFactor);
520 gPos.y -= (y - gMapCanvas.height / 2) * (newZoomFactor - gZoomFactor);
521
522 if (delta > 0)
523 zoomIn();
524 else if (delta < 0)
525 zoomOut();
526 }
23cd2dcc
RK
527 break;
528 }
529 }
530};
55c4a0b7 531
993fd081 532var geofake = {
55c4a0b7 533 tracking: false,
4b12da3a 534 lastPos: {x: undefined, y: undefined},
55c4a0b7
RK
535 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
536 this.tracking = true;
537 var watchCall = function() {
4b12da3a
RK
538 // calc new position in lat/lon degrees
539 // 90° on Earth surface are ~10,000 km at the equator,
540 // so try moving at most 10m at a time
541 if (geofake.lastPos.x)
542 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
543 else
544 geofake.lastPos.x = 48.208174
545 if (geofake.lastPos.y)
546 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
547 else
548 geofake.lastPos.y = 16.373819
55c4a0b7 549 aSuccessCallback({timestamp: Date.now(),
4b12da3a
RK
550 coords: {latitude: geofake.lastPos.x,
551 longitude: geofake.lastPos.y,
55c4a0b7
RK
552 accuracy: 20}});
553 if (geofake.tracking)
554 setTimeout(watchCall, 1000);
555 };
556 setTimeout(watchCall, 1000);
557 return "foo";
558 },
559 clearWatch: function(aID) {
560 this.tracking = false;
561 }
562}
563
3610c22d
RK
564function setCentering(aCheckbox) {
565 if (gMapPrefsLoaded && mainDB)
566 gPrefs.set("center_map", aCheckbox.checked);
567 gCenterPosition = aCheckbox.checked;
568}
569
570function setTracking(aCheckbox) {
571 if (gMapPrefsLoaded && mainDB)
572 gPrefs.set("tracking_enabled", aCheckbox.checked);
573 if (aCheckbox.checked)
574 startTracking();
575 else
576 endTracking();
577}
578
55c4a0b7 579function startTracking() {
31f0fe16 580 if (gGeolocation) {
68afcd96
RK
581 gActionLabel.textContent = "Establishing Position";
582 gAction.style.display = "block";
4b12da3a 583 gGeoWatchID = gGeolocation.watchPosition(
55c4a0b7 584 function(position) {
68afcd96
RK
585 if (gActionLabel.textContent) {
586 gActionLabel.textContent = "";
587 gAction.style.display = "none";
588 }
55c4a0b7 589 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
993fd081 590 var tPoint = {time: position.timestamp,
31f0fe16
RK
591 coords: {latitude: position.coords.latitude,
592 longitude: position.coords.longitude,
593 altitude: position.coords.altitude,
594 accuracy: position.coords.accuracy,
595 altitudeAccuracy: position.coords.altitudeAccuracy,
596 heading: position.coords.heading,
597 speed: position.coords.speed},
993fd081 598 beginSegment: !gLastTrackPoint};
b054bd48
RK
599 // Only add point to track is accuracy is good enough.
600 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
601 gLastTrackPoint = tPoint;
602 gTrack.push(tPoint);
603 try { gTrackStore.push(tPoint); } catch(e) {}
604 var redrawn = false;
605 if (gCenterPosition) {
606 var posCoord = gps2xy(position.coords.latitude,
607 position.coords.longitude);
4b1d0915
RK
608 if (Math.abs(gPos.x - posCoord.x) > gMapCanvas.width * gZoomFactor / 4 ||
609 Math.abs(gPos.y - posCoord.y) > gMapCanvas.height * gZoomFactor / 4) {
b054bd48
RK
610 gPos.x = posCoord.x;
611 gPos.y = posCoord.y;
612 drawMap(); // This draws the current point as well.
613 redrawn = true;
614 }
99631a75 615 }
b054bd48 616 if (!redrawn)
4b1d0915 617 undrawCurrentLocation();
b054bd48 618 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
05c21757 619 }
b054bd48 620 drawCurrentLocation(tPoint);
55c4a0b7
RK
621 },
622 function(error) {
623 // Ignore erros for the moment, but this is good for debugging.
624 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
915d4271
RK
625 if (gDebug)
626 console.log(error.message);
55c4a0b7
RK
627 },
628 {enableHighAccuracy: true}
629 );
630 }
631}
632
633function endTracking() {
68afcd96
RK
634 if (gActionLabel.textContent) {
635 gActionLabel.textContent = "";
636 gAction.style.display = "none";
637 }
55c4a0b7 638 if (gGeoWatchID) {
4b12da3a 639 gGeolocation.clearWatch(gGeoWatchID);
55c4a0b7
RK
640 }
641}
993fd081
RK
642
643function clearTrack() {
644 gTrack = [];
645 gTrackStore.clear();
646 drawMap();
647}
a8634d37
RK
648
649var gTileService = {
650 objStore: "tilecache",
651
5d67397a 652 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
3431f496 653
a8634d37
RK
654 get: function(aStyle, aCoords, aCallback) {
655 var norm = normalizeCoords(aCoords);
656 var dbkey = aStyle + "::" + norm.x + "," + norm.y + "," + norm.z;
657 this.getDBCache(dbkey, function(aResult, aEvent) {
658 if (aResult) {
659 // We did get a cached object.
a8634d37 660 aCallback(aResult.image, aStyle, aCoords);
3431f496 661 // Look at the timestamp and return if it's not too old.
5d67397a 662 if (aResult.timestamp + gTileService.ageLimit > Date.now())
3431f496
RK
663 return;
664 // Reload cached tile otherwise.
5d67397a
RK
665 var oldDate = new Date(aResult.timestamp);
666 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
a8634d37 667 }
3431f496
RK
668 // Retrieve image from the web and store it in the cache.
669 var XHR = new XMLHttpRequest();
670 XHR.open("GET",
671 gMapStyles[aStyle].url
672 .replace("{x}", norm.x)
673 .replace("{y}", norm.y)
674 .replace("{z}", norm.z)
675 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
676 .replace("[1-4]", 1 + Math.floor(Math.random() * 3)),
677 true);
678 XHR.responseType = "blob";
679 XHR.addEventListener("load", function () {
680 if (XHR.status === 200) {
681 var blob = XHR.response;
3431f496 682 aCallback(blob, aStyle, aCoords);
6d7cdcf6 683 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
3431f496
RK
684 }
685 }, false);
686 XHR.send();
a8634d37
RK
687 });
688 },
689
690 getDBCache: function(aKey, aCallback) {
691 if (!mainDB)
692 return;
693 var transaction = mainDB.transaction([this.objStore]);
694 var request = transaction.objectStore(this.objStore).get(aKey);
695 request.onsuccess = function(event) {
696 aCallback(request.result, event);
697 };
698 request.onerror = function(event) {
699 // Errors can be handled here.
700 aCallback(undefined, event);
701 };
702 },
703
704 setDBCache: function(aKey, aValue, aCallback) {
705 if (!mainDB)
706 return;
707 var success = false;
708 var transaction = mainDB.transaction([this.objStore], "readwrite");
709 var objStore = transaction.objectStore(this.objStore);
710 var request = objStore.put(aValue, 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
723 unsetDBCache: function(aKey, aCallback) {
724 if (!mainDB)
725 return;
726 var success = false;
727 var transaction = mainDB.transaction([this.objStore], "readwrite");
728 var request = transaction.objectStore(this.objStore).delete(aKey);
729 request.onsuccess = function(event) {
730 success = true;
731 if (aCallback)
732 aCallback(success, event);
733 };
734 request.onerror = function(event) {
735 // Errors can be handled here.
736 if (aCallback)
737 aCallback(success, event);
738 }
3431f496
RK
739 },
740
741 clearDB: function(aCallback) {
742 if (!mainDB)
743 return;
744 var success = false;
745 var transaction = mainDB.transaction([this.objStore], "readwrite");
746 var request = transaction.objectStore(this.objStore).clear();
747 request.onsuccess = function(event) {
748 success = true;
749 if (aCallback)
750 aCallback(success, event);
751 };
752 request.onerror = function(event) {
753 // Errors can be handled here.
754 if (aCallback)
755 aCallback(success, event);
756 }
a8634d37
RK
757 }
758};