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