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