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