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