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