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