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