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