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