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