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