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