support full screen mode
[lantea.git] / js / map.js
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/. */
4
5 var gCanvas, gContext, gGeolocation;
6 var gDebug = false;
7
8 var gTileSize = 256;
9 var gMaxZoom = 18; // The minimum is 0.
10
11 var gMapStyles = {
12   // OSM tile usage policy: http://wiki.openstreetmap.org/wiki/Tile_usage_policy
13   // Find some more OSM ones at http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers
14   osm_mapnik:
15     {name: "OpenStreetMap (Mapnik)",
16      url: "http://tile.openstreetmap.org/{z}/{x}/{y}.png",
17      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>'},
18   osm_cyclemap:
19     {name: "Cycle Map (OSM)",
20      url: "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
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>'},
22   osm_transmap:
23     {name: "Transport Map (OSM)",
24      url: "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png",
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>'},
26   mapquest_open:
27     {name: "MapQuest OSM",
28      url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png",
29      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>.'},
30   mapquest_aerial:
31     {name: "MapQuest Open Aerial",
32      url: "http://oatile[1-4].mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg",
33      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.'},
34   opengeoserver_arial:
35     {name: "OpenGeoServer Aerial",
36      url: "http://services.opengeoserver.org/tiles/1.0.0/globe.aerial_EPSG3857/{z}/{x}/{y}.png?origin=nw",
37      copyright: 'Tiles by <a href="http://www.opengeoserver.org/">OpenGeoServer.org</a>, <a href="https://creativecommons.org/licenses/by/3.0/at/">CC-BY 3.0 AT</a>.'},
38   google_map:
39     {name: "Google Maps",
40      url: " http://mt1.google.com/vt/x={x}&y={y}&z={z}",
41      copyright: 'Map data and imagery &copy; <a href="http://maps.google.com/">Google</a>'},
42 };
43 var gActiveMap = "osm_mapnik";
44
45 var gPos = {x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
46             y: 23670000.0, // The range is 0-67108864 (2^gMaxZoom * gTileSize)
47             z: 5}; // This could be fractional if supported being between zoom levels.
48
49 var gLastMouseX = 0;
50 var gLastMouseY = 0;
51 var gZoomFactor;
52
53 // Used as an associative array.
54 // The keys have to be strings, ours will be "xindex,yindex,zindex" e.g. "13,245,12".
55 var gTiles = {};
56 var gLoadingTile;
57
58 var gMapPrefsLoaded = false;
59
60 var gDragging = false;
61 var gDragTouchID;
62
63 var gGeoWatchID;
64 var gTrack = [];
65 var gLastTrackPoint, gLastDrawnPoint;
66 var gCenterPosition = true;
67
68 function initMap() {
69   gGeolocation = navigator.geolocation;
70   gCanvas = document.getElementById("map");
71   gContext = gCanvas.getContext("2d");
72   if (!gActiveMap)
73     gActiveMap = "osm_mapnik";
74
75   //gDebug = true;
76   if (gDebug) {
77     gGeolocation = geofake;
78     var hiddenList = document.getElementsByClassName("debugHide");
79     // last to first - list of elements with that class is changing!
80     for (var i = hiddenList.length - 1; i >= 0; i--) {
81       hiddenList[i].classList.remove("debugHide");
82     }
83   }
84
85   var loopCnt = 0;
86   var getPersistentPrefs = function() {
87     if (mainDB) {
88       gPrefs.get("position", function(aValue) {
89         if (aValue) {
90           gPos = aValue;
91           drawMap();
92         }
93       });
94       gPrefs.get("center_map", function(aValue) {
95         if (aValue === undefined)
96           document.getElementById("centerCheckbox").checked = true;
97         else
98           document.getElementById("centerCheckbox").checked = aValue;
99         setCentering(document.getElementById("centerCheckbox"));
100       });
101       gPrefs.get("tracking_enabled", function(aValue) {
102         if (aValue === undefined)
103           document.getElementById("trackCheckbox").checked = true;
104         else
105           document.getElementById("trackCheckbox").checked = aValue;
106         setTracking(document.getElementById("trackCheckbox"));
107       });
108       gMapPrefsLoaded = true;
109     }
110     else
111       setTimeout(getPersistentPrefs, 100);
112     loopCnt++;
113     if (loopCnt > 20) {
114       gMapPrefsLoaded = true;
115       return;
116     }
117   };
118   getPersistentPrefs();
119
120   gCanvas.addEventListener("mouseup", mapEvHandler, false);
121   gCanvas.addEventListener("mousemove", mapEvHandler, false);
122   gCanvas.addEventListener("mousedown", mapEvHandler, false);
123   gCanvas.addEventListener("mouseout", mapEvHandler, false);
124
125   gCanvas.addEventListener("touchstart", mapEvHandler, false);
126   gCanvas.addEventListener("touchmove", mapEvHandler, false);
127   gCanvas.addEventListener("touchend", mapEvHandler, false);
128   gCanvas.addEventListener("touchcancel", mapEvHandler, false);
129   gCanvas.addEventListener("touchleave", mapEvHandler, false);
130
131   // XXX deprecated? see https://groups.google.com/forum/?fromgroups#!topic/mozilla.dev.planning/kuhrORubaRY[1-25]
132   gCanvas.addEventListener("DOMMouseScroll", mapEvHandler, false);
133   gCanvas.addEventListener("mousewheel", mapEvHandler, false);
134
135   document.getElementById("copyright").innerHTML =
136       gMapStyles[gActiveMap].copyright;
137
138   gLoadingTile = new Image();
139   gLoadingTile.src = "style/loading.png";
140 }
141
142 function resizeAndDraw() {
143   var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
144   var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
145
146   var canvasWidth = viewportWidth - 2;
147   var canvasHeight = viewportHeight - 2;
148   gCanvas.style.position = "fixed";
149   gCanvas.width = canvasWidth;
150   gCanvas.height = canvasHeight;
151   drawMap();
152   showUI();
153 }
154
155 function zoomIn() {
156   if (gPos.z < gMaxZoom) {
157     gPos.z++;
158     drawMap();
159   }
160 }
161
162 function zoomOut() {
163   if (gPos.z > 0) {
164     gPos.z--;
165     drawMap();
166   }
167 }
168
169 function gps2xy(aLatitude, aLongitude) {
170   var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
171   var convLat = aLatitude * Math.PI / 180;
172   var rawY = (1 - Math.log(Math.tan(convLat) +
173                            1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
174   var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
175   return {x: Math.round(rawX),
176           y: Math.round(rawY)};
177 }
178
179 function xy2gps(aX, aY) {
180   var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
181   var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
182   return {latitude: 180 / Math.PI *
183                     Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
184           longitude: aX / maxZoomFactor * 360 - 180};
185 }
186
187 function setMapStyle() {
188   var mapSel = document.getElementById("mapSelector");
189   if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
190     gActiveMap = mapSel.value;
191     gTiles = {};
192     document.getElementById("copyright").innerHTML =
193         gMapStyles[gActiveMap].copyright;
194     showUI();
195     drawMap();
196   }
197 }
198
199 // A sane mod function that works for negative numbers.
200 // Returns a % b.
201 function mod(a, b) {
202   return ((a % b) + b) % b;
203 }
204
205 function normaliseIndices(x, y, z) {
206   var zoomFactor = Math.pow(2, z);
207   return {x: mod(x, zoomFactor),
208           y: mod(y, zoomFactor),
209           z: z};
210 }
211
212 function tileURL(x, y, z) {
213   var norm = normaliseIndices(x, y, z);
214   return gMapStyles[gActiveMap].url
215          .replace("{x}", norm.x)
216          .replace("{y}", norm.y)
217          .replace("{z}", norm.z)
218          .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
219          .replace("[1-4]", 1 + Math.floor(Math.random() * 3));
220 }
221
222 // Returns true if the tile is outside the current view.
223 function isOutsideWindow(t) {
224   var pos = decodeIndex(t);
225   var x = pos[0];
226   var y = pos[1];
227   var z = pos[2];
228
229   var zoomFactor = Math.pow(2, gMaxZoom - z);
230   var wid = gCanvas.width * zoomFactor;
231   var ht = gCanvas.height * zoomFactor;
232
233   x *= zoomFactor;
234   y *= zoomFactor;
235
236   var sz = gTileSize * zoomFactor;
237   if (x > gPos.x + wid / 2 || y > gPos.y + ht / 2 ||
238       x + sz < gPos.x - wid / 2 || y - sz < gPos.y - ht / 2)
239     return true;
240   return false;
241 }
242
243 function encodeIndex(x, y, z) {
244   var norm = normaliseIndices(x, y, z);
245   return norm.x + "," + norm.y + "," + norm.z;
246 }
247
248 function decodeIndex(encodedIdx) {
249   return encodedIdx.split(",", 3);
250 }
251
252 function drawMap() {
253   // Go through all the currently loaded tiles. If we don't want any of them remove them.
254   // for (t in gTiles) {
255   //   if (isOutsideWindow(t))
256   //     delete gTiles[t];
257   // }
258   document.getElementById("zoomLevel").textContent = gPos.z;
259   gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
260   var wid = gCanvas.width * gZoomFactor; // Width in level 18 pixels.
261   var ht = gCanvas.height * gZoomFactor; // Height in level 18 pixels.
262   var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
263
264   var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
265   var yMin = gPos.y - ht / 2;
266   var xMax = gPos.x + wid / 2;
267   var yMax = gPos.y + ht / 2;
268
269   if (gMapPrefsLoaded && mainDB)
270     gPrefs.set("position", gPos);
271
272   // Go through all the tiles we want.
273   // If any of them aren't loaded or being loaded, do so.
274   for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
275     for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
276       var xoff = (x * size - xMin) / gZoomFactor;
277       var yoff = (y * size - yMin) / gZoomFactor;
278       var tileKey = encodeIndex(x, y, gPos.z);
279       if (gTiles[tileKey] && gTiles[tileKey].complete) {
280         // Round here is **CRUCIAL** otherwise the images are filtered
281         // and the performance sucks (more than expected).
282         gContext.drawImage(gTiles[tileKey], Math.round(xoff), Math.round(yoff));
283       }
284       else {
285         if (!gTiles[tileKey]) {
286           gTiles[tileKey] = new Image();
287           gTiles[tileKey].src = tileURL(x, y, gPos.z);
288           gTiles[tileKey].onload = function() {
289             // TODO: Just render this tile where it should be.
290             // context.drawImage(gTiles[tileKey], Math.round(xoff), Math.round(yoff)); // Doesn't work for some reason.
291             drawMap();
292           }
293         }
294         gContext.drawImage(gLoadingTile, Math.round(xoff), Math.round(yoff));
295       }
296     }
297   }
298   if (gTrack.length) {
299     gLastDrawnPoint = null;
300     for (var i = 0; i < gTrack.length; i++) {
301       drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
302                      (i + 1 >= gTrack.length));
303     }
304   }
305 }
306
307 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
308   var trackpoint = gps2xy(aLatitude, aLongitude);
309   // lastPoint is for optimizing (not actually executing the draw until the last)
310   trackpoint.optimized = (lastPoint === false);
311
312   if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
313     gContext.strokeStyle = "#FF0000";
314     gContext.fillStyle = gContext.strokeStyle;
315     gContext.lineWidth = 2;
316     gContext.lineCap = "round";
317     gContext.lineJoin = "round";
318   }
319   if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
320     // This breaks optimiziation, so make sure to close path and reset optimization.
321     if (gLastDrawnPoint && gLastDrawnPoint.optimized)
322       gContext.stroke();
323     gContext.beginPath();
324     trackpoint.optimized = false;
325     gContext.arc(Math.round((trackpoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
326                  Math.round((trackpoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2),
327                  gContext.lineWidth, 0, Math.PI * 2, false);
328     gContext.fill();
329   }
330   else {
331     if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
332       gContext.beginPath();
333       gContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
334                       Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2));
335     }
336     gContext.lineTo(Math.round((trackpoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
337                     Math.round((trackpoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2));
338     if (!trackpoint.optimized)
339       gContext.stroke();
340   }
341   gLastDrawnPoint = trackpoint;
342 }
343
344 var mapEvHandler = {
345   handleEvent: function(aEvent) {
346     var touchEvent = aEvent.type.indexOf('touch') != -1;
347
348     // Bail out on unwanted map moves, but not zoom-changing events.
349     if (aEvent.type != "DOMMouseScroll" && aEvent.type != "mousewheel") {
350       // Bail out if this is neither a touch nor left-click.
351       if (!touchEvent && aEvent.button != 0)
352         return;
353
354       // Bail out if the started touch can't be found.
355       if (touchEvent && gDragging &&
356           !aEvent.changedTouches.identifiedTouch(gDragTouchID))
357         return;
358     }
359
360     var coordObj = touchEvent ?
361                    aEvent.changedTouches.identifiedTouch(gDragTouchID) :
362                    aEvent;
363
364     switch (aEvent.type) {
365       case "mousedown":
366       case "touchstart":
367         if (touchEvent) {
368           gDragTouchID = aEvent.changedTouches.item(0).identifier;
369           coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
370         }
371         var x = coordObj.clientX - gCanvas.offsetLeft;
372         var y = coordObj.clientY - gCanvas.offsetTop;
373
374         if (touchEvent || aEvent.button === 0) {
375           gDragging = true;
376         }
377         gLastMouseX = x;
378         gLastMouseY = y;
379         showUI();
380         break;
381       case "mousemove":
382       case "touchmove":
383         var x = coordObj.clientX - gCanvas.offsetLeft;
384         var y = coordObj.clientY - gCanvas.offsetTop;
385         if (gDragging === true) {
386           var dX = x - gLastMouseX;
387           var dY = y - gLastMouseY;
388           gPos.x -= dX * gZoomFactor;
389           gPos.y -= dY * gZoomFactor;
390           drawMap();
391           showUI();
392         }
393         gLastMouseX = x;
394         gLastMouseY = y;
395         break;
396       case "mouseup":
397       case "touchend":
398         gDragging = false;
399         showUI();
400         break;
401       case "mouseout":
402       case "touchcancel":
403       case "touchleave":
404         //gDragging = false;
405         break;
406       case "DOMMouseScroll":
407       case "mousewheel":
408         var delta = 0;
409         if (aEvent.wheelDelta) {
410           delta = aEvent.wheelDelta / 120;
411           if (window.opera)
412             delta = -delta;
413         }
414         else if (aEvent.detail) {
415           delta = -aEvent.detail / 3;
416         }
417
418         // Calculate new center of the map - same point stays under the mouse.
419         // This means that the pixel distance between the old center and point
420         // must equal the pixel distance of the new center and that point.
421         var x = coordObj.clientX - gCanvas.offsetLeft;
422         var y = coordObj.clientY - gCanvas.offsetTop;
423         // Debug output: "coordinates" of the point the mouse was over.
424         /*
425         var ptCoord = {x: gPos.x + (x - gCanvas.width / 2) * gZoomFactor,
426                        y: gPos.y + (x - gCanvas.height / 2) * gZoomFactor};
427         var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
428         var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
429         document.getElementById("debug").textContent =
430             ptCoord.x + "/" + ptCoord.y + " - " +
431             gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
432             pt2Coord.x + "/" + pt2Coord.y;
433         */
434         // Zoom factor after this action.
435         var newZoomFactor = Math.pow(2, gMaxZoom - gPos.z + (delta > 0 ? -1 : 1));
436         gPos.x -= (x - gCanvas.width / 2) * (newZoomFactor - gZoomFactor);
437         gPos.y -= (y - gCanvas.height / 2) * (newZoomFactor - gZoomFactor);
438
439         if (delta > 0)
440           zoomIn();
441         else if (delta < 0)
442           zoomOut();
443         break;
444     }
445   }
446 };
447
448 var geofake = {
449   tracking: false,
450   lastPos: {x: undefined, y: undefined},
451   watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
452     this.tracking = true;
453     var watchCall = function() {
454       // calc new position in lat/lon degrees
455       // 90° on Earth surface are ~10,000 km at the equator,
456       // so try moving at most 10m at a time
457       if (geofake.lastPos.x)
458         geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
459       else
460         geofake.lastPos.x = 48.208174
461       if (geofake.lastPos.y)
462         geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
463       else
464         geofake.lastPos.y = 16.373819
465       aSuccessCallback({timestamp: Date.now(),
466                         coords: {latitude: geofake.lastPos.x,
467                                  longitude: geofake.lastPos.y,
468                                  accuracy: 20}});
469       if (geofake.tracking)
470         setTimeout(watchCall, 1000);
471     };
472     setTimeout(watchCall, 1000);
473     return "foo";
474   },
475   clearWatch: function(aID) {
476     this.tracking = false;
477   }
478 }
479
480 function setCentering(aCheckbox) {
481   if (gMapPrefsLoaded && mainDB)
482     gPrefs.set("center_map", aCheckbox.checked);
483   gCenterPosition = aCheckbox.checked;
484 }
485
486 function setTracking(aCheckbox) {
487   if (gMapPrefsLoaded && mainDB)
488     gPrefs.set("tracking_enabled", aCheckbox.checked);
489   if (aCheckbox.checked)
490     startTracking();
491   else
492     endTracking();
493 }
494
495 function startTracking() {
496   var loopCnt = 0;
497   var getStoredTrack = function() {
498     if (mainDB)
499       gTrackStore.getList(function(aTPoints) {
500         if (gDebug)
501           document.getElementById("debug").textContent = aTPoints.length + " points loaded.";
502         if (aTPoints.length) {
503           gTrack = aTPoints;
504         }
505       });
506     else
507       setTimeout(getStoredTrack, 100);
508     loopCnt++;
509     if (loopCnt > 20)
510       return;
511   };
512   getStoredTrack();
513   if (gGeolocation) {
514     gGeoWatchID = gGeolocation.watchPosition(
515       function(position) {
516         // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
517         var tPoint = {time: position.timestamp,
518                       coords: {latitude: position.coords.latitude,
519                                longitude: position.coords.longitude,
520                                altitude: position.coords.altitude,
521                                accuracy: position.coords.accuracy,
522                                altitudeAccuracy: position.coords.altitudeAccuracy,
523                                heading: position.coords.heading,
524                                speed: position.coords.speed},
525                       beginSegment: !gLastTrackPoint};
526         gLastTrackPoint = tPoint;
527         gTrack.push(tPoint);
528         try { gTrackStore.push(tPoint); } catch(e) {}
529         var redrawn = false;
530         if (gCenterPosition) {
531           var posCoord = gps2xy(position.coords.latitude,
532                                 position.coords.longitude);
533           if (Math.abs(gPos.x - posCoord.x) > gCanvas.width * gZoomFactor / 4 ||
534               Math.abs(gPos.y - posCoord.y) > gCanvas.height * gZoomFactor / 4) {
535             gPos.x = posCoord.x;
536             gPos.y = posCoord.y;
537             drawMap(); // This draws the current point as well.
538             redrawn = true;
539           }
540         }
541         if (!redrawn)
542           drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
543       },
544       function(error) {
545         // Ignore erros for the moment, but this is good for debugging.
546         // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
547         document.getElementById("debug").textContent = error.message;
548       },
549       {enableHighAccuracy: true}
550     );
551   }
552 }
553
554 function endTracking() {
555   if (gGeoWatchID) {
556     gGeolocation.clearWatch(gGeoWatchID);
557   }
558 }
559
560 function clearTrack() {
561   gTrack = [];
562   gTrackStore.clear();
563   drawMap();
564 }