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