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