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