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