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