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