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