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