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