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