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 | |
aa45a91b | 5 | var gGLMapCanvas, gTrackCanvas, gGeolocation; |
0dc9cd0d | 6 | var gDebug = false; |
23cd2dcc | 7 | |
b054bd48 | 8 | var gMinTrackAccuracy = 1000; // meters |
68ca4617 | 9 | var gCenterDelayAfterMove = 3000; // milliseconds |
b054bd48 | 10 | |
b47b4a65 RK |
11 | var gMapStyles = { |
12 | // OSM tile usage policy: http://wiki.openstreetmap.org/wiki/Tile_usage_policy | |
55c4a0b7 | 13 | // Find some more OSM ones at http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers |
ca77d52d | 14 | // and http://wiki.openstreetmap.org/wiki/Tiles or http://wiki.openstreetmap.org/wiki/TMS |
b47b4a65 RK |
15 | osm_mapnik: |
16 | {name: "OpenStreetMap (Mapnik)", | |
a40d8348 | 17 | url: "https://[a-c].tile.openstreetmap.org/{z}/{x}/{y}.png", |
5a19ec68 | 18 | 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 |
19 | osm_cyclemap: |
20 | {name: "Cycle Map (OSM)", | |
a40d8348 | 21 | url: "https://[a-c].tile.thunderforest.com/cycle/{z}/{x}/{y}.png", // "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png", |
5a19ec68 | 22 | 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 |
23 | osm_transmap: |
24 | {name: "Transport Map (OSM)", | |
a40d8348 | 25 | url: "https://[a-c].tile.thunderforest.com/transport/{z}/{x}/{y}.png", // "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png", |
5a19ec68 | 26 | 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>'}, |
ca77d52d RK |
27 | osm_germany: |
28 | {name: "OSM German Style", | |
9e501811 | 29 | url: "https://tilecache[1-4].kairo.at/osmde/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at |
e4840ddc | 30 | //url: "http://[a-d].tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png", // https is not supported at all |
ca77d52d | 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>'}, |
e4840ddc RK |
32 | oepnvkarte: |
33 | {name: "ÖPNV-Karte (OSM)", | |
9e501811 | 34 | url: "https://tilecache[1-4].kairo.at/oepnv/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at |
e4840ddc RK |
35 | //url: "http://tileserver.memomaps.de/tilegen/{z}/{x}/{y}.png", // memomaps.de does not support CORS or https at this time :( |
36 | copyright: 'Map data © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://memomaps.de">MeMoMaps</a> under <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>.'}, | |
b47b4a65 | 37 | mapquest_open: |
55c4a0b7 | 38 | {name: "MapQuest OSM", |
31011cc9 | 39 | url: "https://tilecache[1-4].kairo.at/mapqosm/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at |
e4840ddc | 40 | //url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png", // https has wrong cert, akamai instead of mqcdn |
ca77d52d | 41 | 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 |
42 | mapquest_aerial: |
43 | {name: "MapQuest Open Aerial", | |
31011cc9 | 44 | url: "https://tilecache[1-4].kairo.at/mapqsat/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at |
e4840ddc | 45 | //url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg", |
5a19ec68 | 46 | 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.'}, |
ca77d52d RK |
47 | osm_hot: |
48 | {name: "OSM HOT style", | |
31011cc9 | 49 | url: "https://tilecache[1-4].kairo.at/osmhot/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at |
e4840ddc | 50 | //url: "http://[a-c].tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", // https has CAcert which doesn't work in browsers |
ca77d52d | 51 | 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>'}, |
09388984 RK |
52 | opentopomap: |
53 | {name: "OpenTopoMap", | |
54 | //url: "https://tilecache[1-4].kairo.at/opentopomap/{z}/{x}/{y}.png", // route through tilecache @ kairo.at | |
55 | url: "https://[a-c].tile.opentopomap.org/{z}/{x}/{y}.png", | |
56 | copyright: 'Map data: © <a href="https://openstreetmap.org/copyright">OpenStreetMap</a> contributors, <a href="http://viewfinderpanoramas.org">SRTM</a> | map style: © <a href="https://opentopomap.org">OpenTopoMap</a> (<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)'}, | |
e4840ddc RK |
57 | hikebike: |
58 | {name: "Hike and Bike (OSM)", | |
31011cc9 | 59 | url: "https://tilecache[1-4].kairo.at/hikebike/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at |
e4840ddc RK |
60 | //url: "http://toolserver.org/tiles/hikebike/{z}/{x}/{y}.png", // toolserver.org does not support CORS at this time :( |
61 | 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>'}, | |
62 | outdoors: | |
63 | {name: "Outdoors (OSM)", | |
31011cc9 | 64 | url: "https://[a-c].tile.thunderforest.com/outdoors/{z}/{x}/{y}.png", // url: "http://[a-c].tile.opencyclemap.org/outdoors/{z}/{x}/{y}.png", |
e4840ddc | 65 | 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 by <a href="http://www.thunderforest.com/">Thunderforest</a>.'}, |
ca77d52d | 66 | stamen_toner: |
e4840ddc | 67 | {name: "Stamen Toner (B+W)", |
31011cc9 | 68 | url: "https://tilecache[1-4].kairo.at/toner/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at |
e4840ddc | 69 | //url: "http://[a-c].tile.stamen.com/toner/{z}/{x}/{y}.jpg", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com |
ca77d52d RK |
70 | copyright: 'Map data © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>.'}, |
71 | stamen_terrain: | |
e4840ddc | 72 | {name: "Stamen Terrain (USA only)", |
31011cc9 | 73 | url: "https://tilecache[1-4].kairo.at/terrain/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at |
e4840ddc | 74 | //url: "http://[a-c].tile.stamen.com/terrain/{z}/{x}/{y}.jpg", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com |
ca77d52d RK |
75 | copyright: 'Map data © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>.'}, |
76 | stamen_watercolor: | |
e4840ddc | 77 | {name: "Stamen Watercolor (artistic)", |
31011cc9 | 78 | url: "https://tilecache[1-4].kairo.at/watercolor/{z}/{x}/{y}.png", // route through CORS+SSL tilecache @ kairo.at |
e4840ddc | 79 | //url: "http://[a-c].tile.stamen.com/watercolor/{z}/{x}/{y}.jpg", // https has wrong cert, .ssl.fastly.net instead of .tile.stamen.com |
ca77d52d | 80 | copyright: 'Map data © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>, tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>.'}, |
b47b4a65 | 81 | }; |
23cd2dcc RK |
82 | |
83 | var gLastMouseX = 0; | |
84 | var gLastMouseY = 0; | |
85 | ||
b395419b | 86 | var gLoadingTile; |
23cd2dcc | 87 | |
3610c22d RK |
88 | var gMapPrefsLoaded = false; |
89 | ||
23cd2dcc | 90 | var gDragging = false; |
517c0099 | 91 | var gDragTouchID, gPinchStartWidth; |
23cd2dcc | 92 | |
d361104b | 93 | var gGeoWatchID, gGPSWakeLock; |
55c4a0b7 | 94 | var gTrack = []; |
aa45a91b | 95 | var gLastTrackPoint; |
05c21757 | 96 | var gCenterPosition = true; |
68ca4617 | 97 | var gLastMoveAction = null; |
55c4a0b7 | 98 | |
b47b4a65 | 99 | function initMap() { |
4b12da3a | 100 | gGeolocation = navigator.geolocation; |
ac6286bd RK |
101 | // Set up canvas context. |
102 | gGLMapCanvas = document.getElementById("map"); | |
ecde0af2 RK |
103 | try { |
104 | // Try to grab the standard context. If it fails, fallback to experimental. | |
105 | // We also try to tell it we do not need a depth buffer. | |
edc3be71 RK |
106 | gMap.gl = gGLMapCanvas.getContext("webgl", {depth: false}) || |
107 | gGLMapCanvas.getContext("experimental-webgl", {depth: false}); | |
ecde0af2 RK |
108 | } |
109 | catch(e) {} | |
edc3be71 | 110 | if (!gMap.gl) { |
16e4f664 | 111 | // If we don't have a GL context, give up now |
ecde0af2 | 112 | showGLWarningDialog(); |
edc3be71 | 113 | gMap.gl = null; |
ecde0af2 | 114 | } |
16e4f664 RK |
115 | else { |
116 | // GL context can be lost at any time, handle that. | |
117 | // See http://www.khronos.org/webgl/wiki/HandlingContextLost | |
118 | gGLMapCanvas.addEventListener("webglcontextlost", | |
119 | gMap.handleContextLost, false); | |
120 | gGLMapCanvas.addEventListener("webglcontextrestored", | |
121 | gMap.handleContextRestored, false); | |
122 | } | |
4b1d0915 | 123 | gTrackCanvas = document.getElementById("track"); |
aa45a91b | 124 | gTrackLayer.context = gTrackCanvas.getContext("2d"); |
23cd2dcc | 125 | |
4b12da3a RK |
126 | //gDebug = true; |
127 | if (gDebug) { | |
128 | gGeolocation = geofake; | |
129 | var hiddenList = document.getElementsByClassName("debugHide"); | |
130 | // last to first - list of elements with that class is changing! | |
131 | for (var i = hiddenList.length - 1; i >= 0; i--) { | |
132 | hiddenList[i].classList.remove("debugHide"); | |
133 | } | |
134 | } | |
135 | ||
edc3be71 | 136 | gAction.addEventListener("prefload-done", gMap.initGL, false); |
ecde0af2 | 137 | |
582d50fc RK |
138 | console.log("map vars set, loading prefs..."); |
139 | loadPrefs(); | |
140 | } | |
b395419b | 141 | |
582d50fc RK |
142 | function loadPrefs(aEvent) { |
143 | if (aEvent && aEvent.type == "prefs-step") { | |
144 | console.log("wait: " + gWaitCounter); | |
145 | if (gWaitCounter == 0) { | |
146 | gAction.removeEventListener(aEvent.type, loadPrefs, false); | |
147 | gMapPrefsLoaded = true; | |
148 | console.log("prefs loaded."); | |
149 | ||
150 | gTrackCanvas.addEventListener("mouseup", mapEvHandler, false); | |
151 | gTrackCanvas.addEventListener("mousemove", mapEvHandler, false); | |
152 | gTrackCanvas.addEventListener("mousedown", mapEvHandler, false); | |
153 | gTrackCanvas.addEventListener("mouseout", mapEvHandler, false); | |
154 | ||
155 | gTrackCanvas.addEventListener("touchstart", mapEvHandler, false); | |
156 | gTrackCanvas.addEventListener("touchmove", mapEvHandler, false); | |
157 | gTrackCanvas.addEventListener("touchend", mapEvHandler, false); | |
158 | gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false); | |
159 | gTrackCanvas.addEventListener("touchleave", mapEvHandler, false); | |
160 | ||
161 | gTrackCanvas.addEventListener("wheel", mapEvHandler, false); | |
162 | ||
163 | document.getElementById("body").addEventListener("keydown", mapEvHandler, false); | |
164 | ||
5dd2ab70 RK |
165 | document.addEventListener("visibilitychange", visibilityEvHandler, false); |
166 | ||
d7310ee2 | 167 | console.log("Events added."); |
582d50fc | 168 | |
decacd7f | 169 | console.log("Init loading tile..."); |
582d50fc | 170 | gLoadingTile = new Image(); |
582d50fc | 171 | gLoadingTile.onload = function() { |
decacd7f | 172 | console.log("Loading tile loaded."); |
ecde0af2 | 173 | var throwEv = new CustomEvent("prefload-done"); |
582d50fc RK |
174 | gAction.dispatchEvent(throwEv); |
175 | }; | |
decacd7f RK |
176 | console.log("Set loading tile..."); |
177 | gLoadingTile.src = "style/loading.png"; | |
582d50fc RK |
178 | } |
179 | } | |
180 | else { | |
181 | if (aEvent) | |
182 | gAction.removeEventListener(aEvent.type, loadPrefs, false); | |
183 | gAction.addEventListener("prefs-step", loadPrefs, false); | |
184 | gWaitCounter++; | |
ae9e33a2 RK |
185 | gPrefs.get("active_map_style", function(aValue) { |
186 | if (aValue && gMapStyles[aValue]) { | |
187 | gMap.activeMap = aValue; | |
188 | } | |
33a97b69 RK |
189 | else { |
190 | gMap.activeMap = "osm_mapnik"; | |
191 | } | |
192 | document.getElementById("mapSelector").value = gMap.activeMap; | |
193 | document.getElementById("copyright").innerHTML = | |
194 | gMapStyles[gMap.activeMap].copyright; | |
ae9e33a2 RK |
195 | gWaitCounter--; |
196 | var throwEv = new CustomEvent("prefs-step"); | |
197 | gAction.dispatchEvent(throwEv); | |
198 | }); | |
199 | gWaitCounter++; | |
582d50fc | 200 | gPrefs.get("position", function(aValue) { |
ac6286bd | 201 | if (aValue && aValue.x && aValue.y && aValue.z) { |
dda55132 | 202 | gMap.pos = aValue; |
582d50fc | 203 | } |
df81068a RK |
204 | gWaitCounter--; |
205 | var throwEv = new CustomEvent("prefs-step"); | |
206 | gAction.dispatchEvent(throwEv); | |
582d50fc RK |
207 | }); |
208 | gWaitCounter++; | |
209 | gPrefs.get("center_map", function(aValue) { | |
ae9e33a2 | 210 | if (aValue === undefined) { |
582d50fc | 211 | document.getElementById("centerCheckbox").checked = true; |
ae9e33a2 RK |
212 | } |
213 | else { | |
582d50fc | 214 | document.getElementById("centerCheckbox").checked = aValue; |
ae9e33a2 | 215 | } |
582d50fc RK |
216 | setCentering(document.getElementById("centerCheckbox")); |
217 | gWaitCounter--; | |
218 | var throwEv = new CustomEvent("prefs-step"); | |
219 | gAction.dispatchEvent(throwEv); | |
220 | }); | |
221 | gWaitCounter++; | |
222 | gPrefs.get("tracking_enabled", function(aValue) { | |
ae9e33a2 | 223 | if (aValue === undefined) { |
582d50fc | 224 | document.getElementById("trackCheckbox").checked = true; |
ae9e33a2 RK |
225 | } |
226 | else { | |
582d50fc | 227 | document.getElementById("trackCheckbox").checked = aValue; |
ae9e33a2 | 228 | } |
582d50fc RK |
229 | gWaitCounter--; |
230 | var throwEv = new CustomEvent("prefs-step"); | |
231 | gAction.dispatchEvent(throwEv); | |
232 | }); | |
233 | gWaitCounter++; | |
cef88e12 RK |
234 | var trackLoadStarted = false; |
235 | var redrawBase = 100; | |
6ddefbf9 RK |
236 | gTrackStore.getListStepped(function(aTPoint) { |
237 | if (aTPoint) { | |
238 | // Add in front and return new length. | |
239 | var tracklen = gTrack.unshift(aTPoint); | |
7a076538 RK |
240 | // Redraw track periodically, larger distance the longer it gets |
241 | // (but clamped to the first value over a certain limit). | |
fdaf08db RK |
242 | // Initial paint will do initial track drawing. |
243 | if (tracklen % redrawBase == 0) { | |
b4df67c9 | 244 | gTrackLayer.drawTrack(); // TODO: we could draw incremmentally if we would support reverse-direction drawing... |
7a076538 RK |
245 | if (redrawBase < 1000) { |
246 | redrawBase = tracklen; | |
247 | } | |
fdaf08db | 248 | } |
6ddefbf9 RK |
249 | } |
250 | else { | |
251 | // Last point received. | |
b4df67c9 | 252 | gTrackLayer.drawTrack(); // TODO: we could draw incremmentally if we would support reverse-direction drawing... |
6ddefbf9 RK |
253 | } |
254 | if (!trackLoadStarted) { | |
255 | // We have the most recent point, if present, rest will load async. | |
256 | trackLoadStarted = true; | |
257 | gWaitCounter--; | |
258 | var throwEv = new CustomEvent("prefs-step"); | |
259 | gAction.dispatchEvent(throwEv); | |
582d50fc | 260 | } |
582d50fc RK |
261 | }); |
262 | } | |
23cd2dcc RK |
263 | } |
264 | ||
edc3be71 RK |
265 | var gMap = { |
266 | gl: null, | |
267 | glShaderProgram: null, | |
268 | glVertexPositionAttr: null, | |
269 | glTextureCoordAttr: null, | |
270 | glResolutionAttr: null, | |
271 | glMapTexture: null, | |
e8525b46 | 272 | glTextures: {}, |
d6ff6891 RK |
273 | glTxCleanIntervalID: null, |
274 | glTexturesPerZoomLevel: 0, | |
edc3be71 | 275 | |
dda55132 RK |
276 | activeMap: "osm_mapnik", |
277 | tileSize: 256, | |
278 | maxZoom: 18, // The minimum is 0. | |
279 | zoomFactor: null, | |
280 | pos: { | |
281 | x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18) | |
282 | y: 23670000.0, // The range is 0-67108864 (2^gMap.maxZoom * gMap.tileSize) | |
283 | z: 5 // This could be fractional if supported being between zoom levels. | |
284 | }, | |
d6ff6891 RK |
285 | baseDim: { // Map width, height and tile size in level 18 pixels. |
286 | wid: null, | |
287 | ht: null, | |
288 | tsize: null, | |
289 | }, | |
aa45a91b | 290 | glDrawRequested: false, // To avoid parallel calls to drawGL(). |
dda55132 | 291 | |
ac6286bd RK |
292 | get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; }, |
293 | get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; }, | |
294 | ||
edc3be71 RK |
295 | getVertShaderSource: function() { |
296 | return 'attribute vec2 aVertexPosition;\n' + | |
297 | 'attribute vec2 aTextureCoord;\n\n' + | |
298 | 'uniform vec2 uResolution;\n\n' + | |
299 | 'varying highp vec2 vTextureCoord;\n\n' + | |
300 | 'void main(void) {\n' + | |
301 | // convert the rectangle from pixels to -1.0 to +1.0 (clipspace) 0.0 to 1.0 | |
302 | ' vec2 clipSpace = aVertexPosition * 2.0 / uResolution - 1.0;\n' + | |
303 | ' gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' + | |
304 | ' vTextureCoord = aTextureCoord;\n' + | |
305 | '}'; }, | |
d7310ee2 | 306 | getFragShaderSource: function() { |
edc3be71 RK |
307 | return 'varying highp vec2 vTextureCoord;\n\n' + |
308 | 'uniform sampler2D uImage;\n\n' + | |
309 | 'void main(void) {\n' + | |
310 | ' gl_FragColor = texture2D(uImage, vTextureCoord);\n' + | |
311 | '}'; }, | |
312 | ||
313 | initGL: function() { | |
314 | // When called from the event listener, the "this" reference doesn't work, so use the object name. | |
b3a9fc52 | 315 | console.log("Initializing WebGL..."); |
edc3be71 RK |
316 | if (gMap.gl) { |
317 | gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight); | |
318 | gMap.gl.clearColor(0.0, 0.0, 0.0, 0.5); // Set clear color to black, fully opaque. | |
319 | gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT|gMap.gl.DEPTH_BUFFER_BIT); // Clear the color. | |
320 | ||
321 | // Create and initialize the shaders. | |
b3a9fc52 | 322 | console.log("Create and compile shaders..."); |
edc3be71 RK |
323 | var vertShader = gMap.gl.createShader(gMap.gl.VERTEX_SHADER); |
324 | var fragShader = gMap.gl.createShader(gMap.gl.FRAGMENT_SHADER); | |
325 | gMap.gl.shaderSource(vertShader, gMap.getVertShaderSource()); | |
326 | // Compile the shader program. | |
327 | gMap.gl.compileShader(vertShader); | |
328 | // See if it compiled successfully. | |
329 | if (!gMap.gl.getShaderParameter(vertShader, gMap.gl.COMPILE_STATUS)) { | |
330 | console.log("An error occurred compiling the vertex shader: " + gMap.gl.getShaderInfoLog(vertShader)); | |
331 | return null; | |
332 | } | |
333 | gMap.gl.shaderSource(fragShader, gMap.getFragShaderSource()); | |
334 | // Compile the shader program. | |
335 | gMap.gl.compileShader(fragShader); | |
336 | // See if it compiled successfully. | |
337 | if (!gMap.gl.getShaderParameter(fragShader, gMap.gl.COMPILE_STATUS)) { | |
338 | console.log("An error occurred compiling the fragment shader: " + gMap.gl.getShaderInfoLog(fragShader)); | |
339 | return null; | |
340 | } | |
ecde0af2 | 341 | |
b3a9fc52 | 342 | console.log("Create and link shader program..."); |
edc3be71 RK |
343 | gMap.glShaderProgram = gMap.gl.createProgram(); |
344 | gMap.gl.attachShader(gMap.glShaderProgram, vertShader); | |
345 | gMap.gl.attachShader(gMap.glShaderProgram, fragShader); | |
346 | gMap.gl.linkProgram(gMap.glShaderProgram); | |
347 | // If creating the shader program failed, alert | |
348 | if (!gMap.gl.getProgramParameter(gMap.glShaderProgram, gMap.gl.LINK_STATUS)) { | |
349 | alert("Unable to initialize the shader program."); | |
350 | } | |
351 | gMap.gl.useProgram(gMap.glShaderProgram); | |
352 | // Get locations of the attributes. | |
353 | gMap.glVertexPositionAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aVertexPosition"); | |
354 | gMap.glTextureCoordAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aTextureCoord"); | |
355 | gMap.glResolutionAttr = gMap.gl.getUniformLocation(gMap.glShaderProgram, "uResolution"); | |
356 | ||
b3a9fc52 | 357 | console.log("Set up vertex buffer..."); |
edc3be71 RK |
358 | var tileVerticesBuffer = gMap.gl.createBuffer(); |
359 | gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, tileVerticesBuffer); | |
360 | // The vertices are the coordinates of the corner points of the square. | |
361 | var vertices = [ | |
362 | 0.0, 0.0, | |
363 | 1.0, 0.0, | |
364 | 0.0, 1.0, | |
365 | 0.0, 1.0, | |
366 | 1.0, 0.0, | |
367 | 1.0, 1.0, | |
368 | ]; | |
369 | gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(vertices), gMap.gl.STATIC_DRAW); | |
370 | gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr); | |
371 | gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0); | |
372 | ||
dc047338 | 373 | gMap.loadImageToTexture(gLoadingTile, getTileKey("loading", {x: 0, y: 0, z: 0})); |
edc3be71 RK |
374 | |
375 | gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height); | |
376 | ||
377 | // Create a buffer for the position of the rectangle corners. | |
b3a9fc52 | 378 | console.log("Set up coord buffer..."); |
edc3be71 RK |
379 | var mapVerticesTextureCoordBuffer = gMap.gl.createBuffer(); |
380 | gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer); | |
381 | gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr); | |
382 | gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0); | |
d6ff6891 RK |
383 | |
384 | // Call texture cleaning every 30 seconds, for now (is 60 better?). | |
385 | gMap.glTxCleanIntervalID = window.setInterval(gMap.cleanTextures, 30 * 1000); | |
ecde0af2 | 386 | } |
edc3be71 | 387 | |
16e4f664 RK |
388 | if (!gAppInitDone) { |
389 | // We may be called when context was lost and destroyed, | |
390 | // only send event when we are in app startup | |
391 | // (gAppInitDone is set to true right after we return this event). | |
392 | var throwEv = new CustomEvent("mapinit-done"); | |
393 | gAction.dispatchEvent(throwEv); | |
394 | } | |
edc3be71 RK |
395 | }, |
396 | ||
0f6678fa RK |
397 | draw: function() { |
398 | gMap.assembleGL(); | |
aa45a91b | 399 | gTrackLayer.drawTrack(); |
dda55132 | 400 | }, |
ecde0af2 | 401 | |
0f6678fa | 402 | assembleGL: function() { |
dda55132 | 403 | if (!gMap.gl) { return; } |
dda55132 RK |
404 | |
405 | document.getElementById("zoomLevel").textContent = gMap.pos.z; | |
406 | gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z); | |
d6ff6891 RK |
407 | gMap.baseDim.wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor; |
408 | gMap.baseDim.ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor; | |
409 | gMap.baseDim.tsize = gMap.tileSize * gMap.zoomFactor; | |
dda55132 | 410 | |
d6ff6891 RK |
411 | var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels. |
412 | var yMin = gMap.pos.y - gMap.baseDim.ht / 2; | |
413 | var xMax = gMap.pos.x + gMap.baseDim.wid / 2; | |
414 | var yMax = gMap.pos.y + gMap.baseDim.ht / 2; | |
dda55132 RK |
415 | |
416 | if (gMapPrefsLoaded && mainDB) | |
417 | gPrefs.set("position", gMap.pos); | |
418 | ||
dda55132 | 419 | // Go through all the tiles in the map, find out if to draw them and do so. |
d6ff6891 RK |
420 | for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) { |
421 | for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) { | |
0f6678fa RK |
422 | // Only go to loading step if we haven't loaded the texture. |
423 | var coords = {x: x, y: y, z: gMap.pos.z}; | |
424 | var tileKey = getTileKey(gMap.activeMap, normalizeCoords(coords)); | |
dc047338 | 425 | if (!gMap.glTextures[tileKey]) { |
dda55132 | 426 | // Initiate loading/drawing of the actual tile. |
0f6678fa | 427 | gTileService.get(gMap.activeMap, coords, |
b9707ee0 | 428 | function(aImage, aStyle, aCoords, aTileKey) { |
0f6678fa | 429 | // Only actually load if this still applies for the current view. |
dda55132 | 430 | if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) { |
0f6678fa RK |
431 | var URL = window.URL; |
432 | var imgURL = URL.createObjectURL(aImage); | |
433 | var imgObj = new Image(); | |
434 | imgObj.onload = function() { | |
dc047338 | 435 | gMap.loadImageToTexture(imgObj, aTileKey); |
aa45a91b | 436 | gMap.requestDrawGL(); |
0f6678fa | 437 | URL.revokeObjectURL(imgURL); |
dda55132 | 438 | } |
0f6678fa | 439 | imgObj.src = imgURL; |
dda55132 RK |
440 | } |
441 | }); | |
dda55132 RK |
442 | } |
443 | } | |
444 | } | |
aa45a91b RK |
445 | gMap.requestDrawGL(); |
446 | }, | |
447 | ||
448 | requestDrawGL: function() { | |
449 | // Only draw if we're actually visible. | |
450 | // Also, avoid running this multiple times when it could not complete yet. | |
451 | if (document.hidden != true && !gMap.glDrawRequested) { | |
452 | gMap.glDrawRequested = true; | |
453 | window.requestAnimationFrame(gMap.drawGL); | |
5dd2ab70 | 454 | } |
b9707ee0 RK |
455 | }, |
456 | ||
aa45a91b | 457 | drawGL: function(aTimestamp) { |
d6ff6891 RK |
458 | var xMin = gMap.pos.x - gMap.baseDim.wid / 2; // Corners of the window in level 18 pixels. |
459 | var yMin = gMap.pos.y - gMap.baseDim.ht / 2; | |
460 | var xMax = gMap.pos.x + gMap.baseDim.wid / 2; | |
461 | var yMax = gMap.pos.y + gMap.baseDim.ht / 2; | |
b9707ee0 | 462 | |
b9707ee0 | 463 | // Go through all the tiles in the map, find out if to draw them and do so. |
d6ff6891 RK |
464 | for (var x = Math.floor(xMin / gMap.baseDim.tsize); x < Math.ceil(xMax / gMap.baseDim.tsize); x++) { |
465 | for (var y = Math.floor(yMin / gMap.baseDim.tsize); y < Math.ceil(yMax / gMap.baseDim.tsize); y++) { | |
466 | // Rounding the pixel offsets ensures we position the tiles precisely. | |
467 | var xoff = Math.round((x * gMap.baseDim.tsize - xMin) / gMap.zoomFactor); | |
468 | var yoff = Math.round((y * gMap.baseDim.tsize - yMin) / gMap.zoomFactor); | |
dc047338 | 469 | // Draw the tile, first find out the actual texture to use. |
b9707ee0 RK |
470 | var norm = normalizeCoords({x: x, y: y, z: gMap.pos.z}); |
471 | var tileKey = getTileKey(gMap.activeMap, norm); | |
dc047338 RK |
472 | if (!gMap.glTextures[tileKey]) { |
473 | tileKey = getTileKey("loading", {x: 0, y: 0, z: 0}); | |
474 | } | |
475 | gMap.drawTileGL(xoff, yoff, tileKey); | |
b9707ee0 RK |
476 | } |
477 | } | |
aa45a91b | 478 | gMap.glDrawRequested = false; |
dda55132 | 479 | }, |
edc3be71 | 480 | |
ac6286bd RK |
481 | resizeAndDraw: function() { |
482 | var viewportWidth = Math.min(window.innerWidth, window.outerWidth); | |
483 | var viewportHeight = Math.min(window.innerHeight, window.outerHeight); | |
484 | if (gGLMapCanvas && gTrackCanvas) { | |
485 | gGLMapCanvas.width = viewportWidth; | |
486 | gGLMapCanvas.height = viewportHeight; | |
487 | gTrackCanvas.width = viewportWidth; | |
488 | gTrackCanvas.height = viewportHeight; | |
489 | if (gMap.gl) { | |
490 | // Size viewport to canvas size. | |
491 | gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight); | |
492 | // Clear the color. | |
493 | gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT); | |
494 | // Make sure the vertex shader get the right resolution. | |
495 | gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height); | |
d6ff6891 RK |
496 | // Prepare recalculation of textures to keep for one zoom level. |
497 | gMap.glTexturesPerZoomLevel = 0; | |
ac6286bd RK |
498 | } |
499 | gMap.draw(); | |
500 | showUI(); | |
501 | } | |
dda55132 RK |
502 | }, |
503 | ||
dc047338 | 504 | drawTileGL: function(aLeft, aRight, aTileKey) { |
b9707ee0 | 505 | gMap.gl.activeTexture(gMap.gl.TEXTURE0); |
dc047338 | 506 | gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]); |
b9707ee0 RK |
507 | // Set uImage to refer to TEXTURE0 |
508 | gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0); | |
dda55132 RK |
509 | var x_start = aLeft; |
510 | var i_width = gMap.tileSize; | |
511 | var y_start = aRight; | |
512 | var i_height = gMap.tileSize; | |
edc3be71 RK |
513 | var textureCoordinates = [ |
514 | x_start, y_start, | |
515 | x_start + i_width, y_start, | |
516 | x_start, y_start + i_height, | |
517 | x_start, y_start + i_height, | |
518 | x_start + i_width, y_start, | |
519 | x_start + i_width, y_start + i_height, | |
520 | ]; | |
521 | gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW); | |
edc3be71 RK |
522 | |
523 | // There are 6 indices in textureCoordinates. | |
524 | gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6); | |
e8525b46 RK |
525 | }, |
526 | ||
dc047338 | 527 | loadImageToTexture: function(aImage, aTileKey) { |
e8525b46 | 528 | // Create and bind texture. |
dc047338 RK |
529 | gMap.glTextures[aTileKey] = gMap.gl.createTexture(); |
530 | gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTileKey]); | |
e8525b46 RK |
531 | // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two). |
532 | gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST); | |
533 | gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST); | |
534 | // Upload the image into the texture. | |
535 | gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage); | |
536 | }, | |
d6ff6891 RK |
537 | |
538 | cleanTextures: function() { | |
539 | // Get rid of unneeded textures to save memory. | |
540 | // TODO: Be less aggressive, maybe keep neighboring zoom levels (but x/y coords there are zoom-specific). | |
541 | if (!gMap.glTexturesPerZoomLevel) { | |
542 | // Calculate how many textures we need to keep for one zoom level. | |
543 | // ceil(width/size) gives us the minimum, keep one on either side as well. | |
544 | gMap.glTexturesPerZoomLevel = | |
545 | Math.ceil(gMap.gl.drawingBufferWidth / gMap.tileSize + 2) * | |
546 | Math.ceil(gMap.gl.drawingBufferHeight / gMap.tileSize + 2); | |
547 | console.log("Keeping " + gMap.glTexturesPerZoomLevel + " textures per level"); | |
548 | } | |
549 | if (Object.keys(gMap.glTextures).length > gMap.glTexturesPerZoomLevel) { | |
550 | console.log("Cleaning textures... (have " + Object.keys(gMap.glTextures).length + " atm)"); | |
551 | ||
552 | // Find coordinate ranges for tiles to keep. | |
553 | var tMin = normalizeCoords({x: Math.floor((gMap.pos.x - gMap.baseDim.wid / 2) / gMap.baseDim.tsize) - 1, | |
554 | y: Math.floor((gMap.pos.y - gMap.baseDim.ht / 2) / gMap.baseDim.tsize) - 1, | |
555 | z: gMap.pos.z}); | |
556 | var tMax = normalizeCoords({x: Math.ceil((gMap.pos.x + gMap.baseDim.wid / 2) / gMap.baseDim.tsize) + 1, | |
557 | y: Math.ceil((gMap.pos.y + gMap.baseDim.ht / 2) / gMap.baseDim.tsize) + 1, | |
558 | z: gMap.pos.z}); | |
559 | console.log("In range: " + tMin.x + "," + tMin.y + "," + tMin.z + " - " + tMax.x + "," + tMax.y + "," + tMax.z); | |
bb752fc4 RK |
560 | for (var tileKey in gMap.glTextures) { |
561 | var keyMatches = tileKey.match(/([^:]+)::(\d+),(\d+),(\d+)/); | |
d6ff6891 RK |
562 | if (keyMatches && keyMatches[1] != "loading") { |
563 | var txData = { | |
564 | style: keyMatches[1], | |
565 | x: keyMatches[2], | |
566 | y: keyMatches[3], | |
567 | z: keyMatches[4], | |
568 | } | |
569 | var delTx = false; | |
570 | if (txData.style != gMap.activeMap) { delTx = true; console.log("Different map style: " + txData.style); } | |
571 | if (!delTx && (txData.z < tMin.z || txData.z > tMax.z)) { delTx = true; console.log("Out-of-range zoom: " + txData.z); } | |
572 | if (tMin.x < tMax.x) { | |
573 | if (!delTx && (txData.x < tMin.x || txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); } | |
574 | } | |
575 | else { | |
576 | // We are crossing over the 0 coordinate! | |
577 | if (!delTx && (txData.x < tMin.x && txData.x > tMax.x)) { delTx = true; console.log("Out-of-range X: " + txData.x); } | |
578 | } | |
579 | if (tMin.y < tMax.y) { | |
580 | if (!delTx && (txData.y < tMin.y || txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); } | |
581 | } | |
582 | else { | |
583 | // We are crossing over the 0 coordinate! | |
584 | if (!delTx && (txData.y < tMin.y && txData.y > tMax.y)) { delTx = true; console.log("Out-of-range Y: " + txData.y); } | |
585 | } | |
586 | if (delTx) { | |
587 | // Delete texture from GL and from the array we are holding. | |
bb752fc4 RK |
588 | gMap.gl.deleteTexture(gMap.glTextures[tileKey]); |
589 | delete gMap.glTextures[tileKey]; | |
d6ff6891 RK |
590 | } |
591 | } | |
592 | } | |
e4840ddc | 593 | console.log("Cleaning complete, " + Object.keys(gMap.glTextures).length + " textures left"); |
d6ff6891 RK |
594 | } |
595 | }, | |
16e4f664 | 596 | |
aa45a91b RK |
597 | // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming. |
598 | // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling | |
599 | ||
600 | zoomIn: function() { | |
601 | if (gMap.pos.z < gMap.maxZoom) { | |
602 | gMap.pos.z++; | |
603 | gMap.draw(); | |
604 | } | |
605 | }, | |
606 | ||
607 | zoomOut: function() { | |
608 | if (gMap.pos.z > 0) { | |
609 | gMap.pos.z--; | |
610 | gMap.draw(); | |
611 | } | |
612 | }, | |
613 | ||
614 | zoomTo: function(aTargetLevel) { | |
615 | aTargetLevel = parseInt(aTargetLevel); | |
616 | if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) { | |
617 | gMap.pos.z = aTargetLevel; | |
618 | gMap.draw(); | |
619 | } | |
620 | }, | |
621 | ||
622 | setActiveMap: function(aStyle) { | |
623 | gMap.activeMap = aStyle; | |
624 | gPrefs.set("active_map_style", gMap.activeMap); | |
625 | document.getElementById("copyright").innerHTML = | |
626 | gMapStyles[gMap.activeMap].copyright; | |
627 | if (!gWaitCounter) { // Only do this when prefs are loaded already. | |
628 | showUI(); | |
629 | gMap.draw(); | |
630 | } | |
631 | }, | |
632 | ||
16e4f664 RK |
633 | handleContextLost: function(event) { |
634 | event.preventDefault(); | |
635 | // GL context is gone, let's reset everything that depends on it. | |
636 | clearInterval(gMap.glTxCleanIntervalID); | |
637 | gMap.glTextures = {}; | |
638 | }, | |
639 | ||
640 | handleContextRestored: function(event) { | |
641 | // When GL context is back, init GL again and draw. | |
642 | gMap.initGL(); | |
643 | gMap.draw(); | |
644 | }, | |
ecde0af2 RK |
645 | } |
646 | ||
aa45a91b RK |
647 | var gTrackLayer = { |
648 | context: null, | |
649 | curPosMapCache: undefined, | |
650 | lastDrawnPoint: null, | |
b4df67c9 RK |
651 | lastRequestedIndex: null, // may not have been actually drawn... |
652 | drawRequested: false, | |
653 | restartDrawing: true, | |
68ca4617 | 654 | |
b4df67c9 | 655 | maxDrawTime: 10, // max time allowed for drawing a section, in ms - 10 means we can do 100 fps smoothly |
68ca4617 RK |
656 | trackWidth: 2, // pixels |
657 | trackColor: "#FF0000", | |
658 | curLocSize: 6, // pixels | |
659 | curLocColor: "#A00000", | |
aa45a91b | 660 | |
b4df67c9 RK |
661 | drawTrack: function(needRestart = true) { |
662 | // TODO: figure out if we can support reverse drawing while initially loading the track. | |
663 | // Only draw if we're actually visible. | |
664 | // Also, avoid running this multiple times when it could not complete yet. | |
665 | if (needRestart) { gTrackLayer.restartDrawing = true; } | |
666 | if (gTrackLayer.context && document.hidden != true && !gTrackLayer.drawRequested) { | |
667 | gTrackLayer.drawRequested = true; | |
668 | window.requestAnimationFrame(gTrackLayer.drawTrackSection); | |
669 | } | |
670 | }, | |
671 | ||
672 | drawTrackSection: function(aTimestamp) { | |
673 | var start = performance.now(); | |
674 | if (gTrackLayer.restartDrawing) { | |
675 | gTrackLayer.lastRequestedIndex = 0; | |
aa45a91b | 676 | gTrackLayer.lastDrawnPoint = null; |
b4df67c9 | 677 | gTrackLayer.restartDrawing = false; |
aa45a91b RK |
678 | gTrackLayer.curPosMapCache = undefined; |
679 | gTrackLayer.context.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height); | |
b4df67c9 RK |
680 | } |
681 | if (gTrack.length && (performance.now() < start + gTrackLayer.maxDrawTime)) { | |
682 | for (; gTrackLayer.lastRequestedIndex < gTrack.length; gTrackLayer.lastRequestedIndex++) { | |
683 | gTrackLayer.drawTrackPoint(gTrackLayer.lastRequestedIndex); | |
684 | if (performance.now() >= start + gTrackLayer.maxDrawTime) { | |
685 | // Break out of the loop if we are over the max allowed time, we'll continue in the next rAF (see below). | |
9292a1b7 | 686 | gTrackLayer.drawTrackPoint(null); |
b4df67c9 | 687 | break; |
aa45a91b RK |
688 | } |
689 | } | |
690 | } | |
b4df67c9 RK |
691 | // If we still have work to do and we're still visible, continue drawing. |
692 | if ((gTrackLayer.lastRequestedIndex + 1 < gTrack.length) && gTrackLayer.context && (document.hidden != true)) { | |
693 | window.requestAnimationFrame(gTrackLayer.drawTrackSection); | |
694 | } | |
695 | gTrackLayer.drawRequested = false; | |
aa45a91b | 696 | }, |
b5e49b95 | 697 | |
b4df67c9 RK |
698 | drawTrackPoint: function(aIndex) { |
699 | gTrackLayer.running = true; | |
9292a1b7 RK |
700 | if (!aIndex && aIndex !== 0) { |
701 | // We can be called this way to make sure we draw an actual line up to where we are right now. | |
702 | if (gTrackLayer.lastDrawnPoint && gTrackLayer.lastDrawnPoint.optimized) { | |
703 | gTrackLayer.context.stroke(); | |
704 | gTrackLayer.lastDrawnPoint.optimized = false; | |
705 | } | |
706 | return; | |
707 | } | |
b4df67c9 RK |
708 | var trackpoint = {"worldpos": gps2xy(gTrack[aIndex].coords.latitude, gTrack[aIndex].coords.longitude)}; |
709 | var isLastPoint = (aIndex + 1 >= gTrack.length || gTrack[aIndex+1].beginSegment); | |
aa45a91b RK |
710 | var update_drawnpoint = true; |
711 | // lastPoint is for optimizing (not actually executing the draw until the last) | |
b4df67c9 RK |
712 | trackpoint.segmentEnd = (isLastPoint === true); |
713 | trackpoint.optimized = (isLastPoint === false); | |
aa45a91b RK |
714 | trackpoint.mappos = {x: Math.round((trackpoint.worldpos.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2), |
715 | y: Math.round((trackpoint.worldpos.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)}; | |
716 | trackpoint.skip_drawing = false; | |
717 | if (gTrackLayer.lastDrawnPoint) { | |
718 | // Lines completely outside the current display should not be drawn. | |
719 | if ((trackpoint.mappos.x < 0 && gTrackLayer.lastDrawnPoint.mappos.x < 0) || | |
720 | (trackpoint.mappos.x > gMap.width && gTrackLayer.lastDrawnPoint.mappos.x > gMap.width) || | |
721 | (trackpoint.mappos.y < 0 && gTrackLayer.lastDrawnPoint.mappos.y < 0) || | |
722 | (trackpoint.mappos.y > gMap.height && gTrackLayer.lastDrawnPoint.mappos.y > gMap.height)) { | |
723 | trackpoint.skip_drawing = true; | |
724 | } | |
725 | } | |
726 | if (!gTrackLayer.lastDrawnPoint || !gTrackLayer.lastDrawnPoint.optimized) { | |
68ca4617 | 727 | gTrackLayer.context.strokeStyle = gTrackLayer.trackColor; |
aa45a91b | 728 | gTrackLayer.context.fillStyle = gTrackLayer.context.strokeStyle; |
68ca4617 | 729 | gTrackLayer.context.lineWidth = gTrackLayer.trackWidth; |
aa45a91b RK |
730 | gTrackLayer.context.lineCap = "round"; |
731 | gTrackLayer.context.lineJoin = "round"; | |
732 | } | |
733 | // This breaks optimiziation, so make sure to reset optimization. | |
734 | if (trackpoint.skip_drawing || !gTrackLayer.lastDrawnPoint) { | |
735 | trackpoint.optimized = false; | |
736 | // Close path if one was open. | |
737 | if (gTrackLayer.lastDrawnPoint && gTrackLayer.lastDrawnPoint.optimized) { | |
738 | gTrackLayer.context.stroke(); | |
739 | } | |
740 | } | |
741 | if (!trackpoint.skip_drawing) { | |
742 | if (gTrackLayer.lastDrawnPoint && gTrackLayer.lastDrawnPoint.skip_drawing && !gTrackLayer.lastDrawnPoint.segmentEnd) { | |
743 | // If the last point was skipped but the current one isn't, draw a segment start | |
744 | // for the off-screen previous one as well as a connection line. | |
745 | gTrackLayer.context.beginPath(); | |
746 | gTrackLayer.context.arc(gTrackLayer.lastDrawnPoint.mappos.x, gTrackLayer.lastDrawnPoint.mappos.y, | |
747 | gTrackLayer.context.lineWidth, 0, Math.PI * 2, false); | |
748 | gTrackLayer.context.fill(); | |
749 | gTrackLayer.context.lineTo(trackpoint.mappos.x, trackpoint.mappos.y); | |
750 | } | |
751 | else if (!gTrackLayer.lastDrawnPoint || !gTrackLayer.lastDrawnPoint.optimized) { | |
752 | // Start drawing a segment with the current point. | |
753 | gTrackLayer.context.beginPath(); | |
754 | gTrackLayer.context.arc(trackpoint.mappos.x, trackpoint.mappos.y, | |
755 | gTrackLayer.context.lineWidth, 0, Math.PI * 2, false); | |
756 | gTrackLayer.context.fill(); | |
757 | } | |
758 | else if (!trackpoint.segmentEnd && gTrackLayer.lastDrawnPoint && | |
759 | (Math.abs(gTrackLayer.lastDrawnPoint.mappos.x - trackpoint.mappos.x) <= 1) && | |
760 | (Math.abs(gTrackLayer.lastDrawnPoint.mappos.y - trackpoint.mappos.y) <= 1)) { | |
761 | // We would draw the same or almost the same point, don't do any actual drawing. | |
762 | update_drawnpoint = false; | |
763 | } | |
764 | else { | |
765 | // Continue drawing segment, close if needed. | |
766 | gTrackLayer.context.lineTo(trackpoint.mappos.x, trackpoint.mappos.y); | |
767 | if (!trackpoint.optimized) | |
768 | gTrackLayer.context.stroke(); | |
769 | } | |
770 | } | |
771 | if (update_drawnpoint) { | |
772 | gTrackLayer.lastDrawnPoint = trackpoint; | |
773 | } | |
774 | }, | |
23cd2dcc | 775 | |
aa45a91b | 776 | drawCurrentLocation: function(trackPoint) { |
b4df67c9 RK |
777 | // Only run this when visible and we are not drawing a track right now. |
778 | if (gTrackLayer.context && document.hidden != true && !gTrackLayer.drawRequested) { | |
779 | var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude); | |
68ca4617 | 780 | var circleRadius = Math.round(gTrackLayer.curLocSize / 2); |
b4df67c9 RK |
781 | var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2), |
782 | y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)}; | |
783 | ||
784 | gTrackLayer.undrawCurrentLocation(); | |
785 | ||
786 | // Cache overdrawn area. | |
787 | gTrackLayer.curPosMapCache = | |
788 | {point: locpoint, | |
789 | radius: circleRadius, | |
790 | data: gTrackLayer.context.getImageData(mappos.x - circleRadius, | |
791 | mappos.y - circleRadius, | |
792 | circleRadius * 2, circleRadius * 2)}; | |
793 | ||
68ca4617 | 794 | gTrackLayer.context.strokeStyle = gTrackLayer.curLocColor; |
b4df67c9 RK |
795 | gTrackLayer.context.fillStyle = gTrackLayer.context.strokeStyle; |
796 | gTrackLayer.context.beginPath(); | |
797 | gTrackLayer.context.arc(mappos.x, mappos.y, | |
798 | circleRadius, 0, Math.PI * 2, false); | |
799 | gTrackLayer.context.fill(); | |
800 | } | |
aa45a91b | 801 | }, |
23cd2dcc | 802 | |
aa45a91b | 803 | undrawCurrentLocation: function() { |
b4df67c9 RK |
804 | // Only run this when visible and we are not drawing a track right now. |
805 | if (gTrackLayer.context && document.hidden != true && !gTrackLayer.drawRequested) { | |
806 | if (gTrackLayer.curPosMapCache) { | |
807 | var oldpoint = gTrackLayer.curPosMapCache.point; | |
808 | var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2), | |
809 | y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)}; | |
810 | gTrackLayer.context.putImageData(gTrackLayer.curPosMapCache.data, | |
811 | oldmp.x - gTrackLayer.curPosMapCache.radius, | |
812 | oldmp.y - gTrackLayer.curPosMapCache.radius); | |
813 | gTrackLayer.curPosMapCache = undefined; | |
814 | } | |
aa45a91b | 815 | } |
1222624d RK |
816 | } |
817 | } | |
818 | ||
55c4a0b7 | 819 | function gps2xy(aLatitude, aLongitude) { |
dda55132 | 820 | var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize; |
55c4a0b7 RK |
821 | var convLat = aLatitude * Math.PI / 180; |
822 | var rawY = (1 - Math.log(Math.tan(convLat) + | |
823 | 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor; | |
824 | var rawX = (aLongitude + 180) / 360 * maxZoomFactor; | |
825 | return {x: Math.round(rawX), | |
826 | y: Math.round(rawY)}; | |
827 | } | |
828 | ||
829 | function xy2gps(aX, aY) { | |
dda55132 | 830 | var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize; |
55c4a0b7 RK |
831 | var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor; |
832 | return {latitude: 180 / Math.PI * | |
833 | Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))), | |
834 | longitude: aX / maxZoomFactor * 360 - 180}; | |
835 | } | |
836 | ||
23cd2dcc RK |
837 | // A sane mod function that works for negative numbers. |
838 | // Returns a % b. | |
839 | function mod(a, b) { | |
840 | return ((a % b) + b) % b; | |
841 | } | |
842 | ||
a8634d37 RK |
843 | function normalizeCoords(aCoords) { |
844 | var zoomFactor = Math.pow(2, aCoords.z); | |
845 | return {x: mod(aCoords.x, zoomFactor), | |
846 | y: mod(aCoords.y, zoomFactor), | |
847 | z: aCoords.z}; | |
23cd2dcc RK |
848 | } |
849 | ||
b9707ee0 RK |
850 | function getTileKey(aStyle, aNormalizedCoords) { |
851 | return aStyle + "::" + | |
852 | aNormalizedCoords.x + "," + | |
853 | aNormalizedCoords.y + "," + | |
854 | aNormalizedCoords.z; | |
855 | } | |
856 | ||
23cd2dcc RK |
857 | // Returns true if the tile is outside the current view. |
858 | function isOutsideWindow(t) { | |
859 | var pos = decodeIndex(t); | |
23cd2dcc | 860 | |
dda55132 | 861 | var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z); |
ac6286bd RK |
862 | var wid = gMap.width * zoomFactor; |
863 | var ht = gMap.height * zoomFactor; | |
23cd2dcc | 864 | |
4b1d0915 RK |
865 | pos.x *= zoomFactor; |
866 | pos.y *= zoomFactor; | |
23cd2dcc | 867 | |
dda55132 RK |
868 | var sz = gMap.tileSize * zoomFactor; |
869 | if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 || | |
870 | pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2) | |
23cd2dcc RK |
871 | return true; |
872 | return false; | |
873 | } | |
874 | ||
875 | function encodeIndex(x, y, z) { | |
a8634d37 | 876 | var norm = normalizeCoords({x: x, y: y, z: z}); |
23cd2dcc RK |
877 | return norm.x + "," + norm.y + "," + norm.z; |
878 | } | |
879 | ||
880 | function decodeIndex(encodedIdx) { | |
4b1d0915 RK |
881 | var ind = encodedIdx.split(",", 3); |
882 | return {x: ind[0], y: ind[1], z: ind[2]}; | |
23cd2dcc RK |
883 | } |
884 | ||
7a076538 RK |
885 | function calcTrackDuration() { |
886 | // Get the duration of the track in s. | |
887 | var tDuration = 0; | |
888 | if (gTrack.length > 1) { | |
889 | for (var i = 1; i < gTrack.length; i++) { | |
8f63227b RK |
890 | if (!gTrack[i].beginSegment) { |
891 | tDuration += (gTrack[i].time - gTrack[i-1].time); | |
892 | } | |
7a076538 RK |
893 | } |
894 | } | |
895 | return Math.round(tDuration / 1000); // The timestamps are in ms but we return seconds. | |
896 | } | |
897 | ||
898 | function calcTrackLength() { | |
899 | // Get the length of the track in km. | |
900 | var tLength = 0; | |
901 | if (gTrack.length > 1) { | |
902 | for (var i = 1; i < gTrack.length; i++) { | |
8f63227b RK |
903 | if (!gTrack[i].beginSegment) { |
904 | tLength += getPointDistance(gTrack[i-1].coords, gTrack[i].coords); | |
905 | } | |
7a076538 RK |
906 | } |
907 | } | |
908 | return tLength; | |
909 | } | |
910 | ||
911 | function getPointDistance(aGPSPoint1, aGPSPoint2) { | |
912 | // Get the distance in km between the two given GPS points. | |
913 | // See http://stackoverflow.com/questions/365826/calculate-distance-between-2-gps-coordinates | |
914 | // Earth is almost exactly a sphere and we calculate small distances on the surface, so we can do spherical great-circle math. | |
915 | // Also see http://en.wikipedia.org/wiki/Great-circle_distance | |
916 | var R = 6371; // km | |
917 | var dLat = deg2rad(aGPSPoint2.latitude - aGPSPoint1.latitude); | |
918 | var dLon = deg2rad(aGPSPoint2.longitude - aGPSPoint1.longitude); | |
919 | var lat1 = deg2rad(aGPSPoint1.latitude); | |
920 | var lat2 = deg2rad(aGPSPoint2.latitude); | |
921 | ||
922 | var a = Math.sin(dLat/2) * Math.sin(dLat/2) + | |
923 | Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); | |
924 | var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); | |
925 | return R * c; | |
926 | } | |
927 | ||
928 | function deg2rad(aDegreeValue) { | |
929 | // Convert an angle in degrees to radiants. | |
930 | return aDegreeValue * (Math.PI / 180); | |
931 | } | |
932 | ||
23cd2dcc RK |
933 | var mapEvHandler = { |
934 | handleEvent: function(aEvent) { | |
935 | var touchEvent = aEvent.type.indexOf('touch') != -1; | |
936 | ||
306ae634 RK |
937 | if (touchEvent) { |
938 | aEvent.stopPropagation(); | |
939 | } | |
940 | ||
8389557a RK |
941 | // Bail out if the event is happening on an input. |
942 | if (aEvent.target.tagName.toLowerCase() == "input") | |
943 | return; | |
944 | ||
1222624d RK |
945 | // Bail out on unwanted map moves, but not zoom or keyboard events. |
946 | if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) { | |
23cd2dcc RK |
947 | // Bail out if this is neither a touch nor left-click. |
948 | if (!touchEvent && aEvent.button != 0) | |
949 | return; | |
950 | ||
951 | // Bail out if the started touch can't be found. | |
4b12da3a | 952 | if (touchEvent && gDragging && |
aec007a6 | 953 | !aEvent.targetTouches.item(0)) |
23cd2dcc RK |
954 | return; |
955 | } | |
956 | ||
957 | var coordObj = touchEvent ? | |
aec007a6 | 958 | aEvent.targetTouches.item(0) : |
23cd2dcc RK |
959 | aEvent; |
960 | ||
961 | switch (aEvent.type) { | |
962 | case "mousedown": | |
963 | case "touchstart": | |
964 | if (touchEvent) { | |
517c0099 RK |
965 | if (aEvent.targetTouches.length == 2) { |
966 | gPinchStartWidth = Math.sqrt( | |
967 | Math.pow(aEvent.targetTouches.item(1).clientX - | |
968 | aEvent.targetTouches.item(0).clientX, 2) + | |
969 | Math.pow(aEvent.targetTouches.item(1).clientY - | |
970 | aEvent.targetTouches.item(0).clientY, 2) | |
971 | ); | |
972 | } | |
aec007a6 | 973 | coordObj = aEvent.targetTouches.item(0); |
23cd2dcc | 974 | } |
ac6286bd RK |
975 | var x = coordObj.clientX - gGLMapCanvas.offsetLeft; |
976 | var y = coordObj.clientY - gGLMapCanvas.offsetTop; | |
b395419b | 977 | |
23cd2dcc RK |
978 | if (touchEvent || aEvent.button === 0) { |
979 | gDragging = true; | |
980 | } | |
981 | gLastMouseX = x; | |
982 | gLastMouseY = y; | |
7a549148 | 983 | showUI(); |
68ca4617 | 984 | gLastMoveAction = performance.now(); |
23cd2dcc RK |
985 | break; |
986 | case "mousemove": | |
987 | case "touchmove": | |
517c0099 RK |
988 | if (touchEvent && aEvent.targetTouches.length == 2) { |
989 | curPinchStartWidth = Math.sqrt( | |
990 | Math.pow(aEvent.targetTouches.item(1).clientX - | |
991 | aEvent.targetTouches.item(0).clientX, 2) + | |
992 | Math.pow(aEvent.targetTouches.item(1).clientY - | |
993 | aEvent.targetTouches.item(0).clientY, 2) | |
994 | ); | |
003d56f8 RK |
995 | if (!gPinchStartWidth) |
996 | gPinchStartWidth = curPinchStartWidth; | |
d07d7abc | 997 | |
517c0099 RK |
998 | if (gPinchStartWidth / curPinchStartWidth > 1.7 || |
999 | gPinchStartWidth / curPinchStartWidth < 0.6) { | |
dda55132 RK |
1000 | var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1); |
1001 | if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) { | |
517c0099 RK |
1002 | // Calculate new center of the map - preserve middle of pinch. |
1003 | // This means that pixel distance between old center and middle | |
1004 | // must equal pixel distance of new center and middle. | |
1005 | var x = (aEvent.targetTouches.item(1).clientX + | |
1006 | aEvent.targetTouches.item(0).clientX) / 2 - | |
ac6286bd | 1007 | gGLMapCanvas.offsetLeft; |
517c0099 RK |
1008 | var y = (aEvent.targetTouches.item(1).clientY + |
1009 | aEvent.targetTouches.item(0).clientY) / 2 - | |
ac6286bd | 1010 | gGLMapCanvas.offsetTop; |
517c0099 RK |
1011 | |
1012 | // Zoom factor after this action. | |
dda55132 | 1013 | var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel); |
ac6286bd RK |
1014 | gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor); |
1015 | gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor); | |
517c0099 RK |
1016 | |
1017 | if (gPinchStartWidth < curPinchStartWidth) | |
aa45a91b | 1018 | gMap.zoomIn(); |
517c0099 | 1019 | else |
aa45a91b | 1020 | gMap.zoomOut(); |
003d56f8 RK |
1021 | |
1022 | // Reset pinch start width and start another pinch gesture. | |
1023 | gPinchStartWidth = null; | |
517c0099 RK |
1024 | } |
1025 | } | |
d07d7abc | 1026 | // If we are in a pinch, do not drag. |
517c0099 RK |
1027 | break; |
1028 | } | |
ac6286bd RK |
1029 | var x = coordObj.clientX - gGLMapCanvas.offsetLeft; |
1030 | var y = coordObj.clientY - gGLMapCanvas.offsetTop; | |
23cd2dcc RK |
1031 | if (gDragging === true) { |
1032 | var dX = x - gLastMouseX; | |
1033 | var dY = y - gLastMouseY; | |
dda55132 RK |
1034 | gMap.pos.x -= dX * gMap.zoomFactor; |
1035 | gMap.pos.y -= dY * gMap.zoomFactor; | |
0f6678fa | 1036 | gMap.draw(); |
7a549148 | 1037 | showUI(); |
23cd2dcc RK |
1038 | } |
1039 | gLastMouseX = x; | |
1040 | gLastMouseY = y; | |
68ca4617 | 1041 | gLastMoveAction = performance.now(); |
23cd2dcc RK |
1042 | break; |
1043 | case "mouseup": | |
1044 | case "touchend": | |
d07d7abc | 1045 | gPinchStartWidth = null; |
23cd2dcc | 1046 | gDragging = false; |
7a549148 | 1047 | showUI(); |
23cd2dcc RK |
1048 | break; |
1049 | case "mouseout": | |
1050 | case "touchcancel": | |
1051 | case "touchleave": | |
1052 | //gDragging = false; | |
1053 | break; | |
5fb31b29 RK |
1054 | case "wheel": |
1055 | // If we'd want pixels, we'd need to calc up using aEvent.deltaMode. | |
1056 | // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel | |
1057 | ||
1058 | // Only accept (non-null) deltaY values | |
1059 | if (!aEvent.deltaY) | |
1060 | break; | |
23cd2dcc | 1061 | |
55c4a0b7 RK |
1062 | // Debug output: "coordinates" of the point the mouse was over. |
1063 | /* | |
ac6286bd RK |
1064 | var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor, |
1065 | y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor}; | |
55c4a0b7 RK |
1066 | var gpsCoord = xy2gps(ptCoord.x, ptCoord.y); |
1067 | var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude); | |
915d4271 RK |
1068 | console.log(ptCoord.x + "/" + ptCoord.y + " - " + |
1069 | gpsCoord.latitude + "/" + gpsCoord.longitude + " - " + | |
1070 | pt2Coord.x + "/" + pt2Coord.y); | |
55c4a0b7 | 1071 | */ |
4b1d0915 | 1072 | |
dda55132 RK |
1073 | var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1); |
1074 | if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) { | |
4b1d0915 RK |
1075 | // Calculate new center of the map - same point stays under the mouse. |
1076 | // This means that the pixel distance between the old center and point | |
1077 | // must equal the pixel distance of the new center and that point. | |
ac6286bd RK |
1078 | var x = coordObj.clientX - gGLMapCanvas.offsetLeft; |
1079 | var y = coordObj.clientY - gGLMapCanvas.offsetTop; | |
4b1d0915 RK |
1080 | |
1081 | // Zoom factor after this action. | |
dda55132 | 1082 | var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel); |
ac6286bd RK |
1083 | gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor); |
1084 | gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor); | |
4b1d0915 | 1085 | |
5fb31b29 | 1086 | if (aEvent.deltaY < 0) |
aa45a91b | 1087 | gMap.zoomIn(); |
5fb31b29 | 1088 | else |
aa45a91b | 1089 | gMap.zoomOut(); |
4b1d0915 | 1090 | } |
23cd2dcc | 1091 | break; |
1222624d RK |
1092 | case "keydown": |
1093 | // Allow keyboard control to move and zoom the map. | |
1094 | // Should use aEvent.key instead of aEvent.which but needs bug 680830. | |
1095 | // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown | |
1096 | var dX = 0; | |
1097 | var dY = 0; | |
1098 | switch (aEvent.which) { | |
1099 | case 39: // right | |
dda55132 | 1100 | dX = -gMap.tileSize / 2; |
1222624d RK |
1101 | break; |
1102 | case 37: // left | |
dda55132 | 1103 | dX = gMap.tileSize / 2; |
1222624d RK |
1104 | break; |
1105 | case 38: // up | |
dda55132 | 1106 | dY = gMap.tileSize / 2; |
1222624d RK |
1107 | break; |
1108 | case 40: // down | |
dda55132 | 1109 | dY = -gMap.tileSize / 2; |
1222624d RK |
1110 | break; |
1111 | case 87: // w | |
1112 | case 107: // + (numpad) | |
1113 | case 171: // + (normal key) | |
aa45a91b | 1114 | gMap.zoomIn(); |
1222624d RK |
1115 | break; |
1116 | case 83: // s | |
1117 | case 109: // - (numpad) | |
1118 | case 173: // - (normal key) | |
aa45a91b | 1119 | gMap.zoomOut(); |
1222624d RK |
1120 | break; |
1121 | case 48: // 0 | |
1122 | case 49: // 1 | |
1123 | case 50: // 2 | |
1124 | case 51: // 3 | |
1125 | case 52: // 4 | |
1126 | case 53: // 5 | |
1127 | case 54: // 6 | |
1128 | case 55: // 7 | |
1129 | case 56: // 8 | |
aa45a91b | 1130 | gMap.zoomTo(aEvent.which - 38); |
1222624d RK |
1131 | break; |
1132 | case 57: // 9 | |
aa45a91b | 1133 | gMap.zoomTo(9); |
1222624d RK |
1134 | break; |
1135 | case 96: // 0 (numpad) | |
1136 | case 97: // 1 (numpad) | |
1137 | case 98: // 2 (numpad) | |
1138 | case 99: // 3 (numpad) | |
1139 | case 100: // 4 (numpad) | |
1140 | case 101: // 5 (numpad) | |
1141 | case 102: // 6 (numpad) | |
1142 | case 103: // 7 (numpad) | |
1143 | case 104: // 8 (numpad) | |
aa45a91b | 1144 | gMap.zoomTo(aEvent.which - 86); |
1222624d RK |
1145 | break; |
1146 | case 105: // 9 (numpad) | |
aa45a91b | 1147 | gMap.zoomTo(9); |
1222624d RK |
1148 | break; |
1149 | default: // not supported | |
1150 | console.log("key not supported: " + aEvent.which); | |
1151 | break; | |
1152 | } | |
1153 | ||
1154 | // Move if needed. | |
1155 | if (dX || dY) { | |
dda55132 RK |
1156 | gMap.pos.x -= dX * gMap.zoomFactor; |
1157 | gMap.pos.y -= dY * gMap.zoomFactor; | |
0f6678fa | 1158 | gMap.draw(); |
68ca4617 | 1159 | gLastMoveAction = performance.now(); |
1222624d RK |
1160 | } |
1161 | break; | |
23cd2dcc RK |
1162 | } |
1163 | } | |
1164 | }; | |
55c4a0b7 | 1165 | |
5dd2ab70 RK |
1166 | function visibilityEvHandler() { |
1167 | // Immediately draw if we just got visible. | |
1168 | if (document.hidden != true) { | |
1169 | gMap.draw(); | |
1170 | } | |
1171 | // No need to handle the event where we become invisible as we care only draw | |
1172 | // when we are visible anyhow. | |
1173 | } | |
1174 | ||
993fd081 | 1175 | var geofake = { |
55c4a0b7 | 1176 | tracking: false, |
4b12da3a | 1177 | lastPos: {x: undefined, y: undefined}, |
55c4a0b7 RK |
1178 | watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) { |
1179 | this.tracking = true; | |
1180 | var watchCall = function() { | |
4b12da3a RK |
1181 | // calc new position in lat/lon degrees |
1182 | // 90° on Earth surface are ~10,000 km at the equator, | |
1183 | // so try moving at most 10m at a time | |
1184 | if (geofake.lastPos.x) | |
1185 | geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000 | |
1186 | else | |
1187 | geofake.lastPos.x = 48.208174 | |
1188 | if (geofake.lastPos.y) | |
1189 | geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000 | |
1190 | else | |
1191 | geofake.lastPos.y = 16.373819 | |
55c4a0b7 | 1192 | aSuccessCallback({timestamp: Date.now(), |
4b12da3a RK |
1193 | coords: {latitude: geofake.lastPos.x, |
1194 | longitude: geofake.lastPos.y, | |
55c4a0b7 RK |
1195 | accuracy: 20}}); |
1196 | if (geofake.tracking) | |
1197 | setTimeout(watchCall, 1000); | |
1198 | }; | |
1199 | setTimeout(watchCall, 1000); | |
1200 | return "foo"; | |
1201 | }, | |
1202 | clearWatch: function(aID) { | |
1203 | this.tracking = false; | |
1204 | } | |
1205 | } | |
1206 | ||
3610c22d RK |
1207 | function setCentering(aCheckbox) { |
1208 | if (gMapPrefsLoaded && mainDB) | |
1209 | gPrefs.set("center_map", aCheckbox.checked); | |
1210 | gCenterPosition = aCheckbox.checked; | |
1211 | } | |
1212 | ||
1213 | function setTracking(aCheckbox) { | |
1214 | if (gMapPrefsLoaded && mainDB) | |
1215 | gPrefs.set("tracking_enabled", aCheckbox.checked); | |
1216 | if (aCheckbox.checked) | |
1217 | startTracking(); | |
1218 | else | |
1219 | endTracking(); | |
1220 | } | |
1221 | ||
55c4a0b7 | 1222 | function startTracking() { |
31f0fe16 | 1223 | if (gGeolocation) { |
68afcd96 RK |
1224 | gActionLabel.textContent = "Establishing Position"; |
1225 | gAction.style.display = "block"; | |
d361104b RK |
1226 | if (navigator.requestWakeLock) { |
1227 | gGPSWakeLock = navigator.requestWakeLock("gps"); | |
1228 | } | |
4b12da3a | 1229 | gGeoWatchID = gGeolocation.watchPosition( |
55c4a0b7 | 1230 | function(position) { |
68afcd96 RK |
1231 | if (gActionLabel.textContent) { |
1232 | gActionLabel.textContent = ""; | |
1233 | gAction.style.display = "none"; | |
1234 | } | |
55c4a0b7 | 1235 | // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords |
993fd081 | 1236 | var tPoint = {time: position.timestamp, |
31f0fe16 RK |
1237 | coords: {latitude: position.coords.latitude, |
1238 | longitude: position.coords.longitude, | |
1239 | altitude: position.coords.altitude, | |
1240 | accuracy: position.coords.accuracy, | |
1241 | altitudeAccuracy: position.coords.altitudeAccuracy, | |
1242 | heading: position.coords.heading, | |
1243 | speed: position.coords.speed}, | |
993fd081 | 1244 | beginSegment: !gLastTrackPoint}; |
b054bd48 RK |
1245 | // Only add point to track is accuracy is good enough. |
1246 | if (tPoint.coords.accuracy < gMinTrackAccuracy) { | |
1247 | gLastTrackPoint = tPoint; | |
1248 | gTrack.push(tPoint); | |
1249 | try { gTrackStore.push(tPoint); } catch(e) {} | |
1250 | var redrawn = false; | |
68ca4617 | 1251 | if (gCenterPosition && (!gLastMoveAction || performance.now() > gLastMoveAction + gCenterDelayAfterMove)) { |
b054bd48 RK |
1252 | var posCoord = gps2xy(position.coords.latitude, |
1253 | position.coords.longitude); | |
ac6286bd RK |
1254 | if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 || |
1255 | Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) { | |
dda55132 RK |
1256 | gMap.pos.x = posCoord.x; |
1257 | gMap.pos.y = posCoord.y; | |
ac6286bd | 1258 | gMap.draw(); // This draws the current point as well. |
b054bd48 RK |
1259 | redrawn = true; |
1260 | } | |
99631a75 | 1261 | } |
b054bd48 | 1262 | if (!redrawn) |
aa45a91b | 1263 | gTrackLayer.undrawCurrentLocation(); |
b4df67c9 | 1264 | gTrackLayer.drawTrackPoint(gTrack.length-1); |
05c21757 | 1265 | } |
aa45a91b | 1266 | gTrackLayer.drawCurrentLocation(tPoint); |
55c4a0b7 RK |
1267 | }, |
1268 | function(error) { | |
1269 | // Ignore erros for the moment, but this is good for debugging. | |
1270 | // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors | |
915d4271 RK |
1271 | if (gDebug) |
1272 | console.log(error.message); | |
55c4a0b7 RK |
1273 | }, |
1274 | {enableHighAccuracy: true} | |
1275 | ); | |
1276 | } | |
1277 | } | |
1278 | ||
1279 | function endTracking() { | |
68afcd96 RK |
1280 | if (gActionLabel.textContent) { |
1281 | gActionLabel.textContent = ""; | |
1282 | gAction.style.display = "none"; | |
1283 | } | |
d361104b RK |
1284 | if (navigator.requestWakeLock && gGPSWakeLock) { |
1285 | console.log("releasing WakeLock"); | |
1286 | gGPSWakeLock.unlock(); | |
1287 | } | |
55c4a0b7 | 1288 | if (gGeoWatchID) { |
4b12da3a | 1289 | gGeolocation.clearWatch(gGeoWatchID); |
55c4a0b7 RK |
1290 | } |
1291 | } | |
993fd081 RK |
1292 | |
1293 | function clearTrack() { | |
1294 | gTrack = []; | |
1295 | gTrackStore.clear(); | |
aa45a91b | 1296 | gTrackLayer.drawTrack(); |
993fd081 | 1297 | } |
a8634d37 | 1298 | |
3b76e071 RK |
1299 | function loadTrackFromBackend(aTrackId, aFeedbackElement, aSuccessCallback) { |
1300 | if (aFeedbackElement) { | |
1301 | aFeedbackElement.textContent = "Loading..."; | |
1302 | // If someone loads without pointing to UI (e.g. for debugging), we just overwrite whatever's loaded. | |
1303 | if (calcTrackLength() > 1) { | |
1304 | aFeedbackElement.textContent = "Track >1km loaded, please save/clear."; | |
1305 | aFeedbackElement.classList.add("error"); | |
1306 | return; | |
1307 | } | |
1308 | } | |
57ee3e06 RK |
1309 | fetchBackend("track_json?id=" + encodeURIComponent(aTrackId), "GET", null, |
1310 | function(aResult, aStatusCode) { | |
3b76e071 | 1311 | if (aStatusCode >= 400) { |
57ee3e06 | 1312 | console.log("loading track failed: " + aStatusCode + ", result: " + aResult.message); |
3b76e071 RK |
1313 | if (aFeedbackElement) { |
1314 | aFeedbackElement.textContent = "Error: " + aResult; | |
1315 | aFeedbackElement.classList.add("error"); | |
1316 | } | |
57ee3e06 | 1317 | } |
3b76e071 RK |
1318 | else if (aResult) { |
1319 | loadTrack(aResult); | |
1320 | if (aSuccessCallback) { | |
1321 | aSuccessCallback(); | |
1322 | } | |
1323 | } | |
1324 | else { // If no result is returned, we assume a general error. | |
1325 | console.log("Error getting track with ID " + aTrackId + " from backend."); | |
1326 | if (aFeedbackElement) { | |
1327 | aFeedbackElement.textContent = "Error fetching track from backend."; | |
1328 | aFeedbackElement.classList.add("error"); | |
57ee3e06 | 1329 | } |
57ee3e06 RK |
1330 | } |
1331 | } | |
1332 | ); | |
1333 | } | |
1334 | ||
3b76e071 RK |
1335 | function loadTrack(aTrack) { |
1336 | console.log("Loading track with " + aTrack.length + " points."); | |
1337 | gTrack = aTrack; | |
1338 | gTrackStore.clear(function(aSuccess, aEvent) { | |
1339 | for (var i = 0; i < gTrack.length; i++) { | |
1340 | try { gTrackStore.push(gTrack[i]); } catch(e) {} | |
1341 | } | |
1342 | }); | |
aa45a91b | 1343 | gTrackLayer.drawTrack(); // Draws from gTrack, so not problem that gTrackStore is filled async. |
3b76e071 RK |
1344 | } |
1345 | ||
a8634d37 RK |
1346 | var gTileService = { |
1347 | objStore: "tilecache", | |
1348 | ||
5d67397a | 1349 | ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms) |
3431f496 | 1350 | |
a8634d37 RK |
1351 | get: function(aStyle, aCoords, aCallback) { |
1352 | var norm = normalizeCoords(aCoords); | |
b9707ee0 | 1353 | var dbkey = getTileKey(aStyle, norm); |
a8634d37 RK |
1354 | this.getDBCache(dbkey, function(aResult, aEvent) { |
1355 | if (aResult) { | |
1356 | // We did get a cached object. | |
e8525b46 | 1357 | aCallback(aResult.image, aStyle, aCoords, dbkey); |
3431f496 | 1358 | // Look at the timestamp and return if it's not too old. |
5d67397a | 1359 | if (aResult.timestamp + gTileService.ageLimit > Date.now()) |
3431f496 RK |
1360 | return; |
1361 | // Reload cached tile otherwise. | |
5d67397a RK |
1362 | var oldDate = new Date(aResult.timestamp); |
1363 | console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString()); | |
a8634d37 | 1364 | } |
3431f496 RK |
1365 | // Retrieve image from the web and store it in the cache. |
1366 | var XHR = new XMLHttpRequest(); | |
1367 | XHR.open("GET", | |
1368 | gMapStyles[aStyle].url | |
1369 | .replace("{x}", norm.x) | |
1370 | .replace("{y}", norm.y) | |
1371 | .replace("{z}", norm.z) | |
5ed2937e | 1372 | .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 3))) |
ca77d52d | 1373 | .replace("[a-d]", String.fromCharCode(97 + Math.floor(Math.random() * 4))) |
5ed2937e | 1374 | .replace("[1-4]", 1 + Math.floor(Math.random() * 4)), |
3431f496 RK |
1375 | true); |
1376 | XHR.responseType = "blob"; | |
1377 | XHR.addEventListener("load", function () { | |
1378 | if (XHR.status === 200) { | |
1379 | var blob = XHR.response; | |
e8525b46 | 1380 | aCallback(blob, aStyle, aCoords, dbkey); |
6d7cdcf6 | 1381 | gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()}); |
3431f496 RK |
1382 | } |
1383 | }, false); | |
1384 | XHR.send(); | |
a8634d37 RK |
1385 | }); |
1386 | }, | |
1387 | ||
1388 | getDBCache: function(aKey, aCallback) { | |
1389 | if (!mainDB) | |
1390 | return; | |
1391 | var transaction = mainDB.transaction([this.objStore]); | |
1392 | var request = transaction.objectStore(this.objStore).get(aKey); | |
1393 | request.onsuccess = function(event) { | |
1394 | aCallback(request.result, event); | |
1395 | }; | |
1396 | request.onerror = function(event) { | |
1397 | // Errors can be handled here. | |
1398 | aCallback(undefined, event); | |
1399 | }; | |
1400 | }, | |
1401 | ||
1402 | setDBCache: function(aKey, aValue, aCallback) { | |
1403 | if (!mainDB) | |
1404 | return; | |
1405 | var success = false; | |
1406 | var transaction = mainDB.transaction([this.objStore], "readwrite"); | |
1407 | var objStore = transaction.objectStore(this.objStore); | |
1408 | var request = objStore.put(aValue, aKey); | |
1409 | request.onsuccess = function(event) { | |
1410 | success = true; | |
1411 | if (aCallback) | |
1412 | aCallback(success, event); | |
1413 | }; | |
1414 | request.onerror = function(event) { | |
1415 | // Errors can be handled here. | |
1416 | if (aCallback) | |
1417 | aCallback(success, event); | |
1418 | }; | |
1419 | }, | |
1420 | ||
1421 | unsetDBCache: function(aKey, aCallback) { | |
1422 | if (!mainDB) | |
1423 | return; | |
1424 | var success = false; | |
1425 | var transaction = mainDB.transaction([this.objStore], "readwrite"); | |
1426 | var request = transaction.objectStore(this.objStore).delete(aKey); | |
1427 | request.onsuccess = function(event) { | |
1428 | success = true; | |
1429 | if (aCallback) | |
1430 | aCallback(success, event); | |
1431 | }; | |
1432 | request.onerror = function(event) { | |
1433 | // Errors can be handled here. | |
1434 | if (aCallback) | |
1435 | aCallback(success, event); | |
1436 | } | |
3431f496 RK |
1437 | }, |
1438 | ||
1439 | clearDB: function(aCallback) { | |
1440 | if (!mainDB) | |
1441 | return; | |
1442 | var success = false; | |
1443 | var transaction = mainDB.transaction([this.objStore], "readwrite"); | |
1444 | var request = transaction.objectStore(this.objStore).clear(); | |
1445 | request.onsuccess = function(event) { | |
1446 | success = true; | |
e4840ddc | 1447 | console.log("Cache cleared."); |
3431f496 RK |
1448 | if (aCallback) |
1449 | aCallback(success, event); | |
1450 | }; | |
1451 | request.onerror = function(event) { | |
1452 | // Errors can be handled here. | |
e4840ddc | 1453 | console.log("Error clearing cache!"); |
3431f496 RK |
1454 | if (aCallback) |
1455 | aCallback(success, event); | |
1456 | } | |
a8634d37 RK |
1457 | } |
1458 | }; |