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