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