merge changes with timeout change
[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
582d50fc
RK
92 console.log("map vars set, loading prefs...");
93 loadPrefs();
94}
b395419b 95
582d50fc
RK
96function loadPrefs(aEvent) {
97 if (aEvent && aEvent.type == "prefs-step") {
98 console.log("wait: " + gWaitCounter);
99 if (gWaitCounter == 0) {
100 gAction.removeEventListener(aEvent.type, loadPrefs, false);
101 gMapPrefsLoaded = true;
102 console.log("prefs loaded.");
103
104 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
105 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
106 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
107 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
108
109 gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
110 gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
111 gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
112 gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
113 gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
114
115 gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
116
117 document.getElementById("body").addEventListener("keydown", mapEvHandler, false);
118
119 document.getElementById("copyright").innerHTML =
120 gMapStyles[gActiveMap].copyright;
121
122 gLoadingTile = new Image();
123 gLoadingTile.src = "style/loading.png";
124 gLoadingTile.onload = function() {
125 var throwEv = new CustomEvent("mapinit-done");
126 gAction.dispatchEvent(throwEv);
127 };
128 }
129 }
130 else {
131 if (aEvent)
132 gAction.removeEventListener(aEvent.type, loadPrefs, false);
133 gAction.addEventListener("prefs-step", loadPrefs, false);
134 gWaitCounter++;
135 gPrefs.get("position", function(aValue) {
136 if (aValue) {
137 gPos = aValue;
138 gWaitCounter--;
139 }
140 });
141 gWaitCounter++;
142 gPrefs.get("center_map", function(aValue) {
143 if (aValue === undefined)
144 document.getElementById("centerCheckbox").checked = true;
145 else
146 document.getElementById("centerCheckbox").checked = aValue;
147 setCentering(document.getElementById("centerCheckbox"));
148 gWaitCounter--;
149 var throwEv = new CustomEvent("prefs-step");
150 gAction.dispatchEvent(throwEv);
151 });
152 gWaitCounter++;
153 gPrefs.get("tracking_enabled", function(aValue) {
154 if (aValue === undefined)
155 document.getElementById("trackCheckbox").checked = true;
156 else
157 document.getElementById("trackCheckbox").checked = aValue;
158 gWaitCounter--;
159 var throwEv = new CustomEvent("prefs-step");
160 gAction.dispatchEvent(throwEv);
161 });
162 gWaitCounter++;
163 gTrackStore.getList(function(aTPoints) {
164 if (gDebug)
165 console.log(aTPoints.length + " points loaded.");
166 if (aTPoints.length) {
167 gTrack = aTPoints;
168 }
169 gWaitCounter--;
170 var throwEv = new CustomEvent("prefs-step");
171 gAction.dispatchEvent(throwEv);
172 });
173 }
23cd2dcc
RK
174}
175
176function resizeAndDraw() {
321359cd
RK
177 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
178 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
915d4271
RK
179 if (gMapCanvas && gTrackCanvas) {
180 gMapCanvas.width = viewportWidth;
181 gMapCanvas.height = viewportHeight;
182 gTrackCanvas.width = viewportWidth;
183 gTrackCanvas.height = viewportHeight;
184 drawMap();
185 showUI();
186 }
23cd2dcc
RK
187}
188
b5e49b95
RK
189// Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
190// See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
191
23cd2dcc
RK
192function zoomIn() {
193 if (gPos.z < gMaxZoom) {
194 gPos.z++;
195 drawMap();
196 }
197}
198
199function zoomOut() {
200 if (gPos.z > 0) {
201 gPos.z--;
202 drawMap();
203 }
204}
205
1222624d
RK
206function zoomTo(aTargetLevel) {
207 aTargetLevel = parseInt(aTargetLevel);
208 if (aTargetLevel >= 0 && aTargetLevel <= gMaxZoom) {
209 gPos.z = aTargetLevel;
210 drawMap();
211 }
212}
213
55c4a0b7
RK
214function gps2xy(aLatitude, aLongitude) {
215 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
216 var convLat = aLatitude * Math.PI / 180;
217 var rawY = (1 - Math.log(Math.tan(convLat) +
218 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
219 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
220 return {x: Math.round(rawX),
221 y: Math.round(rawY)};
222}
223
224function xy2gps(aX, aY) {
225 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
226 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
227 return {latitude: 180 / Math.PI *
228 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
229 longitude: aX / maxZoomFactor * 360 - 180};
230}
231
b47b4a65
RK
232function setMapStyle() {
233 var mapSel = document.getElementById("mapSelector");
234 if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
235 gActiveMap = mapSel.value;
95f49ba7
RK
236 document.getElementById("copyright").innerHTML =
237 gMapStyles[gActiveMap].copyright;
b5c85133 238 showUI();
b47b4a65
RK
239 drawMap();
240 }
241}
242
23cd2dcc
RK
243// A sane mod function that works for negative numbers.
244// Returns a % b.
245function mod(a, b) {
246 return ((a % b) + b) % b;
247}
248
a8634d37
RK
249function normalizeCoords(aCoords) {
250 var zoomFactor = Math.pow(2, aCoords.z);
251 return {x: mod(aCoords.x, zoomFactor),
252 y: mod(aCoords.y, zoomFactor),
253 z: aCoords.z};
23cd2dcc
RK
254}
255
256// Returns true if the tile is outside the current view.
257function isOutsideWindow(t) {
258 var pos = decodeIndex(t);
23cd2dcc 259
4b1d0915
RK
260 var zoomFactor = Math.pow(2, gMaxZoom - pos.z);
261 var wid = gMapCanvas.width * zoomFactor;
262 var ht = gMapCanvas.height * zoomFactor;
23cd2dcc 263
4b1d0915
RK
264 pos.x *= zoomFactor;
265 pos.y *= zoomFactor;
23cd2dcc 266
b395419b 267 var sz = gTileSize * zoomFactor;
4b1d0915
RK
268 if (pos.x > gPos.x + wid / 2 || pos.y > gPos.y + ht / 2 ||
269 pos.x + sz < gPos.x - wid / 2 || pos.y - sz < gPos.y - ht / 2)
23cd2dcc
RK
270 return true;
271 return false;
272}
273
274function encodeIndex(x, y, z) {
a8634d37 275 var norm = normalizeCoords({x: x, y: y, z: z});
23cd2dcc
RK
276 return norm.x + "," + norm.y + "," + norm.z;
277}
278
279function decodeIndex(encodedIdx) {
4b1d0915
RK
280 var ind = encodedIdx.split(",", 3);
281 return {x: ind[0], y: ind[1], z: ind[2]};
23cd2dcc
RK
282}
283
b5e49b95
RK
284function drawMap(aPixels, aOverdraw) {
285 // aPixels is an object with left/right/top/bottom members telling how many
286 // pixels on the borders should actually be drawn.
287 // aOverdraw is a bool that tells if we should draw placeholders or draw
288 // straight over the existing content.
289 if (!aPixels)
290 aPixels = {left: gMapCanvas.width, right: gMapCanvas.width,
291 top: gMapCanvas.height, bottom: gMapCanvas.height};
292 if (!aOverdraw)
293 aOverdraw = false;
294
b395419b
RK
295 document.getElementById("zoomLevel").textContent = gPos.z;
296 gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
4b1d0915
RK
297 var wid = gMapCanvas.width * gZoomFactor; // Width in level 18 pixels.
298 var ht = gMapCanvas.height * gZoomFactor; // Height in level 18 pixels.
b395419b 299 var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
23cd2dcc
RK
300
301 var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
302 var yMin = gPos.y - ht / 2;
303 var xMax = gPos.x + wid / 2;
304 var yMax = gPos.y + ht / 2;
305
3610c22d
RK
306 if (gMapPrefsLoaded && mainDB)
307 gPrefs.set("position", gPos);
308
b5e49b95
RK
309 var tiles = {left: Math.ceil((xMin + aPixels.left * gZoomFactor) / size) -
310 (aPixels.left ? 0 : 1),
311 right: Math.floor((xMax - aPixels.right * gZoomFactor) / size) -
312 (aPixels.right ? 1 : 0),
313 top: Math.ceil((yMin + aPixels.top * gZoomFactor) / size) -
314 (aPixels.top ? 0 : 1),
315 bottom: Math.floor((yMax - aPixels.bottom * gZoomFactor) / size) -
316 (aPixels.bottom ? 1 : 0)};
317
318 // Go through all the tiles in the map, find out if to draw them and do so.
b47b4a65 319 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
0118cbd3 320 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
b5e49b95 321 // Only go to the drawing step if we need to draw this tile.
68afcd96
RK
322 if (x < tiles.left || x > tiles.right ||
323 y < tiles.top || y > tiles.bottom) {
b5e49b95
RK
324 // Round here is **CRUCIAL** otherwise the images are filtered
325 // and the performance sucks (more than expected).
326 var xoff = Math.round((x * size - xMin) / gZoomFactor);
327 var yoff = Math.round((y * size - yMin) / gZoomFactor);
328 // Draw placeholder tile unless we overdraw.
68afcd96
RK
329 if (!aOverdraw &&
330 (x < tiles.left -1 || x > tiles.right + 1 ||
331 y < tiles.top -1 || y > tiles.bottom + 1))
b5e49b95
RK
332 gMapContext.drawImage(gLoadingTile, xoff, yoff);
333
334 // Initiate loading/drawing of the actual tile.
335 gTileService.get(gActiveMap, {x: x, y: y, z: gPos.z},
336 function(aImage, aStyle, aCoords) {
337 // Only draw if this applies for the current view.
338 if ((aStyle == gActiveMap) && (aCoords.z == gPos.z)) {
339 var ixMin = gPos.x - wid / 2;
340 var iyMin = gPos.y - ht / 2;
341 var ixoff = Math.round((aCoords.x * size - ixMin) / gZoomFactor);
342 var iyoff = Math.round((aCoords.y * size - iyMin) / gZoomFactor);
343 var URL = window.URL;
344 var imgURL = URL.createObjectURL(aImage);
345 var imgObj = new Image();
346 imgObj.src = imgURL;
347 imgObj.onload = function() {
348 gMapContext.drawImage(imgObj, ixoff, iyoff);
349 URL.revokeObjectURL(imgURL);
350 }
a2131f63 351 }
b5e49b95
RK
352 });
353 }
23cd2dcc
RK
354 }
355 }
4b1d0915
RK
356 gLastDrawnPoint = null;
357 gCurPosMapCache = undefined;
358 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
14e6d3ad 359 if (gTrack.length) {
55c4a0b7 360 for (var i = 0; i < gTrack.length; i++) {
14e6d3ad
RK
361 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
362 (i + 1 >= gTrack.length));
55c4a0b7 363 }
14e6d3ad 364 }
55c4a0b7
RK
365}
366
14e6d3ad 367function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
55c4a0b7 368 var trackpoint = gps2xy(aLatitude, aLongitude);
14e6d3ad
RK
369 // lastPoint is for optimizing (not actually executing the draw until the last)
370 trackpoint.optimized = (lastPoint === false);
4b1d0915
RK
371 var mappos = {x: Math.round((trackpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
372 y: Math.round((trackpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
14e6d3ad
RK
373
374 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
4b1d0915
RK
375 gTrackContext.strokeStyle = gTrackColor;
376 gTrackContext.fillStyle = gTrackContext.strokeStyle;
377 gTrackContext.lineWidth = gTrackWidth;
378 gTrackContext.lineCap = "round";
379 gTrackContext.lineJoin = "round";
14e6d3ad
RK
380 }
381 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
382 // This breaks optimiziation, so make sure to close path and reset optimization.
383 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
4b1d0915
RK
384 gTrackContext.stroke();
385 gTrackContext.beginPath();
14e6d3ad 386 trackpoint.optimized = false;
4b1d0915
RK
387 gTrackContext.arc(mappos.x, mappos.y,
388 gTrackContext.lineWidth, 0, Math.PI * 2, false);
389 gTrackContext.fill();
55c4a0b7
RK
390 }
391 else {
14e6d3ad 392 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
4b1d0915
RK
393 gTrackContext.beginPath();
394 gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
395 Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2));
14e6d3ad 396 }
4b1d0915 397 gTrackContext.lineTo(mappos.x, mappos.y);
14e6d3ad 398 if (!trackpoint.optimized)
4b1d0915 399 gTrackContext.stroke();
55c4a0b7 400 }
14e6d3ad 401 gLastDrawnPoint = trackpoint;
23cd2dcc
RK
402}
403
b054bd48 404function drawCurrentLocation(trackPoint) {
4b1d0915
RK
405 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
406 var circleRadius = Math.round(gCurLocSize / 2);
407 var mappos = {x: Math.round((locpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
408 y: Math.round((locpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
409
410 undrawCurrentLocation();
b054bd48
RK
411
412 // Cache overdrawn area.
4b1d0915
RK
413 gCurPosMapCache =
414 {point: locpoint,
415 radius: circleRadius,
416 data: gTrackContext.getImageData(mappos.x - circleRadius,
417 mappos.y - circleRadius,
418 circleRadius * 2, circleRadius * 2)};
419
420 gTrackContext.strokeStyle = gCurLocColor;
421 gTrackContext.fillStyle = gTrackContext.strokeStyle;
422 gTrackContext.beginPath();
423 gTrackContext.arc(mappos.x, mappos.y,
424 circleRadius, 0, Math.PI * 2, false);
425 gTrackContext.fill();
426}
427
428function undrawCurrentLocation() {
429 if (gCurPosMapCache) {
430 var oldpoint = gCurPosMapCache.point;
431 var oldmp = {x: Math.round((oldpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
432 y: Math.round((oldpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
433 gTrackContext.putImageData(gCurPosMapCache.data,
434 oldmp.x - gCurPosMapCache.radius,
435 oldmp.y - gCurPosMapCache.radius);
436 gCurPosMapCache = undefined;
437 }
b054bd48
RK
438}
439
23cd2dcc
RK
440var mapEvHandler = {
441 handleEvent: function(aEvent) {
442 var touchEvent = aEvent.type.indexOf('touch') != -1;
443
8389557a
RK
444 // Bail out if the event is happening on an input.
445 if (aEvent.target.tagName.toLowerCase() == "input")
446 return;
447
1222624d
RK
448 // Bail out on unwanted map moves, but not zoom or keyboard events.
449 if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
23cd2dcc
RK
450 // Bail out if this is neither a touch nor left-click.
451 if (!touchEvent && aEvent.button != 0)
452 return;
453
454 // Bail out if the started touch can't be found.
4b12da3a
RK
455 if (touchEvent && gDragging &&
456 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
23cd2dcc
RK
457 return;
458 }
459
460 var coordObj = touchEvent ?
4b12da3a 461 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
23cd2dcc
RK
462 aEvent;
463
464 switch (aEvent.type) {
465 case "mousedown":
466 case "touchstart":
467 if (touchEvent) {
4b12da3a
RK
468 gDragTouchID = aEvent.changedTouches.item(0).identifier;
469 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
23cd2dcc 470 }
4b1d0915
RK
471 var x = coordObj.clientX - gMapCanvas.offsetLeft;
472 var y = coordObj.clientY - gMapCanvas.offsetTop;
b395419b 473
23cd2dcc
RK
474 if (touchEvent || aEvent.button === 0) {
475 gDragging = true;
476 }
477 gLastMouseX = x;
478 gLastMouseY = y;
7a549148 479 showUI();
23cd2dcc
RK
480 break;
481 case "mousemove":
482 case "touchmove":
4b1d0915
RK
483 var x = coordObj.clientX - gMapCanvas.offsetLeft;
484 var y = coordObj.clientY - gMapCanvas.offsetTop;
23cd2dcc
RK
485 if (gDragging === true) {
486 var dX = x - gLastMouseX;
487 var dY = y - gLastMouseY;
b395419b
RK
488 gPos.x -= dX * gZoomFactor;
489 gPos.y -= dY * gZoomFactor;
747bbd55
RK
490 if (true) { // use optimized path
491 var mapData = gMapContext.getImageData(0, 0,
492 gMapCanvas.width,
493 gMapCanvas.height);
494 gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
495 gMapContext.putImageData(mapData, dX, dY);
496 drawMap({left: (dX > 0) ? dX : 0,
497 right: (dX < 0) ? -dX : 0,
498 top: (dY > 0) ? dY : 0,
499 bottom: (dY < 0) ? -dY : 0});
500 }
501 else {
502 drawMap(false, true);
503 }
7a549148 504 showUI();
23cd2dcc
RK
505 }
506 gLastMouseX = x;
507 gLastMouseY = y;
508 break;
509 case "mouseup":
510 case "touchend":
511 gDragging = false;
7a549148 512 showUI();
23cd2dcc
RK
513 break;
514 case "mouseout":
515 case "touchcancel":
516 case "touchleave":
517 //gDragging = false;
518 break;
5fb31b29
RK
519 case "wheel":
520 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
521 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
522
523 // Only accept (non-null) deltaY values
524 if (!aEvent.deltaY)
525 break;
23cd2dcc 526
55c4a0b7
RK
527 // Debug output: "coordinates" of the point the mouse was over.
528 /*
4b1d0915
RK
529 var ptCoord = {x: gPos.x + (x - gMapCanvas.width / 2) * gZoomFactor,
530 y: gPos.y + (x - gMapCanvas.height / 2) * gZoomFactor};
55c4a0b7
RK
531 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
532 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
915d4271
RK
533 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
534 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
535 pt2Coord.x + "/" + pt2Coord.y);
55c4a0b7 536 */
4b1d0915 537
5fb31b29 538 var newZoomLevel = gPos.z + (aEvent.deltaY < 0 ? 1 : -1);
4b1d0915
RK
539 if ((newZoomLevel >= 0) && (newZoomLevel <= gMaxZoom)) {
540 // Calculate new center of the map - same point stays under the mouse.
541 // This means that the pixel distance between the old center and point
542 // must equal the pixel distance of the new center and that point.
543 var x = coordObj.clientX - gMapCanvas.offsetLeft;
544 var y = coordObj.clientY - gMapCanvas.offsetTop;
545
546 // Zoom factor after this action.
547 var newZoomFactor = Math.pow(2, gMaxZoom - newZoomLevel);
548 gPos.x -= (x - gMapCanvas.width / 2) * (newZoomFactor - gZoomFactor);
549 gPos.y -= (y - gMapCanvas.height / 2) * (newZoomFactor - gZoomFactor);
550
5fb31b29 551 if (aEvent.deltaY < 0)
4b1d0915 552 zoomIn();
5fb31b29 553 else
4b1d0915
RK
554 zoomOut();
555 }
23cd2dcc 556 break;
1222624d
RK
557 case "keydown":
558 // Allow keyboard control to move and zoom the map.
559 // Should use aEvent.key instead of aEvent.which but needs bug 680830.
560 // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
561 var dX = 0;
562 var dY = 0;
563 switch (aEvent.which) {
564 case 39: // right
565 dX = -gTileSize / 2;
566 break;
567 case 37: // left
568 dX = gTileSize / 2;
569 break;
570 case 38: // up
571 dY = gTileSize / 2;
572 break;
573 case 40: // down
574 dY = -gTileSize / 2;
575 break;
576 case 87: // w
577 case 107: // + (numpad)
578 case 171: // + (normal key)
579 zoomIn();
580 break;
581 case 83: // s
582 case 109: // - (numpad)
583 case 173: // - (normal key)
584 zoomOut();
585 break;
586 case 48: // 0
587 case 49: // 1
588 case 50: // 2
589 case 51: // 3
590 case 52: // 4
591 case 53: // 5
592 case 54: // 6
593 case 55: // 7
594 case 56: // 8
595 zoomTo(aEvent.which - 38);
596 break;
597 case 57: // 9
598 zoomTo(9);
599 break;
600 case 96: // 0 (numpad)
601 case 97: // 1 (numpad)
602 case 98: // 2 (numpad)
603 case 99: // 3 (numpad)
604 case 100: // 4 (numpad)
605 case 101: // 5 (numpad)
606 case 102: // 6 (numpad)
607 case 103: // 7 (numpad)
608 case 104: // 8 (numpad)
609 zoomTo(aEvent.which - 86);
610 break;
611 case 105: // 9 (numpad)
612 zoomTo(9);
613 break;
614 default: // not supported
615 console.log("key not supported: " + aEvent.which);
616 break;
617 }
618
619 // Move if needed.
620 if (dX || dY) {
621 gPos.x -= dX * gZoomFactor;
622 gPos.y -= dY * gZoomFactor;
623 if (true) { // use optimized path
624 var mapData = gMapContext.getImageData(0, 0,
625 gMapCanvas.width,
626 gMapCanvas.height);
627 gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
628 gMapContext.putImageData(mapData, dX, dY);
629 drawMap({left: (dX > 0) ? dX : 0,
630 right: (dX < 0) ? -dX : 0,
631 top: (dY > 0) ? dY : 0,
632 bottom: (dY < 0) ? -dY : 0});
633 }
634 else {
635 drawMap(false, true);
636 }
637 }
638 break;
23cd2dcc
RK
639 }
640 }
641};
55c4a0b7 642
993fd081 643var geofake = {
55c4a0b7 644 tracking: false,
4b12da3a 645 lastPos: {x: undefined, y: undefined},
55c4a0b7
RK
646 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
647 this.tracking = true;
648 var watchCall = function() {
4b12da3a
RK
649 // calc new position in lat/lon degrees
650 // 90° on Earth surface are ~10,000 km at the equator,
651 // so try moving at most 10m at a time
652 if (geofake.lastPos.x)
653 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
654 else
655 geofake.lastPos.x = 48.208174
656 if (geofake.lastPos.y)
657 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
658 else
659 geofake.lastPos.y = 16.373819
55c4a0b7 660 aSuccessCallback({timestamp: Date.now(),
4b12da3a
RK
661 coords: {latitude: geofake.lastPos.x,
662 longitude: geofake.lastPos.y,
55c4a0b7
RK
663 accuracy: 20}});
664 if (geofake.tracking)
665 setTimeout(watchCall, 1000);
666 };
667 setTimeout(watchCall, 1000);
668 return "foo";
669 },
670 clearWatch: function(aID) {
671 this.tracking = false;
672 }
673}
674
3610c22d
RK
675function setCentering(aCheckbox) {
676 if (gMapPrefsLoaded && mainDB)
677 gPrefs.set("center_map", aCheckbox.checked);
678 gCenterPosition = aCheckbox.checked;
679}
680
681function setTracking(aCheckbox) {
682 if (gMapPrefsLoaded && mainDB)
683 gPrefs.set("tracking_enabled", aCheckbox.checked);
684 if (aCheckbox.checked)
685 startTracking();
686 else
687 endTracking();
688}
689
55c4a0b7 690function startTracking() {
31f0fe16 691 if (gGeolocation) {
68afcd96
RK
692 gActionLabel.textContent = "Establishing Position";
693 gAction.style.display = "block";
4b12da3a 694 gGeoWatchID = gGeolocation.watchPosition(
55c4a0b7 695 function(position) {
68afcd96
RK
696 if (gActionLabel.textContent) {
697 gActionLabel.textContent = "";
698 gAction.style.display = "none";
699 }
55c4a0b7 700 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
993fd081 701 var tPoint = {time: position.timestamp,
31f0fe16
RK
702 coords: {latitude: position.coords.latitude,
703 longitude: position.coords.longitude,
704 altitude: position.coords.altitude,
705 accuracy: position.coords.accuracy,
706 altitudeAccuracy: position.coords.altitudeAccuracy,
707 heading: position.coords.heading,
708 speed: position.coords.speed},
993fd081 709 beginSegment: !gLastTrackPoint};
b054bd48
RK
710 // Only add point to track is accuracy is good enough.
711 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
712 gLastTrackPoint = tPoint;
713 gTrack.push(tPoint);
714 try { gTrackStore.push(tPoint); } catch(e) {}
715 var redrawn = false;
716 if (gCenterPosition) {
717 var posCoord = gps2xy(position.coords.latitude,
718 position.coords.longitude);
4b1d0915
RK
719 if (Math.abs(gPos.x - posCoord.x) > gMapCanvas.width * gZoomFactor / 4 ||
720 Math.abs(gPos.y - posCoord.y) > gMapCanvas.height * gZoomFactor / 4) {
b054bd48
RK
721 gPos.x = posCoord.x;
722 gPos.y = posCoord.y;
723 drawMap(); // This draws the current point as well.
724 redrawn = true;
725 }
99631a75 726 }
b054bd48 727 if (!redrawn)
4b1d0915 728 undrawCurrentLocation();
b054bd48 729 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
05c21757 730 }
b054bd48 731 drawCurrentLocation(tPoint);
55c4a0b7
RK
732 },
733 function(error) {
734 // Ignore erros for the moment, but this is good for debugging.
735 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
915d4271
RK
736 if (gDebug)
737 console.log(error.message);
55c4a0b7
RK
738 },
739 {enableHighAccuracy: true}
740 );
741 }
742}
743
744function endTracking() {
68afcd96
RK
745 if (gActionLabel.textContent) {
746 gActionLabel.textContent = "";
747 gAction.style.display = "none";
748 }
55c4a0b7 749 if (gGeoWatchID) {
4b12da3a 750 gGeolocation.clearWatch(gGeoWatchID);
55c4a0b7
RK
751 }
752}
993fd081
RK
753
754function clearTrack() {
755 gTrack = [];
756 gTrackStore.clear();
400c082d 757 drawMap({left: 0, right: 0, top: 0, bottom: 0});
993fd081 758}
a8634d37
RK
759
760var gTileService = {
761 objStore: "tilecache",
762
5d67397a 763 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
3431f496 764
a8634d37
RK
765 get: function(aStyle, aCoords, aCallback) {
766 var norm = normalizeCoords(aCoords);
767 var dbkey = aStyle + "::" + norm.x + "," + norm.y + "," + norm.z;
768 this.getDBCache(dbkey, function(aResult, aEvent) {
769 if (aResult) {
770 // We did get a cached object.
a8634d37 771 aCallback(aResult.image, aStyle, aCoords);
3431f496 772 // Look at the timestamp and return if it's not too old.
5d67397a 773 if (aResult.timestamp + gTileService.ageLimit > Date.now())
3431f496
RK
774 return;
775 // Reload cached tile otherwise.
5d67397a
RK
776 var oldDate = new Date(aResult.timestamp);
777 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
a8634d37 778 }
3431f496
RK
779 // Retrieve image from the web and store it in the cache.
780 var XHR = new XMLHttpRequest();
781 XHR.open("GET",
782 gMapStyles[aStyle].url
783 .replace("{x}", norm.x)
784 .replace("{y}", norm.y)
785 .replace("{z}", norm.z)
786 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
787 .replace("[1-4]", 1 + Math.floor(Math.random() * 3)),
788 true);
789 XHR.responseType = "blob";
790 XHR.addEventListener("load", function () {
791 if (XHR.status === 200) {
792 var blob = XHR.response;
3431f496 793 aCallback(blob, aStyle, aCoords);
6d7cdcf6 794 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
3431f496
RK
795 }
796 }, false);
797 XHR.send();
a8634d37
RK
798 });
799 },
800
801 getDBCache: function(aKey, aCallback) {
802 if (!mainDB)
803 return;
804 var transaction = mainDB.transaction([this.objStore]);
805 var request = transaction.objectStore(this.objStore).get(aKey);
806 request.onsuccess = function(event) {
807 aCallback(request.result, event);
808 };
809 request.onerror = function(event) {
810 // Errors can be handled here.
811 aCallback(undefined, event);
812 };
813 },
814
815 setDBCache: function(aKey, aValue, aCallback) {
816 if (!mainDB)
817 return;
818 var success = false;
819 var transaction = mainDB.transaction([this.objStore], "readwrite");
820 var objStore = transaction.objectStore(this.objStore);
821 var request = objStore.put(aValue, aKey);
822 request.onsuccess = function(event) {
823 success = true;
824 if (aCallback)
825 aCallback(success, event);
826 };
827 request.onerror = function(event) {
828 // Errors can be handled here.
829 if (aCallback)
830 aCallback(success, event);
831 };
832 },
833
834 unsetDBCache: function(aKey, aCallback) {
835 if (!mainDB)
836 return;
837 var success = false;
838 var transaction = mainDB.transaction([this.objStore], "readwrite");
839 var request = transaction.objectStore(this.objStore).delete(aKey);
840 request.onsuccess = function(event) {
841 success = true;
842 if (aCallback)
843 aCallback(success, event);
844 };
845 request.onerror = function(event) {
846 // Errors can be handled here.
847 if (aCallback)
848 aCallback(success, event);
849 }
3431f496
RK
850 },
851
852 clearDB: function(aCallback) {
853 if (!mainDB)
854 return;
855 var success = false;
856 var transaction = mainDB.transaction([this.objStore], "readwrite");
857 var request = transaction.objectStore(this.objStore).clear();
858 request.onsuccess = function(event) {
859 success = true;
860 if (aCallback)
861 aCallback(success, event);
862 };
863 request.onerror = function(event) {
864 // Errors can be handled here.
865 if (aCallback)
866 aCallback(success, event);
867 }
a8634d37
RK
868 }
869};