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 | ||
ac6286bd RK |
310 | draw: function(aPixels, aOverdraw) { |
311 | gMap.drawGL(aPixels, aOverdraw); | |
312 | drawTrack(); | |
dda55132 | 313 | }, |
ecde0af2 | 314 | |
dda55132 RK |
315 | drawGL: function(aPixels, aOverdraw) { |
316 | if (!gMap.gl) { return; } | |
317 | // aPixels is an object with left/right/top/bottom members telling how many | |
318 | // pixels on the borders should actually be drawn. | |
319 | // aOverdraw is a bool that tells if we should draw placeholders or draw | |
320 | // straight over the existing content. | |
321 | // XXX: Both those optimizations are OFF for GL right now! | |
322 | //if (!aPixels) | |
323 | aPixels = {left: gMap.gl.drawingBufferWidth, right: gMap.gl.drawingBufferWidth, | |
324 | top: gMap.gl.drawingBufferHeight, bottom: gMap.gl.drawingBufferHeight}; | |
e8525b46 | 325 | if (!aOverdraw) |
dda55132 RK |
326 | aOverdraw = false; |
327 | ||
328 | document.getElementById("zoomLevel").textContent = gMap.pos.z; | |
329 | gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z); | |
330 | var wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor; // Width in level 18 pixels. | |
331 | var ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor; // Height in level 18 pixels. | |
332 | var size = gMap.tileSize * gMap.zoomFactor; // Tile size in level 18 pixels. | |
333 | ||
334 | var xMin = gMap.pos.x - wid / 2; // Corners of the window in level 18 pixels. | |
335 | var yMin = gMap.pos.y - ht / 2; | |
336 | var xMax = gMap.pos.x + wid / 2; | |
337 | var yMax = gMap.pos.y + ht / 2; | |
338 | ||
339 | if (gMapPrefsLoaded && mainDB) | |
340 | gPrefs.set("position", gMap.pos); | |
341 | ||
342 | var tiles = {left: Math.ceil((xMin + aPixels.left * gMap.zoomFactor) / size) - | |
343 | (aPixels.left ? 0 : 1), | |
344 | right: Math.floor((xMax - aPixels.right * gMap.zoomFactor) / size) - | |
345 | (aPixels.right ? 1 : 0), | |
346 | top: Math.ceil((yMin + aPixels.top * gMap.zoomFactor) / size) - | |
347 | (aPixels.top ? 0 : 1), | |
348 | bottom: Math.floor((yMax - aPixels.bottom * gMap.zoomFactor) / size) - | |
349 | (aPixels.bottom ? 1 : 0)}; | |
350 | ||
351 | // Go through all the tiles in the map, find out if to draw them and do so. | |
352 | for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) { | |
353 | for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here! | |
354 | // Only go to the drawing step if we need to draw this tile. | |
355 | if (x < tiles.left || x > tiles.right || | |
356 | y < tiles.top || y > tiles.bottom) { | |
357 | // Round here is **CRUCIAL** otherwise the images are filtered | |
358 | // and the performance sucks (more than expected). | |
359 | var xoff = Math.round((x * size - xMin) / gMap.zoomFactor); | |
360 | var yoff = Math.round((y * size - yMin) / gMap.zoomFactor); | |
361 | // Draw placeholder tile unless we overdraw. | |
362 | if (!aOverdraw && | |
363 | (x < tiles.left -1 || x > tiles.right + 1 || | |
e8525b46 RK |
364 | y < tiles.top -1 || y > tiles.bottom + 1)) { |
365 | gMap.drawTileGL(xoff, yoff, 0); | |
366 | } | |
dda55132 RK |
367 | // Initiate loading/drawing of the actual tile. |
368 | gTileService.get(gMap.activeMap, {x: x, y: y, z: gMap.pos.z}, | |
e8525b46 | 369 | function(aImage, aStyle, aCoords, aTileKey) { |
dda55132 RK |
370 | // Only draw if this applies for the current view. |
371 | if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) { | |
372 | var ixMin = gMap.pos.x - wid / 2; | |
373 | var iyMin = gMap.pos.y - ht / 2; | |
374 | var ixoff = Math.round((aCoords.x * size - ixMin) / gMap.zoomFactor); | |
375 | var iyoff = Math.round((aCoords.y * size - iyMin) / gMap.zoomFactor); | |
376 | var URL = window.URL; | |
377 | var imgURL = URL.createObjectURL(aImage); | |
378 | var imgObj = new Image(); | |
379 | imgObj.src = imgURL; | |
380 | imgObj.onload = function() { | |
ac6286bd | 381 | // TODO: Do actually paint in a separate function, called on requestAnimationFrame. |
e8525b46 RK |
382 | var txIndex = gMap.glTextureKeys[aTileKey]; |
383 | if (!txIndex) { | |
384 | txIndex = Object.keys(gMap.glTextureKeys).length; | |
385 | gMap.loadImageToTexture(imgObj, txIndex, aTileKey); | |
386 | } | |
387 | gMap.drawTileGL(ixoff, iyoff, txIndex); | |
dda55132 RK |
388 | URL.revokeObjectURL(imgURL); |
389 | } | |
390 | } | |
391 | }); | |
dda55132 RK |
392 | } |
393 | } | |
394 | } | |
dda55132 | 395 | }, |
edc3be71 | 396 | |
ac6286bd RK |
397 | resizeAndDraw: function() { |
398 | var viewportWidth = Math.min(window.innerWidth, window.outerWidth); | |
399 | var viewportHeight = Math.min(window.innerHeight, window.outerHeight); | |
400 | if (gGLMapCanvas && gTrackCanvas) { | |
401 | gGLMapCanvas.width = viewportWidth; | |
402 | gGLMapCanvas.height = viewportHeight; | |
403 | gTrackCanvas.width = viewportWidth; | |
404 | gTrackCanvas.height = viewportHeight; | |
405 | if (gMap.gl) { | |
406 | // Size viewport to canvas size. | |
407 | gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight); | |
408 | // Clear the color. | |
409 | gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT); | |
410 | // Make sure the vertex shader get the right resolution. | |
411 | gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height); | |
412 | } | |
413 | gMap.draw(); | |
414 | showUI(); | |
415 | } | |
dda55132 RK |
416 | }, |
417 | ||
e8525b46 RK |
418 | drawTileGL: function(aLeft, aRight, aTextureIndex) { |
419 | gMap.gl.activeTexture(gMap.gl.TEXTURE0 + aTextureIndex); | |
420 | gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTextureIndex]); | |
dda55132 RK |
421 | var x_start = aLeft; |
422 | var i_width = gMap.tileSize; | |
423 | var y_start = aRight; | |
424 | var i_height = gMap.tileSize; | |
edc3be71 RK |
425 | var textureCoordinates = [ |
426 | x_start, y_start, | |
427 | x_start + i_width, y_start, | |
428 | x_start, y_start + i_height, | |
429 | x_start, y_start + i_height, | |
430 | x_start + i_width, y_start, | |
431 | x_start + i_width, y_start + i_height, | |
432 | ]; | |
433 | gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW); | |
edc3be71 RK |
434 | |
435 | // There are 6 indices in textureCoordinates. | |
436 | gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6); | |
e8525b46 RK |
437 | }, |
438 | ||
439 | loadImageToTexture: function(aImage, aTextureIndex, aTileKey) { | |
440 | gMap.glTextureKeys[aTileKey] = aTextureIndex; | |
441 | // Create and bind texture. | |
442 | gMap.glTextures[aTextureIndex] = gMap.gl.createTexture(); | |
443 | gMap.gl.activeTexture(gMap.gl.TEXTURE0 + aTextureIndex); | |
444 | gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTextureIndex]); | |
445 | gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0); | |
446 | // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two). | |
447 | gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST); | |
448 | gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST); | |
449 | // Upload the image into the texture. | |
450 | gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage); | |
451 | }, | |
ecde0af2 RK |
452 | } |
453 | ||
b5e49b95 RK |
454 | // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming. |
455 | // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling | |
456 | ||
23cd2dcc | 457 | function zoomIn() { |
dda55132 RK |
458 | if (gMap.pos.z < gMap.maxZoom) { |
459 | gMap.pos.z++; | |
ac6286bd | 460 | gMap.draw(); |
23cd2dcc RK |
461 | } |
462 | } | |
463 | ||
464 | function zoomOut() { | |
dda55132 RK |
465 | if (gMap.pos.z > 0) { |
466 | gMap.pos.z--; | |
ac6286bd | 467 | gMap.draw(); |
23cd2dcc RK |
468 | } |
469 | } | |
470 | ||
1222624d RK |
471 | function zoomTo(aTargetLevel) { |
472 | aTargetLevel = parseInt(aTargetLevel); | |
dda55132 RK |
473 | if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) { |
474 | gMap.pos.z = aTargetLevel; | |
ac6286bd | 475 | gMap.draw(); |
1222624d RK |
476 | } |
477 | } | |
478 | ||
55c4a0b7 | 479 | function gps2xy(aLatitude, aLongitude) { |
dda55132 | 480 | var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize; |
55c4a0b7 RK |
481 | var convLat = aLatitude * Math.PI / 180; |
482 | var rawY = (1 - Math.log(Math.tan(convLat) + | |
483 | 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor; | |
484 | var rawX = (aLongitude + 180) / 360 * maxZoomFactor; | |
485 | return {x: Math.round(rawX), | |
486 | y: Math.round(rawY)}; | |
487 | } | |
488 | ||
489 | function xy2gps(aX, aY) { | |
dda55132 | 490 | var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize; |
55c4a0b7 RK |
491 | var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor; |
492 | return {latitude: 180 / Math.PI * | |
493 | Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))), | |
494 | longitude: aX / maxZoomFactor * 360 - 180}; | |
495 | } | |
496 | ||
b47b4a65 RK |
497 | function setMapStyle() { |
498 | var mapSel = document.getElementById("mapSelector"); | |
dda55132 RK |
499 | if (mapSel.selectedIndex >= 0 && gMap.activeMap != mapSel.value) { |
500 | gMap.activeMap = mapSel.value; | |
95f49ba7 | 501 | document.getElementById("copyright").innerHTML = |
dda55132 | 502 | gMapStyles[gMap.activeMap].copyright; |
b5c85133 | 503 | showUI(); |
ac6286bd | 504 | gMap.draw(); |
b47b4a65 RK |
505 | } |
506 | } | |
507 | ||
23cd2dcc RK |
508 | // A sane mod function that works for negative numbers. |
509 | // Returns a % b. | |
510 | function mod(a, b) { | |
511 | return ((a % b) + b) % b; | |
512 | } | |
513 | ||
a8634d37 RK |
514 | function normalizeCoords(aCoords) { |
515 | var zoomFactor = Math.pow(2, aCoords.z); | |
516 | return {x: mod(aCoords.x, zoomFactor), | |
517 | y: mod(aCoords.y, zoomFactor), | |
518 | z: aCoords.z}; | |
23cd2dcc RK |
519 | } |
520 | ||
521 | // Returns true if the tile is outside the current view. | |
522 | function isOutsideWindow(t) { | |
523 | var pos = decodeIndex(t); | |
23cd2dcc | 524 | |
dda55132 | 525 | var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z); |
ac6286bd RK |
526 | var wid = gMap.width * zoomFactor; |
527 | var ht = gMap.height * zoomFactor; | |
23cd2dcc | 528 | |
4b1d0915 RK |
529 | pos.x *= zoomFactor; |
530 | pos.y *= zoomFactor; | |
23cd2dcc | 531 | |
dda55132 RK |
532 | var sz = gMap.tileSize * zoomFactor; |
533 | if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 || | |
534 | pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2) | |
23cd2dcc RK |
535 | return true; |
536 | return false; | |
537 | } | |
538 | ||
539 | function encodeIndex(x, y, z) { | |
a8634d37 | 540 | var norm = normalizeCoords({x: x, y: y, z: z}); |
23cd2dcc RK |
541 | return norm.x + "," + norm.y + "," + norm.z; |
542 | } | |
543 | ||
544 | function decodeIndex(encodedIdx) { | |
4b1d0915 RK |
545 | var ind = encodedIdx.split(",", 3); |
546 | return {x: ind[0], y: ind[1], z: ind[2]}; | |
23cd2dcc RK |
547 | } |
548 | ||
6ddefbf9 | 549 | function drawTrack() { |
4b1d0915 RK |
550 | gLastDrawnPoint = null; |
551 | gCurPosMapCache = undefined; | |
552 | gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height); | |
14e6d3ad | 553 | if (gTrack.length) { |
55c4a0b7 | 554 | for (var i = 0; i < gTrack.length; i++) { |
14e6d3ad RK |
555 | drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude, |
556 | (i + 1 >= gTrack.length)); | |
55c4a0b7 | 557 | } |
14e6d3ad | 558 | } |
55c4a0b7 RK |
559 | } |
560 | ||
14e6d3ad | 561 | function drawTrackPoint(aLatitude, aLongitude, lastPoint) { |
55c4a0b7 | 562 | var trackpoint = gps2xy(aLatitude, aLongitude); |
14e6d3ad RK |
563 | // lastPoint is for optimizing (not actually executing the draw until the last) |
564 | trackpoint.optimized = (lastPoint === false); | |
ac6286bd RK |
565 | var mappos = {x: Math.round((trackpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2), |
566 | y: Math.round((trackpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)}; | |
14e6d3ad RK |
567 | |
568 | if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) { | |
4b1d0915 RK |
569 | gTrackContext.strokeStyle = gTrackColor; |
570 | gTrackContext.fillStyle = gTrackContext.strokeStyle; | |
571 | gTrackContext.lineWidth = gTrackWidth; | |
572 | gTrackContext.lineCap = "round"; | |
573 | gTrackContext.lineJoin = "round"; | |
14e6d3ad RK |
574 | } |
575 | if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) { | |
576 | // This breaks optimiziation, so make sure to close path and reset optimization. | |
577 | if (gLastDrawnPoint && gLastDrawnPoint.optimized) | |
4b1d0915 RK |
578 | gTrackContext.stroke(); |
579 | gTrackContext.beginPath(); | |
14e6d3ad | 580 | trackpoint.optimized = false; |
4b1d0915 RK |
581 | gTrackContext.arc(mappos.x, mappos.y, |
582 | gTrackContext.lineWidth, 0, Math.PI * 2, false); | |
583 | gTrackContext.fill(); | |
55c4a0b7 RK |
584 | } |
585 | else { | |
14e6d3ad | 586 | if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) { |
4b1d0915 | 587 | gTrackContext.beginPath(); |
ac6286bd RK |
588 | gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2), |
589 | Math.round((gLastDrawnPoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)); | |
14e6d3ad | 590 | } |
4b1d0915 | 591 | gTrackContext.lineTo(mappos.x, mappos.y); |
14e6d3ad | 592 | if (!trackpoint.optimized) |
4b1d0915 | 593 | gTrackContext.stroke(); |
55c4a0b7 | 594 | } |
14e6d3ad | 595 | gLastDrawnPoint = trackpoint; |
23cd2dcc RK |
596 | } |
597 | ||
b054bd48 | 598 | function drawCurrentLocation(trackPoint) { |
4b1d0915 RK |
599 | var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude); |
600 | var circleRadius = Math.round(gCurLocSize / 2); | |
ac6286bd RK |
601 | var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2), |
602 | y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)}; | |
4b1d0915 RK |
603 | |
604 | undrawCurrentLocation(); | |
b054bd48 RK |
605 | |
606 | // Cache overdrawn area. | |
4b1d0915 RK |
607 | gCurPosMapCache = |
608 | {point: locpoint, | |
609 | radius: circleRadius, | |
610 | data: gTrackContext.getImageData(mappos.x - circleRadius, | |
611 | mappos.y - circleRadius, | |
612 | circleRadius * 2, circleRadius * 2)}; | |
613 | ||
614 | gTrackContext.strokeStyle = gCurLocColor; | |
615 | gTrackContext.fillStyle = gTrackContext.strokeStyle; | |
616 | gTrackContext.beginPath(); | |
617 | gTrackContext.arc(mappos.x, mappos.y, | |
618 | circleRadius, 0, Math.PI * 2, false); | |
619 | gTrackContext.fill(); | |
620 | } | |
621 | ||
622 | function undrawCurrentLocation() { | |
623 | if (gCurPosMapCache) { | |
624 | var oldpoint = gCurPosMapCache.point; | |
ac6286bd RK |
625 | var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2), |
626 | y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)}; | |
4b1d0915 RK |
627 | gTrackContext.putImageData(gCurPosMapCache.data, |
628 | oldmp.x - gCurPosMapCache.radius, | |
629 | oldmp.y - gCurPosMapCache.radius); | |
630 | gCurPosMapCache = undefined; | |
631 | } | |
b054bd48 RK |
632 | } |
633 | ||
23cd2dcc RK |
634 | var mapEvHandler = { |
635 | handleEvent: function(aEvent) { | |
636 | var touchEvent = aEvent.type.indexOf('touch') != -1; | |
637 | ||
306ae634 RK |
638 | if (touchEvent) { |
639 | aEvent.stopPropagation(); | |
640 | } | |
641 | ||
8389557a RK |
642 | // Bail out if the event is happening on an input. |
643 | if (aEvent.target.tagName.toLowerCase() == "input") | |
644 | return; | |
645 | ||
1222624d RK |
646 | // Bail out on unwanted map moves, but not zoom or keyboard events. |
647 | if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) { | |
23cd2dcc RK |
648 | // Bail out if this is neither a touch nor left-click. |
649 | if (!touchEvent && aEvent.button != 0) | |
650 | return; | |
651 | ||
652 | // Bail out if the started touch can't be found. | |
4b12da3a RK |
653 | if (touchEvent && gDragging && |
654 | !aEvent.changedTouches.identifiedTouch(gDragTouchID)) | |
23cd2dcc RK |
655 | return; |
656 | } | |
657 | ||
658 | var coordObj = touchEvent ? | |
4b12da3a | 659 | aEvent.changedTouches.identifiedTouch(gDragTouchID) : |
23cd2dcc RK |
660 | aEvent; |
661 | ||
662 | switch (aEvent.type) { | |
663 | case "mousedown": | |
664 | case "touchstart": | |
665 | if (touchEvent) { | |
517c0099 RK |
666 | if (aEvent.targetTouches.length == 2) { |
667 | gPinchStartWidth = Math.sqrt( | |
668 | Math.pow(aEvent.targetTouches.item(1).clientX - | |
669 | aEvent.targetTouches.item(0).clientX, 2) + | |
670 | Math.pow(aEvent.targetTouches.item(1).clientY - | |
671 | aEvent.targetTouches.item(0).clientY, 2) | |
672 | ); | |
673 | } | |
4b12da3a RK |
674 | gDragTouchID = aEvent.changedTouches.item(0).identifier; |
675 | coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID); | |
23cd2dcc | 676 | } |
ac6286bd RK |
677 | var x = coordObj.clientX - gGLMapCanvas.offsetLeft; |
678 | var y = coordObj.clientY - gGLMapCanvas.offsetTop; | |
b395419b | 679 | |
23cd2dcc RK |
680 | if (touchEvent || aEvent.button === 0) { |
681 | gDragging = true; | |
682 | } | |
683 | gLastMouseX = x; | |
684 | gLastMouseY = y; | |
7a549148 | 685 | showUI(); |
23cd2dcc RK |
686 | break; |
687 | case "mousemove": | |
688 | case "touchmove": | |
517c0099 RK |
689 | if (touchEvent && aEvent.targetTouches.length == 2) { |
690 | curPinchStartWidth = Math.sqrt( | |
691 | Math.pow(aEvent.targetTouches.item(1).clientX - | |
692 | aEvent.targetTouches.item(0).clientX, 2) + | |
693 | Math.pow(aEvent.targetTouches.item(1).clientY - | |
694 | aEvent.targetTouches.item(0).clientY, 2) | |
695 | ); | |
003d56f8 RK |
696 | if (!gPinchStartWidth) |
697 | gPinchStartWidth = curPinchStartWidth; | |
d07d7abc | 698 | |
517c0099 RK |
699 | if (gPinchStartWidth / curPinchStartWidth > 1.7 || |
700 | gPinchStartWidth / curPinchStartWidth < 0.6) { | |
dda55132 RK |
701 | var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1); |
702 | if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) { | |
517c0099 RK |
703 | // Calculate new center of the map - preserve middle of pinch. |
704 | // This means that pixel distance between old center and middle | |
705 | // must equal pixel distance of new center and middle. | |
706 | var x = (aEvent.targetTouches.item(1).clientX + | |
707 | aEvent.targetTouches.item(0).clientX) / 2 - | |
ac6286bd | 708 | gGLMapCanvas.offsetLeft; |
517c0099 RK |
709 | var y = (aEvent.targetTouches.item(1).clientY + |
710 | aEvent.targetTouches.item(0).clientY) / 2 - | |
ac6286bd | 711 | gGLMapCanvas.offsetTop; |
517c0099 RK |
712 | |
713 | // Zoom factor after this action. | |
dda55132 | 714 | var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel); |
ac6286bd RK |
715 | gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor); |
716 | gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor); | |
517c0099 RK |
717 | |
718 | if (gPinchStartWidth < curPinchStartWidth) | |
719 | zoomIn(); | |
720 | else | |
721 | zoomOut(); | |
003d56f8 RK |
722 | |
723 | // Reset pinch start width and start another pinch gesture. | |
724 | gPinchStartWidth = null; | |
517c0099 RK |
725 | } |
726 | } | |
d07d7abc | 727 | // If we are in a pinch, do not drag. |
517c0099 RK |
728 | break; |
729 | } | |
ac6286bd RK |
730 | var x = coordObj.clientX - gGLMapCanvas.offsetLeft; |
731 | var y = coordObj.clientY - gGLMapCanvas.offsetTop; | |
23cd2dcc RK |
732 | if (gDragging === true) { |
733 | var dX = x - gLastMouseX; | |
734 | var dY = y - gLastMouseY; | |
dda55132 RK |
735 | gMap.pos.x -= dX * gMap.zoomFactor; |
736 | gMap.pos.y -= dY * gMap.zoomFactor; | |
ac6286bd RK |
737 | if (false) { // use optimized path |
738 | /* TODO: investigate optimized path for GL - code below was 2D. | |
747bbd55 RK |
739 | var mapData = gMapContext.getImageData(0, 0, |
740 | gMapCanvas.width, | |
741 | gMapCanvas.height); | |
742 | gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height); | |
743 | gMapContext.putImageData(mapData, dX, dY); | |
ac6286bd | 744 | gMap.draw({left: (dX > 0) ? dX : 0, |
747bbd55 RK |
745 | right: (dX < 0) ? -dX : 0, |
746 | top: (dY > 0) ? dY : 0, | |
747 | bottom: (dY < 0) ? -dY : 0}); | |
ac6286bd | 748 | */ |
747bbd55 RK |
749 | } |
750 | else { | |
ac6286bd | 751 | gMap.draw(false, true); |
747bbd55 | 752 | } |
7a549148 | 753 | showUI(); |
23cd2dcc RK |
754 | } |
755 | gLastMouseX = x; | |
756 | gLastMouseY = y; | |
757 | break; | |
758 | case "mouseup": | |
759 | case "touchend": | |
d07d7abc | 760 | gPinchStartWidth = null; |
23cd2dcc | 761 | gDragging = false; |
7a549148 | 762 | showUI(); |
23cd2dcc RK |
763 | break; |
764 | case "mouseout": | |
765 | case "touchcancel": | |
766 | case "touchleave": | |
767 | //gDragging = false; | |
768 | break; | |
5fb31b29 RK |
769 | case "wheel": |
770 | // If we'd want pixels, we'd need to calc up using aEvent.deltaMode. | |
771 | // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel | |
772 | ||
773 | // Only accept (non-null) deltaY values | |
774 | if (!aEvent.deltaY) | |
775 | break; | |
23cd2dcc | 776 | |
55c4a0b7 RK |
777 | // Debug output: "coordinates" of the point the mouse was over. |
778 | /* | |
ac6286bd RK |
779 | var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor, |
780 | y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor}; | |
55c4a0b7 RK |
781 | var gpsCoord = xy2gps(ptCoord.x, ptCoord.y); |
782 | var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude); | |
915d4271 RK |
783 | console.log(ptCoord.x + "/" + ptCoord.y + " - " + |
784 | gpsCoord.latitude + "/" + gpsCoord.longitude + " - " + | |
785 | pt2Coord.x + "/" + pt2Coord.y); | |
55c4a0b7 | 786 | */ |
4b1d0915 | 787 | |
dda55132 RK |
788 | var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1); |
789 | if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) { | |
4b1d0915 RK |
790 | // Calculate new center of the map - same point stays under the mouse. |
791 | // This means that the pixel distance between the old center and point | |
792 | // must equal the pixel distance of the new center and that point. | |
ac6286bd RK |
793 | var x = coordObj.clientX - gGLMapCanvas.offsetLeft; |
794 | var y = coordObj.clientY - gGLMapCanvas.offsetTop; | |
4b1d0915 RK |
795 | |
796 | // Zoom factor after this action. | |
dda55132 | 797 | var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel); |
ac6286bd RK |
798 | gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor); |
799 | gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor); | |
4b1d0915 | 800 | |
5fb31b29 | 801 | if (aEvent.deltaY < 0) |
4b1d0915 | 802 | zoomIn(); |
5fb31b29 | 803 | else |
4b1d0915 RK |
804 | zoomOut(); |
805 | } | |
23cd2dcc | 806 | break; |
1222624d RK |
807 | case "keydown": |
808 | // Allow keyboard control to move and zoom the map. | |
809 | // Should use aEvent.key instead of aEvent.which but needs bug 680830. | |
810 | // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown | |
811 | var dX = 0; | |
812 | var dY = 0; | |
813 | switch (aEvent.which) { | |
814 | case 39: // right | |
dda55132 | 815 | dX = -gMap.tileSize / 2; |
1222624d RK |
816 | break; |
817 | case 37: // left | |
dda55132 | 818 | dX = gMap.tileSize / 2; |
1222624d RK |
819 | break; |
820 | case 38: // up | |
dda55132 | 821 | dY = gMap.tileSize / 2; |
1222624d RK |
822 | break; |
823 | case 40: // down | |
dda55132 | 824 | dY = -gMap.tileSize / 2; |
1222624d RK |
825 | break; |
826 | case 87: // w | |
827 | case 107: // + (numpad) | |
828 | case 171: // + (normal key) | |
829 | zoomIn(); | |
830 | break; | |
831 | case 83: // s | |
832 | case 109: // - (numpad) | |
833 | case 173: // - (normal key) | |
834 | zoomOut(); | |
835 | break; | |
836 | case 48: // 0 | |
837 | case 49: // 1 | |
838 | case 50: // 2 | |
839 | case 51: // 3 | |
840 | case 52: // 4 | |
841 | case 53: // 5 | |
842 | case 54: // 6 | |
843 | case 55: // 7 | |
844 | case 56: // 8 | |
845 | zoomTo(aEvent.which - 38); | |
846 | break; | |
847 | case 57: // 9 | |
848 | zoomTo(9); | |
849 | break; | |
850 | case 96: // 0 (numpad) | |
851 | case 97: // 1 (numpad) | |
852 | case 98: // 2 (numpad) | |
853 | case 99: // 3 (numpad) | |
854 | case 100: // 4 (numpad) | |
855 | case 101: // 5 (numpad) | |
856 | case 102: // 6 (numpad) | |
857 | case 103: // 7 (numpad) | |
858 | case 104: // 8 (numpad) | |
859 | zoomTo(aEvent.which - 86); | |
860 | break; | |
861 | case 105: // 9 (numpad) | |
862 | zoomTo(9); | |
863 | break; | |
864 | default: // not supported | |
865 | console.log("key not supported: " + aEvent.which); | |
866 | break; | |
867 | } | |
868 | ||
869 | // Move if needed. | |
870 | if (dX || dY) { | |
dda55132 RK |
871 | gMap.pos.x -= dX * gMap.zoomFactor; |
872 | gMap.pos.y -= dY * gMap.zoomFactor; | |
ac6286bd RK |
873 | if (false) { // use optimized path |
874 | /* TODO: investigate optimized path for GL - code below was 2D. | |
1222624d RK |
875 | var mapData = gMapContext.getImageData(0, 0, |
876 | gMapCanvas.width, | |
877 | gMapCanvas.height); | |
878 | gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height); | |
879 | gMapContext.putImageData(mapData, dX, dY); | |
ac6286bd | 880 | gMap.draw({left: (dX > 0) ? dX : 0, |
1222624d RK |
881 | right: (dX < 0) ? -dX : 0, |
882 | top: (dY > 0) ? dY : 0, | |
883 | bottom: (dY < 0) ? -dY : 0}); | |
ac6286bd | 884 | */ |
1222624d RK |
885 | } |
886 | else { | |
ac6286bd | 887 | gMap.draw(false, true); |
1222624d RK |
888 | } |
889 | } | |
890 | break; | |
23cd2dcc RK |
891 | } |
892 | } | |
893 | }; | |
55c4a0b7 | 894 | |
993fd081 | 895 | var geofake = { |
55c4a0b7 | 896 | tracking: false, |
4b12da3a | 897 | lastPos: {x: undefined, y: undefined}, |
55c4a0b7 RK |
898 | watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) { |
899 | this.tracking = true; | |
900 | var watchCall = function() { | |
4b12da3a RK |
901 | // calc new position in lat/lon degrees |
902 | // 90° on Earth surface are ~10,000 km at the equator, | |
903 | // so try moving at most 10m at a time | |
904 | if (geofake.lastPos.x) | |
905 | geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000 | |
906 | else | |
907 | geofake.lastPos.x = 48.208174 | |
908 | if (geofake.lastPos.y) | |
909 | geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000 | |
910 | else | |
911 | geofake.lastPos.y = 16.373819 | |
55c4a0b7 | 912 | aSuccessCallback({timestamp: Date.now(), |
4b12da3a RK |
913 | coords: {latitude: geofake.lastPos.x, |
914 | longitude: geofake.lastPos.y, | |
55c4a0b7 RK |
915 | accuracy: 20}}); |
916 | if (geofake.tracking) | |
917 | setTimeout(watchCall, 1000); | |
918 | }; | |
919 | setTimeout(watchCall, 1000); | |
920 | return "foo"; | |
921 | }, | |
922 | clearWatch: function(aID) { | |
923 | this.tracking = false; | |
924 | } | |
925 | } | |
926 | ||
3610c22d RK |
927 | function setCentering(aCheckbox) { |
928 | if (gMapPrefsLoaded && mainDB) | |
929 | gPrefs.set("center_map", aCheckbox.checked); | |
930 | gCenterPosition = aCheckbox.checked; | |
931 | } | |
932 | ||
933 | function setTracking(aCheckbox) { | |
934 | if (gMapPrefsLoaded && mainDB) | |
935 | gPrefs.set("tracking_enabled", aCheckbox.checked); | |
936 | if (aCheckbox.checked) | |
937 | startTracking(); | |
938 | else | |
939 | endTracking(); | |
940 | } | |
941 | ||
55c4a0b7 | 942 | function startTracking() { |
31f0fe16 | 943 | if (gGeolocation) { |
68afcd96 RK |
944 | gActionLabel.textContent = "Establishing Position"; |
945 | gAction.style.display = "block"; | |
4b12da3a | 946 | gGeoWatchID = gGeolocation.watchPosition( |
55c4a0b7 | 947 | function(position) { |
68afcd96 RK |
948 | if (gActionLabel.textContent) { |
949 | gActionLabel.textContent = ""; | |
950 | gAction.style.display = "none"; | |
951 | } | |
55c4a0b7 | 952 | // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords |
993fd081 | 953 | var tPoint = {time: position.timestamp, |
31f0fe16 RK |
954 | coords: {latitude: position.coords.latitude, |
955 | longitude: position.coords.longitude, | |
956 | altitude: position.coords.altitude, | |
957 | accuracy: position.coords.accuracy, | |
958 | altitudeAccuracy: position.coords.altitudeAccuracy, | |
959 | heading: position.coords.heading, | |
960 | speed: position.coords.speed}, | |
993fd081 | 961 | beginSegment: !gLastTrackPoint}; |
b054bd48 RK |
962 | // Only add point to track is accuracy is good enough. |
963 | if (tPoint.coords.accuracy < gMinTrackAccuracy) { | |
964 | gLastTrackPoint = tPoint; | |
965 | gTrack.push(tPoint); | |
966 | try { gTrackStore.push(tPoint); } catch(e) {} | |
967 | var redrawn = false; | |
968 | if (gCenterPosition) { | |
969 | var posCoord = gps2xy(position.coords.latitude, | |
970 | position.coords.longitude); | |
ac6286bd RK |
971 | if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 || |
972 | Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) { | |
dda55132 RK |
973 | gMap.pos.x = posCoord.x; |
974 | gMap.pos.y = posCoord.y; | |
ac6286bd | 975 | gMap.draw(); // This draws the current point as well. |
b054bd48 RK |
976 | redrawn = true; |
977 | } | |
99631a75 | 978 | } |
b054bd48 | 979 | if (!redrawn) |
4b1d0915 | 980 | undrawCurrentLocation(); |
b054bd48 | 981 | drawTrackPoint(position.coords.latitude, position.coords.longitude, true); |
05c21757 | 982 | } |
b054bd48 | 983 | drawCurrentLocation(tPoint); |
55c4a0b7 RK |
984 | }, |
985 | function(error) { | |
986 | // Ignore erros for the moment, but this is good for debugging. | |
987 | // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors | |
915d4271 RK |
988 | if (gDebug) |
989 | console.log(error.message); | |
55c4a0b7 RK |
990 | }, |
991 | {enableHighAccuracy: true} | |
992 | ); | |
993 | } | |
994 | } | |
995 | ||
996 | function endTracking() { | |
68afcd96 RK |
997 | if (gActionLabel.textContent) { |
998 | gActionLabel.textContent = ""; | |
999 | gAction.style.display = "none"; | |
1000 | } | |
55c4a0b7 | 1001 | if (gGeoWatchID) { |
4b12da3a | 1002 | gGeolocation.clearWatch(gGeoWatchID); |
55c4a0b7 RK |
1003 | } |
1004 | } | |
993fd081 RK |
1005 | |
1006 | function clearTrack() { | |
1007 | gTrack = []; | |
1008 | gTrackStore.clear(); | |
6ddefbf9 | 1009 | drawTrack(); |
993fd081 | 1010 | } |
a8634d37 RK |
1011 | |
1012 | var gTileService = { | |
1013 | objStore: "tilecache", | |
1014 | ||
5d67397a | 1015 | ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms) |
3431f496 | 1016 | |
a8634d37 RK |
1017 | get: function(aStyle, aCoords, aCallback) { |
1018 | var norm = normalizeCoords(aCoords); | |
1019 | var dbkey = aStyle + "::" + norm.x + "," + norm.y + "," + norm.z; | |
1020 | this.getDBCache(dbkey, function(aResult, aEvent) { | |
1021 | if (aResult) { | |
1022 | // We did get a cached object. | |
e8525b46 | 1023 | aCallback(aResult.image, aStyle, aCoords, dbkey); |
3431f496 | 1024 | // Look at the timestamp and return if it's not too old. |
5d67397a | 1025 | if (aResult.timestamp + gTileService.ageLimit > Date.now()) |
3431f496 RK |
1026 | return; |
1027 | // Reload cached tile otherwise. | |
5d67397a RK |
1028 | var oldDate = new Date(aResult.timestamp); |
1029 | console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString()); | |
a8634d37 | 1030 | } |
3431f496 RK |
1031 | // Retrieve image from the web and store it in the cache. |
1032 | var XHR = new XMLHttpRequest(); | |
1033 | XHR.open("GET", | |
1034 | gMapStyles[aStyle].url | |
1035 | .replace("{x}", norm.x) | |
1036 | .replace("{y}", norm.y) | |
1037 | .replace("{z}", norm.z) | |
1038 | .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2))) | |
1039 | .replace("[1-4]", 1 + Math.floor(Math.random() * 3)), | |
1040 | true); | |
1041 | XHR.responseType = "blob"; | |
1042 | XHR.addEventListener("load", function () { | |
1043 | if (XHR.status === 200) { | |
1044 | var blob = XHR.response; | |
e8525b46 | 1045 | aCallback(blob, aStyle, aCoords, dbkey); |
6d7cdcf6 | 1046 | gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()}); |
3431f496 RK |
1047 | } |
1048 | }, false); | |
1049 | XHR.send(); | |
a8634d37 RK |
1050 | }); |
1051 | }, | |
1052 | ||
1053 | getDBCache: function(aKey, aCallback) { | |
1054 | if (!mainDB) | |
1055 | return; | |
1056 | var transaction = mainDB.transaction([this.objStore]); | |
1057 | var request = transaction.objectStore(this.objStore).get(aKey); | |
1058 | request.onsuccess = function(event) { | |
1059 | aCallback(request.result, event); | |
1060 | }; | |
1061 | request.onerror = function(event) { | |
1062 | // Errors can be handled here. | |
1063 | aCallback(undefined, event); | |
1064 | }; | |
1065 | }, | |
1066 | ||
1067 | setDBCache: function(aKey, aValue, aCallback) { | |
1068 | if (!mainDB) | |
1069 | return; | |
1070 | var success = false; | |
1071 | var transaction = mainDB.transaction([this.objStore], "readwrite"); | |
1072 | var objStore = transaction.objectStore(this.objStore); | |
1073 | var request = objStore.put(aValue, aKey); | |
1074 | request.onsuccess = function(event) { | |
1075 | success = true; | |
1076 | if (aCallback) | |
1077 | aCallback(success, event); | |
1078 | }; | |
1079 | request.onerror = function(event) { | |
1080 | // Errors can be handled here. | |
1081 | if (aCallback) | |
1082 | aCallback(success, event); | |
1083 | }; | |
1084 | }, | |
1085 | ||
1086 | unsetDBCache: function(aKey, aCallback) { | |
1087 | if (!mainDB) | |
1088 | return; | |
1089 | var success = false; | |
1090 | var transaction = mainDB.transaction([this.objStore], "readwrite"); | |
1091 | var request = transaction.objectStore(this.objStore).delete(aKey); | |
1092 | request.onsuccess = function(event) { | |
1093 | success = true; | |
1094 | if (aCallback) | |
1095 | aCallback(success, event); | |
1096 | }; | |
1097 | request.onerror = function(event) { | |
1098 | // Errors can be handled here. | |
1099 | if (aCallback) | |
1100 | aCallback(success, event); | |
1101 | } | |
3431f496 RK |
1102 | }, |
1103 | ||
1104 | clearDB: function(aCallback) { | |
1105 | if (!mainDB) | |
1106 | return; | |
1107 | var success = false; | |
1108 | var transaction = mainDB.transaction([this.objStore], "readwrite"); | |
1109 | var request = transaction.objectStore(this.objStore).clear(); | |
1110 | request.onsuccess = function(event) { | |
1111 | success = true; | |
1112 | if (aCallback) | |
1113 | aCallback(success, event); | |
1114 | }; | |
1115 | request.onerror = function(event) { | |
1116 | // Errors can be handled here. | |
1117 | if (aCallback) | |
1118 | aCallback(success, event); | |
1119 | } | |
a8634d37 RK |
1120 | } |
1121 | }; |