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