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