hide copyright field as well, but make sure it's shown when we change maps and might...
[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   showUI();
149 }
150
151 function zoomIn() {
152   if (gPos.z < gMaxZoom) {
153     gPos.z++;
154     drawMap();
155   }
156 }
157
158 function zoomOut() {
159   if (gPos.z > 0) {
160     gPos.z--;
161     drawMap();
162   }
163 }
164
165 function gps2xy(aLatitude, aLongitude) {
166   var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
167   var convLat = aLatitude * Math.PI / 180;
168   var rawY = (1 - Math.log(Math.tan(convLat) +
169                            1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
170   var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
171   return {x: Math.round(rawX),
172           y: Math.round(rawY)};
173 }
174
175 function xy2gps(aX, aY) {
176   var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
177   var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
178   return {latitude: 180 / Math.PI *
179                     Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
180           longitude: aX / maxZoomFactor * 360 - 180};
181 }
182
183 function setMapStyle() {
184   var mapSel = document.getElementById("mapSelector");
185   if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
186     gActiveMap = mapSel.value;
187     gTiles = {};
188     document.getElementById("copyright").innerHTML =
189         gMapStyles[gActiveMap].copyright;
190     showUI();
191     drawMap();
192   }
193 }
194
195 // A sane mod function that works for negative numbers.
196 // Returns a % b.
197 function mod(a, b) {
198   return ((a % b) + b) % b;
199 }
200
201 function normaliseIndices(x, y, z) {
202   var zoomFactor = Math.pow(2, z);
203   return {x: mod(x, zoomFactor),
204           y: mod(y, zoomFactor),
205           z: z};
206 }
207
208 function tileURL(x, y, z) {
209   var norm = normaliseIndices(x, y, z);
210   return gMapStyles[gActiveMap].url
211          .replace("{x}", norm.x)
212          .replace("{y}", norm.y)
213          .replace("{z}", norm.z)
214          .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)));
215 }
216
217 // Returns true if the tile is outside the current view.
218 function isOutsideWindow(t) {
219   var pos = decodeIndex(t);
220   var x = pos[0];
221   var y = pos[1];
222   var z = pos[2];
223
224   var zoomFactor = Math.pow(2, gMaxZoom - z);
225   var wid = gCanvas.width * zoomFactor;
226   var ht = gCanvas.height * zoomFactor;
227
228   x *= zoomFactor;
229   y *= zoomFactor;
230
231   var sz = gTileSize * zoomFactor;
232   if (x > gPos.x + wid / 2 || y > gPos.y + ht / 2 ||
233       x + sz < gPos.x - wid / 2 || y - sz < gPos.y - ht / 2)
234     return true;
235   return false;
236 }
237
238 function encodeIndex(x, y, z) {
239   var norm = normaliseIndices(x, y, z);
240   return norm.x + "," + norm.y + "," + norm.z;
241 }
242
243 function decodeIndex(encodedIdx) {
244   return encodedIdx.split(",", 3);
245 }
246
247 function drawMap() {
248   // Go through all the currently loaded tiles. If we don't want any of them remove them.
249   // for (t in gTiles) {
250   //   if (isOutsideWindow(t))
251   //     delete gTiles[t];
252   // }
253   document.getElementById("zoomLevel").textContent = gPos.z;
254   gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
255   var wid = gCanvas.width * gZoomFactor; // Width in level 18 pixels.
256   var ht = gCanvas.height * gZoomFactor; // Height in level 18 pixels.
257   var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
258
259   var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
260   var yMin = gPos.y - ht / 2;
261   var xMax = gPos.x + wid / 2;
262   var yMax = gPos.y + ht / 2;
263
264   if (gMapPrefsLoaded && mainDB)
265     gPrefs.set("position", gPos);
266
267   // Go through all the tiles we want.
268   // If any of them aren't loaded or being loaded, do so.
269   for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
270     for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
271       var xoff = (x * size - xMin) / gZoomFactor;
272       var yoff = (y * size - yMin) / gZoomFactor;
273       var tileKey = encodeIndex(x, y, gPos.z);
274       if (gTiles[tileKey] && gTiles[tileKey].complete) {
275         // Round here is **CRUCIAL** otherwise the images are filtered
276         // and the performance sucks (more than expected).
277         gContext.drawImage(gTiles[tileKey], Math.round(xoff), Math.round(yoff));
278       }
279       else {
280         if (!gTiles[tileKey]) {
281           gTiles[tileKey] = new Image();
282           gTiles[tileKey].src = tileURL(x, y, gPos.z);
283           gTiles[tileKey].onload = function() {
284             // TODO: Just render this tile where it should be.
285             // context.drawImage(gTiles[tileKey], Math.round(xoff), Math.round(yoff)); // Doesn't work for some reason.
286             drawMap();
287           }
288         }
289         gContext.drawImage(gLoadingTile, Math.round(xoff), Math.round(yoff));
290       }
291     }
292   }
293   if (gTrack.length) {
294     gLastDrawnPoint = null;
295     for (var i = 0; i < gTrack.length; i++) {
296       drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
297                      (i + 1 >= gTrack.length));
298     }
299   }
300 }
301
302 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
303   var trackpoint = gps2xy(aLatitude, aLongitude);
304   // lastPoint is for optimizing (not actually executing the draw until the last)
305   trackpoint.optimized = (lastPoint === false);
306
307   if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
308     gContext.strokeStyle = "#FF0000";
309     gContext.fillStyle = gContext.strokeStyle;
310     gContext.lineWidth = 2;
311     gContext.lineCap = "round";
312     gContext.lineJoin = "round";
313   }
314   if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
315     // This breaks optimiziation, so make sure to close path and reset optimization.
316     if (gLastDrawnPoint && gLastDrawnPoint.optimized)
317       gContext.stroke();
318     gContext.beginPath();
319     trackpoint.optimized = false;
320     gContext.arc(Math.round((trackpoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
321                  Math.round((trackpoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2),
322                  gContext.lineWidth, 0, Math.PI * 2, false);
323     gContext.fill();
324   }
325   else {
326     if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
327       gContext.beginPath();
328       gContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
329                       Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2));
330     }
331     gContext.lineTo(Math.round((trackpoint.x - gPos.x) / gZoomFactor + gCanvas.width / 2),
332                     Math.round((trackpoint.y - gPos.y) / gZoomFactor + gCanvas.height / 2));
333     if (!trackpoint.optimized)
334       gContext.stroke();
335   }
336   gLastDrawnPoint = trackpoint;
337 }
338
339 var mapEvHandler = {
340   handleEvent: function(aEvent) {
341     var touchEvent = aEvent.type.indexOf('touch') != -1;
342
343     // Bail out on unwanted map moves, but not zoom-changing events.
344     if (aEvent.type != "DOMMouseScroll" && aEvent.type != "mousewheel") {
345       // Bail out if this is neither a touch nor left-click.
346       if (!touchEvent && aEvent.button != 0)
347         return;
348
349       // Bail out if the started touch can't be found.
350       if (touchEvent && gDragging &&
351           !aEvent.changedTouches.identifiedTouch(gDragTouchID))
352         return;
353     }
354
355     var coordObj = touchEvent ?
356                    aEvent.changedTouches.identifiedTouch(gDragTouchID) :
357                    aEvent;
358
359     switch (aEvent.type) {
360       case "mousedown":
361       case "touchstart":
362         if (touchEvent) {
363           gDragTouchID = aEvent.changedTouches.item(0).identifier;
364           coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
365         }
366         var x = coordObj.clientX - gCanvas.offsetLeft;
367         var y = coordObj.clientY - gCanvas.offsetTop;
368
369         if (touchEvent || aEvent.button === 0) {
370           gDragging = true;
371         }
372         gLastMouseX = x;
373         gLastMouseY = y;
374         showUI();
375         break;
376       case "mousemove":
377       case "touchmove":
378         var x = coordObj.clientX - gCanvas.offsetLeft;
379         var y = coordObj.clientY - gCanvas.offsetTop;
380         if (gDragging === true) {
381           var dX = x - gLastMouseX;
382           var dY = y - gLastMouseY;
383           gPos.x -= dX * gZoomFactor;
384           gPos.y -= dY * gZoomFactor;
385           drawMap();
386           showUI();
387         }
388         gLastMouseX = x;
389         gLastMouseY = y;
390         break;
391       case "mouseup":
392       case "touchend":
393         gDragging = false;
394         showUI();
395         break;
396       case "mouseout":
397       case "touchcancel":
398       case "touchleave":
399         //gDragging = false;
400         break;
401       case "DOMMouseScroll":
402       case "mousewheel":
403         var delta = 0;
404         if (aEvent.wheelDelta) {
405           delta = aEvent.wheelDelta / 120;
406           if (window.opera)
407             delta = -delta;
408         }
409         else if (aEvent.detail) {
410           delta = -aEvent.detail / 3;
411         }
412
413         // Calculate new center of the map - same point stays under the mouse.
414         // This means that the pixel distance between the old center and point
415         // must equal the pixel distance of the new center and that point.
416         var x = coordObj.clientX - gCanvas.offsetLeft;
417         var y = coordObj.clientY - gCanvas.offsetTop;
418         // Debug output: "coordinates" of the point the mouse was over.
419         /*
420         var ptCoord = {x: gPos.x + (x - gCanvas.width / 2) * gZoomFactor,
421                        y: gPos.y + (x - gCanvas.height / 2) * gZoomFactor};
422         var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
423         var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
424         document.getElementById("debug").textContent =
425             ptCoord.x + "/" + ptCoord.y + " - " +
426             gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
427             pt2Coord.x + "/" + pt2Coord.y;
428         */
429         // Zoom factor after this action.
430         var newZoomFactor = Math.pow(2, gMaxZoom - gPos.z + (delta > 0 ? -1 : 1));
431         gPos.x -= (x - gCanvas.width / 2) * (newZoomFactor - gZoomFactor);
432         gPos.y -= (y - gCanvas.height / 2) * (newZoomFactor - gZoomFactor);
433
434         if (delta > 0)
435           zoomIn();
436         else if (delta < 0)
437           zoomOut();
438         break;
439     }
440   }
441 };
442
443 var geofake = {
444   tracking: false,
445   lastPos: {x: undefined, y: undefined},
446   watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
447     this.tracking = true;
448     var watchCall = function() {
449       // calc new position in lat/lon degrees
450       // 90° on Earth surface are ~10,000 km at the equator,
451       // so try moving at most 10m at a time
452       if (geofake.lastPos.x)
453         geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
454       else
455         geofake.lastPos.x = 48.208174
456       if (geofake.lastPos.y)
457         geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
458       else
459         geofake.lastPos.y = 16.373819
460       aSuccessCallback({timestamp: Date.now(),
461                         coords: {latitude: geofake.lastPos.x,
462                                  longitude: geofake.lastPos.y,
463                                  accuracy: 20}});
464       if (geofake.tracking)
465         setTimeout(watchCall, 1000);
466     };
467     setTimeout(watchCall, 1000);
468     return "foo";
469   },
470   clearWatch: function(aID) {
471     this.tracking = false;
472   }
473 }
474
475 function setCentering(aCheckbox) {
476   if (gMapPrefsLoaded && mainDB)
477     gPrefs.set("center_map", aCheckbox.checked);
478   gCenterPosition = aCheckbox.checked;
479 }
480
481 function setTracking(aCheckbox) {
482   if (gMapPrefsLoaded && mainDB)
483     gPrefs.set("tracking_enabled", aCheckbox.checked);
484   if (aCheckbox.checked)
485     startTracking();
486   else
487     endTracking();
488 }
489
490 function startTracking() {
491   var loopCnt = 0;
492   var getStoredTrack = function() {
493     if (mainDB)
494       gTrackStore.getList(function(aTPoints) {
495         if (gDebug)
496           document.getElementById("debug").textContent = aTPoints.length + " points loaded.";
497         if (aTPoints.length) {
498           gTrack = aTPoints;
499         }
500       });
501     else
502       setTimeout(getStoredTrack, 100);
503     loopCnt++;
504     if (loopCnt > 20)
505       return;
506   };
507   getStoredTrack();
508   if (gGeolocation) {
509     gGeoWatchID = gGeolocation.watchPosition(
510       function(position) {
511         // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
512         var tPoint = {time: position.timestamp,
513                       coords: {latitude: position.coords.latitude,
514                                longitude: position.coords.longitude,
515                                altitude: position.coords.altitude,
516                                accuracy: position.coords.accuracy,
517                                altitudeAccuracy: position.coords.altitudeAccuracy,
518                                heading: position.coords.heading,
519                                speed: position.coords.speed},
520                       beginSegment: !gLastTrackPoint};
521         gLastTrackPoint = tPoint;
522         gTrack.push(tPoint);
523         try { gTrackStore.push(tPoint); } catch(e) {}
524         var redrawn = false;
525         if (gCenterPosition) {
526           var posCoord = gps2xy(position.coords.latitude,
527                                 position.coords.longitude);
528           if (Math.abs(gPos.x - posCoord.x) > gCanvas.width * gZoomFactor / 4 ||
529               Math.abs(gPos.y - posCoord.y) > gCanvas.height * gZoomFactor / 4) {
530             gPos.x = posCoord.x;
531             gPos.y = posCoord.y;
532             drawMap(); // This draws the current point as well.
533             redrawn = true;
534           }
535         }
536         if (!redrawn)
537           drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
538       },
539       function(error) {
540         // Ignore erros for the moment, but this is good for debugging.
541         // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
542         document.getElementById("debug").textContent = error.message;
543       },
544       {enableHighAccuracy: true}
545     );
546   }
547 }
548
549 function endTracking() {
550   if (gGeoWatchID) {
551     gGeolocation.clearWatch(gGeoWatchID);
552   }
553 }
554
555 function clearTrack() {
556   gTrack = [];
557   gTrackStore.clear();
558   drawMap();
559 }