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