dc3ad9c776637595ddbc764b18b111e119dc67ba
[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 gMapCanvas, gMapContext, gTrackCanvas, gTrackContext, gGeolocation;
6 var gDebug = false;
7
8 var gTileSize = 256;
9 var gMaxZoom = 18; // The minimum is 0.
10
11 var gMinTrackAccuracy = 1000; // meters
12 var gTrackWidth = 2; // pixels
13 var gTrackColor = "#FF0000";
14 var gCurLocSize = 6; // pixels
15 var gCurLocColor = "#A00000";
16
17 var gMapStyles = {
18   // OSM tile usage policy: http://wiki.openstreetmap.org/wiki/Tile_usage_policy
19   // Find some more OSM ones at http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers
20   osm_mapnik:
21     {name: "OpenStreetMap (Mapnik)",
22      url: "http://tile.openstreetmap.org/{z}/{x}/{y}.png",
23      copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
24   osm_cyclemap:
25     {name: "Cycle Map (OSM)",
26      url: "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
27      copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
28   osm_transmap:
29     {name: "Transport Map (OSM)",
30      url: "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png",
31      copyright: 'Map data and imagery &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
32   mapquest_open:
33     {name: "MapQuest OSM",
34      url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png",
35      copyright: 'Map data &copy; <a href="http://www.openstreetmap.org/">OpenStreetMap</a> and contributors (<a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>), tiles Courtesy of <a href="http://www.mapquest.com/">MapQuest</a>.'},
36   mapquest_aerial:
37     {name: "MapQuest Open Aerial",
38      url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg",
39      copyright: 'Tiles Courtesy of <a href="http://www.mapquest.com/">MapQuest</a>, portions Courtesy NASA/JPL-Caltech and U.S. Depart. of Agriculture, Farm Service Agency.'},
40   opengeoserver_arial:
41     {name: "OpenGeoServer Aerial",
42      url: "http://services.opengeoserver.org/tiles/1.0.0/globe.aerial_EPSG3857/{z}/{x}/{y}.png?origin=nw",
43      copyright: 'Tiles by <a href="http://www.opengeoserver.org/">OpenGeoServer.org</a>, <a href="https://creativecommons.org/licenses/by/3.0/at/">CC-BY 3.0 AT</a>.'},
44   google_map:
45     {name: "Google Maps",
46      url: " http://mt1.google.com/vt/x={x}&y={y}&z={z}",
47      copyright: 'Map data and imagery &copy; <a href="http://maps.google.com/">Google</a>'},
48 };
49 var gActiveMap = "osm_mapnik";
50
51 var gPos = {x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
52             y: 23670000.0, // The range is 0-67108864 (2^gMaxZoom * gTileSize)
53             z: 5}; // This could be fractional if supported being between zoom levels.
54
55 var gLastMouseX = 0;
56 var gLastMouseY = 0;
57 var gZoomFactor;
58
59 var gLoadingTile;
60
61 var gMapPrefsLoaded = false;
62
63 var gDragging = false;
64 var gDragTouchID, gPinchStartWidth;
65
66 var gGeoWatchID;
67 var gTrack = [];
68 var gLastTrackPoint, gLastDrawnPoint;
69 var gCenterPosition = true;
70
71 var gCurPosMapCache;
72
73 function initMap() {
74   gGeolocation = navigator.geolocation;
75   gMapCanvas = document.getElementById("map");
76   gMapContext = gMapCanvas.getContext("2d");
77   gTrackCanvas = document.getElementById("track");
78   gTrackContext = gTrackCanvas.getContext("2d");
79   if (!gActiveMap)
80     gActiveMap = "osm_mapnik";
81
82   //gDebug = true;
83   if (gDebug) {
84     gGeolocation = geofake;
85     var hiddenList = document.getElementsByClassName("debugHide");
86     // last to first - list of elements with that class is changing!
87     for (var i = hiddenList.length - 1; i >= 0; i--) {
88       hiddenList[i].classList.remove("debugHide");
89     }
90   }
91
92   console.log("map vars set, loading prefs...");
93   loadPrefs();
94 }
95
96 function loadPrefs(aEvent) {
97   if (aEvent && aEvent.type == "prefs-step") {
98     console.log("wait: " + gWaitCounter);
99     if (gWaitCounter == 0) {
100       gAction.removeEventListener(aEvent.type, loadPrefs, false);
101       gMapPrefsLoaded = true;
102       console.log("prefs loaded.");
103
104       gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
105       gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
106       gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
107       gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
108
109       gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
110       gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
111       gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
112       gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
113       gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
114
115       gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
116
117       document.getElementById("body").addEventListener("keydown", mapEvHandler, false);
118
119       document.getElementById("copyright").innerHTML =
120           gMapStyles[gActiveMap].copyright;
121
122       gLoadingTile = new Image();
123       gLoadingTile.src = "style/loading.png";
124       gLoadingTile.onload = function() {
125         var throwEv = new CustomEvent("mapinit-done");
126         gAction.dispatchEvent(throwEv);
127       };
128     }
129   }
130   else {
131     if (aEvent)
132       gAction.removeEventListener(aEvent.type, loadPrefs, false);
133     gAction.addEventListener("prefs-step", loadPrefs, false);
134     gWaitCounter++;
135     gPrefs.get("position", function(aValue) {
136       if (aValue) {
137         gPos = aValue;
138       }
139       gWaitCounter--;
140       var throwEv = new CustomEvent("prefs-step");
141       gAction.dispatchEvent(throwEv);
142     });
143     gWaitCounter++;
144     gPrefs.get("center_map", function(aValue) {
145       if (aValue === undefined)
146         document.getElementById("centerCheckbox").checked = true;
147       else
148         document.getElementById("centerCheckbox").checked = aValue;
149       setCentering(document.getElementById("centerCheckbox"));
150       gWaitCounter--;
151       var throwEv = new CustomEvent("prefs-step");
152       gAction.dispatchEvent(throwEv);
153     });
154     gWaitCounter++;
155     gPrefs.get("tracking_enabled", function(aValue) {
156       if (aValue === undefined)
157         document.getElementById("trackCheckbox").checked = true;
158       else
159         document.getElementById("trackCheckbox").checked = aValue;
160       gWaitCounter--;
161       var throwEv = new CustomEvent("prefs-step");
162       gAction.dispatchEvent(throwEv);
163     });
164     gWaitCounter++;
165     var trackLoadStarted = false;
166     gTrackStore.getListStepped(function(aTPoint) {
167       if (aTPoint) {
168         // Add in front and return new length.
169         var tracklen = gTrack.unshift(aTPoint);
170         // Redraw track every 100 values (initial paint will do first anyhow).
171         if (tracklen % 100 == 0)
172           drawTrack();
173       }
174       else {
175         // Last point received.
176         drawTrack();
177       }
178       if (!trackLoadStarted) {
179         // We have the most recent point, if present, rest will load async.
180         trackLoadStarted = true;
181         gWaitCounter--;
182         var throwEv = new CustomEvent("prefs-step");
183         gAction.dispatchEvent(throwEv);
184       }
185     });
186   }
187 }
188
189 function resizeAndDraw() {
190   var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
191   var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
192   if (gMapCanvas && gTrackCanvas) {
193     gMapCanvas.width = viewportWidth;
194     gMapCanvas.height = viewportHeight;
195     gTrackCanvas.width = viewportWidth;
196     gTrackCanvas.height = viewportHeight;
197     drawMap();
198     showUI();
199   }
200 }
201
202 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
203 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
204
205 function zoomIn() {
206   if (gPos.z < gMaxZoom) {
207     gPos.z++;
208     drawMap();
209   }
210 }
211
212 function zoomOut() {
213   if (gPos.z > 0) {
214     gPos.z--;
215     drawMap();
216   }
217 }
218
219 function zoomTo(aTargetLevel) {
220   aTargetLevel = parseInt(aTargetLevel);
221   if (aTargetLevel >= 0 && aTargetLevel <= gMaxZoom) {
222     gPos.z = aTargetLevel;
223     drawMap();
224   }
225 }
226
227 function gps2xy(aLatitude, aLongitude) {
228   var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
229   var convLat = aLatitude * Math.PI / 180;
230   var rawY = (1 - Math.log(Math.tan(convLat) +
231                            1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
232   var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
233   return {x: Math.round(rawX),
234           y: Math.round(rawY)};
235 }
236
237 function xy2gps(aX, aY) {
238   var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
239   var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
240   return {latitude: 180 / Math.PI *
241                     Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
242           longitude: aX / maxZoomFactor * 360 - 180};
243 }
244
245 function setMapStyle() {
246   var mapSel = document.getElementById("mapSelector");
247   if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
248     gActiveMap = mapSel.value;
249     document.getElementById("copyright").innerHTML =
250         gMapStyles[gActiveMap].copyright;
251     showUI();
252     drawMap();
253   }
254 }
255
256 // A sane mod function that works for negative numbers.
257 // Returns a % b.
258 function mod(a, b) {
259   return ((a % b) + b) % b;
260 }
261
262 function normalizeCoords(aCoords) {
263   var zoomFactor = Math.pow(2, aCoords.z);
264   return {x: mod(aCoords.x, zoomFactor),
265           y: mod(aCoords.y, zoomFactor),
266           z: aCoords.z};
267 }
268
269 // Returns true if the tile is outside the current view.
270 function isOutsideWindow(t) {
271   var pos = decodeIndex(t);
272
273   var zoomFactor = Math.pow(2, gMaxZoom - pos.z);
274   var wid = gMapCanvas.width * zoomFactor;
275   var ht = gMapCanvas.height * zoomFactor;
276
277   pos.x *= zoomFactor;
278   pos.y *= zoomFactor;
279
280   var sz = gTileSize * zoomFactor;
281   if (pos.x > gPos.x + wid / 2 || pos.y > gPos.y + ht / 2 ||
282       pos.x + sz < gPos.x - wid / 2 || pos.y - sz < gPos.y - ht / 2)
283     return true;
284   return false;
285 }
286
287 function encodeIndex(x, y, z) {
288   var norm = normalizeCoords({x: x, y: y, z: z});
289   return norm.x + "," + norm.y + "," + norm.z;
290 }
291
292 function decodeIndex(encodedIdx) {
293   var ind = encodedIdx.split(",", 3);
294   return {x: ind[0], y: ind[1], z: ind[2]};
295 }
296
297 function drawMap(aPixels, aOverdraw) {
298   // aPixels is an object with left/right/top/bottom members telling how many
299   //   pixels on the borders should actually be drawn.
300   // aOverdraw is a bool that tells if we should draw placeholders or draw
301   //   straight over the existing content.
302   if (!aPixels)
303     aPixels = {left: gMapCanvas.width, right: gMapCanvas.width,
304                top: gMapCanvas.height, bottom: gMapCanvas.height};
305   if (!aOverdraw)
306     aOverdraw = false;
307
308   document.getElementById("zoomLevel").textContent = gPos.z;
309   gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
310   var wid = gMapCanvas.width * gZoomFactor; // Width in level 18 pixels.
311   var ht = gMapCanvas.height * gZoomFactor; // Height in level 18 pixels.
312   var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
313
314   var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
315   var yMin = gPos.y - ht / 2;
316   var xMax = gPos.x + wid / 2;
317   var yMax = gPos.y + ht / 2;
318
319   if (gMapPrefsLoaded && mainDB)
320     gPrefs.set("position", gPos);
321
322   var tiles = {left: Math.ceil((xMin + aPixels.left * gZoomFactor) / size) -
323                                (aPixels.left ? 0 : 1),
324                right: Math.floor((xMax - aPixels.right * gZoomFactor) / size) -
325                                  (aPixels.right ? 1 : 0),
326                top: Math.ceil((yMin + aPixels.top * gZoomFactor) / size) -
327                               (aPixels.top ? 0 : 1),
328                bottom: Math.floor((yMax - aPixels.bottom * gZoomFactor) / size) -
329                                   (aPixels.bottom ? 1 : 0)};
330
331   // Go through all the tiles in the map, find out if to draw them and do so.
332   for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
333     for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
334       // Only go to the drawing step if we need to draw this tile.
335       if (x < tiles.left || x > tiles.right ||
336           y < tiles.top || y > tiles.bottom) {
337         // Round here is **CRUCIAL** otherwise the images are filtered
338         // and the performance sucks (more than expected).
339         var xoff = Math.round((x * size - xMin) / gZoomFactor);
340         var yoff = Math.round((y * size - yMin) / gZoomFactor);
341         // Draw placeholder tile unless we overdraw.
342         if (!aOverdraw &&
343             (x < tiles.left -1  || x > tiles.right + 1 ||
344              y < tiles.top -1 || y > tiles.bottom + 1))
345           gMapContext.drawImage(gLoadingTile, xoff, yoff);
346
347         // Initiate loading/drawing of the actual tile.
348         gTileService.get(gActiveMap, {x: x, y: y, z: gPos.z},
349                          function(aImage, aStyle, aCoords) {
350           // Only draw if this applies for the current view.
351           if ((aStyle == gActiveMap) && (aCoords.z == gPos.z)) {
352             var ixMin = gPos.x - wid / 2;
353             var iyMin = gPos.y - ht / 2;
354             var ixoff = Math.round((aCoords.x * size - ixMin) / gZoomFactor);
355             var iyoff = Math.round((aCoords.y * size - iyMin) / gZoomFactor);
356             var URL = window.URL;
357             var imgURL = URL.createObjectURL(aImage);
358             var imgObj = new Image();
359             imgObj.src = imgURL;
360             imgObj.onload = function() {
361               gMapContext.drawImage(imgObj, ixoff, iyoff);
362               URL.revokeObjectURL(imgURL);
363             }
364           }
365         });
366       }
367     }
368   }
369   drawTrack();
370 }
371
372 function drawTrack() {
373   gLastDrawnPoint = null;
374   gCurPosMapCache = undefined;
375   gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
376   if (gTrack.length) {
377     for (var i = 0; i < gTrack.length; i++) {
378       drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
379                      (i + 1 >= gTrack.length));
380     }
381   }
382 }
383
384 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
385   var trackpoint = gps2xy(aLatitude, aLongitude);
386   // lastPoint is for optimizing (not actually executing the draw until the last)
387   trackpoint.optimized = (lastPoint === false);
388   var mappos = {x: Math.round((trackpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
389                 y: Math.round((trackpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
390
391   if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
392     gTrackContext.strokeStyle = gTrackColor;
393     gTrackContext.fillStyle = gTrackContext.strokeStyle;
394     gTrackContext.lineWidth = gTrackWidth;
395     gTrackContext.lineCap = "round";
396     gTrackContext.lineJoin = "round";
397   }
398   if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
399     // This breaks optimiziation, so make sure to close path and reset optimization.
400     if (gLastDrawnPoint && gLastDrawnPoint.optimized)
401       gTrackContext.stroke();
402     gTrackContext.beginPath();
403     trackpoint.optimized = false;
404     gTrackContext.arc(mappos.x, mappos.y,
405                       gTrackContext.lineWidth, 0, Math.PI * 2, false);
406     gTrackContext.fill();
407   }
408   else {
409     if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
410       gTrackContext.beginPath();
411       gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
412                            Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2));
413     }
414     gTrackContext.lineTo(mappos.x, mappos.y);
415     if (!trackpoint.optimized)
416       gTrackContext.stroke();
417   }
418   gLastDrawnPoint = trackpoint;
419 }
420
421 function drawCurrentLocation(trackPoint) {
422   var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
423   var circleRadius = Math.round(gCurLocSize / 2);
424   var mappos = {x: Math.round((locpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
425                 y: Math.round((locpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
426
427   undrawCurrentLocation();
428
429   // Cache overdrawn area.
430   gCurPosMapCache =
431       {point: locpoint,
432        radius: circleRadius,
433        data: gTrackContext.getImageData(mappos.x - circleRadius,
434                                         mappos.y - circleRadius,
435                                         circleRadius * 2, circleRadius * 2)};
436
437   gTrackContext.strokeStyle = gCurLocColor;
438   gTrackContext.fillStyle = gTrackContext.strokeStyle;
439   gTrackContext.beginPath();
440   gTrackContext.arc(mappos.x, mappos.y,
441                     circleRadius, 0, Math.PI * 2, false);
442   gTrackContext.fill();
443 }
444
445 function undrawCurrentLocation() {
446   if (gCurPosMapCache) {
447     var oldpoint = gCurPosMapCache.point;
448     var oldmp = {x: Math.round((oldpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
449                  y: Math.round((oldpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
450     gTrackContext.putImageData(gCurPosMapCache.data,
451                                oldmp.x - gCurPosMapCache.radius,
452                                oldmp.y - gCurPosMapCache.radius);
453     gCurPosMapCache = undefined;
454   }
455 }
456
457 var mapEvHandler = {
458   handleEvent: function(aEvent) {
459     var touchEvent = aEvent.type.indexOf('touch') != -1;
460
461     // Bail out if the event is happening on an input.
462     if (aEvent.target.tagName.toLowerCase() == "input")
463       return;
464
465     // Bail out on unwanted map moves, but not zoom or keyboard events.
466     if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
467       // Bail out if this is neither a touch nor left-click.
468       if (!touchEvent && aEvent.button != 0)
469         return;
470
471       // Bail out if the started touch can't be found.
472       if (touchEvent && gDragging &&
473           !aEvent.changedTouches.identifiedTouch(gDragTouchID))
474         return;
475     }
476
477     var coordObj = touchEvent ?
478                    aEvent.changedTouches.identifiedTouch(gDragTouchID) :
479                    aEvent;
480
481     switch (aEvent.type) {
482       case "mousedown":
483       case "touchstart":
484         if (touchEvent) {
485           if (aEvent.targetTouches.length == 2) {
486             gPinchStartWidth = Math.sqrt(
487                 Math.pow(aEvent.targetTouches.item(1).clientX -
488                          aEvent.targetTouches.item(0).clientX, 2) +
489                 Math.pow(aEvent.targetTouches.item(1).clientY -
490                          aEvent.targetTouches.item(0).clientY, 2)
491             );
492           }
493           gDragTouchID = aEvent.changedTouches.item(0).identifier;
494           coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
495         }
496         var x = coordObj.clientX - gMapCanvas.offsetLeft;
497         var y = coordObj.clientY - gMapCanvas.offsetTop;
498
499         if (touchEvent || aEvent.button === 0) {
500           gDragging = true;
501         }
502         gLastMouseX = x;
503         gLastMouseY = y;
504         showUI();
505         break;
506       case "mousemove":
507       case "touchmove":
508         if (touchEvent && aEvent.targetTouches.length == 2) {
509           curPinchStartWidth = Math.sqrt(
510               Math.pow(aEvent.targetTouches.item(1).clientX -
511                        aEvent.targetTouches.item(0).clientX, 2) +
512               Math.pow(aEvent.targetTouches.item(1).clientY -
513                        aEvent.targetTouches.item(0).clientY, 2)
514           );
515           if (!gPinchStartWidth)
516             gPinchStartWidth = curPinchStartWidth;
517
518           if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
519               gPinchStartWidth / curPinchStartWidth < 0.6) {
520             var newZoomLevel = gPos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
521             if ((newZoomLevel >= 0) && (newZoomLevel <= gMaxZoom)) {
522               // Calculate new center of the map - preserve middle of pinch.
523               // This means that pixel distance between old center and middle
524               // must equal pixel distance of new center and middle.
525               var x = (aEvent.targetTouches.item(1).clientX +
526                        aEvent.targetTouches.item(0).clientX) / 2 -
527                       gMapCanvas.offsetLeft;
528               var y = (aEvent.targetTouches.item(1).clientY +
529                        aEvent.targetTouches.item(0).clientY) / 2 -
530                       gMapCanvas.offsetTop;
531
532               // Zoom factor after this action.
533               var newZoomFactor = Math.pow(2, gMaxZoom - newZoomLevel);
534               gPos.x -= (x - gMapCanvas.width / 2) * (newZoomFactor - gZoomFactor);
535               gPos.y -= (y - gMapCanvas.height / 2) * (newZoomFactor - gZoomFactor);
536
537               if (gPinchStartWidth < curPinchStartWidth)
538                 zoomIn();
539               else
540                 zoomOut();
541
542               // Reset pinch start width and start another pinch gesture.
543               gPinchStartWidth = null;
544             }
545           }
546           // If we are in a pinch, do not drag.
547           break;
548         }
549         var x = coordObj.clientX - gMapCanvas.offsetLeft;
550         var y = coordObj.clientY - gMapCanvas.offsetTop;
551         if (gDragging === true) {
552           var dX = x - gLastMouseX;
553           var dY = y - gLastMouseY;
554           gPos.x -= dX * gZoomFactor;
555           gPos.y -= dY * gZoomFactor;
556           if (true) { // use optimized path
557             var mapData = gMapContext.getImageData(0, 0,
558                                                    gMapCanvas.width,
559                                                    gMapCanvas.height);
560             gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
561             gMapContext.putImageData(mapData, dX, dY);
562             drawMap({left: (dX > 0) ? dX : 0,
563                      right: (dX < 0) ? -dX : 0,
564                      top: (dY > 0) ? dY : 0,
565                      bottom: (dY < 0) ? -dY : 0});
566           }
567           else {
568             drawMap(false, true);
569           }
570           showUI();
571         }
572         gLastMouseX = x;
573         gLastMouseY = y;
574         break;
575       case "mouseup":
576       case "touchend":
577         gPinchStartWidth = null;
578         gDragging = false;
579         showUI();
580         break;
581       case "mouseout":
582       case "touchcancel":
583       case "touchleave":
584         //gDragging = false;
585         break;
586       case "wheel":
587         // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
588         // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
589
590         // Only accept (non-null) deltaY values
591         if (!aEvent.deltaY)
592           break;
593
594         // Debug output: "coordinates" of the point the mouse was over.
595         /*
596         var ptCoord = {x: gPos.x + (x - gMapCanvas.width / 2) * gZoomFactor,
597                        y: gPos.y + (x - gMapCanvas.height / 2) * gZoomFactor};
598         var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
599         var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
600         console.log(ptCoord.x + "/" + ptCoord.y + " - " +
601                     gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
602                     pt2Coord.x + "/" + pt2Coord.y);
603         */
604
605         var newZoomLevel = gPos.z + (aEvent.deltaY < 0 ? 1 : -1);
606         if ((newZoomLevel >= 0) && (newZoomLevel <= gMaxZoom)) {
607           // Calculate new center of the map - same point stays under the mouse.
608           // This means that the pixel distance between the old center and point
609           // must equal the pixel distance of the new center and that point.
610           var x = coordObj.clientX - gMapCanvas.offsetLeft;
611           var y = coordObj.clientY - gMapCanvas.offsetTop;
612
613           // Zoom factor after this action.
614           var newZoomFactor = Math.pow(2, gMaxZoom - newZoomLevel);
615           gPos.x -= (x - gMapCanvas.width / 2) * (newZoomFactor - gZoomFactor);
616           gPos.y -= (y - gMapCanvas.height / 2) * (newZoomFactor - gZoomFactor);
617
618           if (aEvent.deltaY < 0)
619             zoomIn();
620           else
621             zoomOut();
622         }
623         break;
624       case "keydown":
625         // Allow keyboard control to move and zoom the map.
626         // Should use aEvent.key instead of aEvent.which but needs bug 680830.
627         // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
628         var dX = 0;
629         var dY = 0;
630         switch (aEvent.which) {
631           case 39: // right
632             dX = -gTileSize / 2;
633           break;
634           case 37: // left
635             dX = gTileSize / 2;
636           break;
637           case 38: // up
638             dY = gTileSize / 2;
639           break;
640           case 40: // down
641             dY = -gTileSize / 2;
642           break;
643           case 87: // w
644           case 107: // + (numpad)
645           case 171: // + (normal key)
646             zoomIn();
647           break;
648           case 83: // s
649           case 109: // - (numpad)
650           case 173: // - (normal key)
651             zoomOut();
652           break;
653           case 48: // 0
654           case 49: // 1
655           case 50: // 2
656           case 51: // 3
657           case 52: // 4
658           case 53: // 5
659           case 54: // 6
660           case 55: // 7
661           case 56: // 8
662             zoomTo(aEvent.which - 38);
663           break;
664           case 57: // 9
665             zoomTo(9);
666           break;
667           case 96: // 0 (numpad)
668           case 97: // 1 (numpad)
669           case 98: // 2 (numpad)
670           case 99: // 3 (numpad)
671           case 100: // 4 (numpad)
672           case 101: // 5 (numpad)
673           case 102: // 6 (numpad)
674           case 103: // 7 (numpad)
675           case 104: // 8 (numpad)
676             zoomTo(aEvent.which - 86);
677           break;
678           case 105: // 9 (numpad)
679             zoomTo(9);
680           break;
681           default: // not supported
682             console.log("key not supported: " + aEvent.which);
683           break;
684         }
685
686         // Move if needed.
687         if (dX || dY) {
688           gPos.x -= dX * gZoomFactor;
689           gPos.y -= dY * gZoomFactor;
690           if (true) { // use optimized path
691             var mapData = gMapContext.getImageData(0, 0,
692                                                    gMapCanvas.width,
693                                                    gMapCanvas.height);
694             gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
695             gMapContext.putImageData(mapData, dX, dY);
696             drawMap({left: (dX > 0) ? dX : 0,
697                      right: (dX < 0) ? -dX : 0,
698                      top: (dY > 0) ? dY : 0,
699                      bottom: (dY < 0) ? -dY : 0});
700           }
701           else {
702             drawMap(false, true);
703           }
704         }
705         break;
706     }
707   }
708 };
709
710 var geofake = {
711   tracking: false,
712   lastPos: {x: undefined, y: undefined},
713   watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
714     this.tracking = true;
715     var watchCall = function() {
716       // calc new position in lat/lon degrees
717       // 90° on Earth surface are ~10,000 km at the equator,
718       // so try moving at most 10m at a time
719       if (geofake.lastPos.x)
720         geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
721       else
722         geofake.lastPos.x = 48.208174
723       if (geofake.lastPos.y)
724         geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
725       else
726         geofake.lastPos.y = 16.373819
727       aSuccessCallback({timestamp: Date.now(),
728                         coords: {latitude: geofake.lastPos.x,
729                                  longitude: geofake.lastPos.y,
730                                  accuracy: 20}});
731       if (geofake.tracking)
732         setTimeout(watchCall, 1000);
733     };
734     setTimeout(watchCall, 1000);
735     return "foo";
736   },
737   clearWatch: function(aID) {
738     this.tracking = false;
739   }
740 }
741
742 function setCentering(aCheckbox) {
743   if (gMapPrefsLoaded && mainDB)
744     gPrefs.set("center_map", aCheckbox.checked);
745   gCenterPosition = aCheckbox.checked;
746 }
747
748 function setTracking(aCheckbox) {
749   if (gMapPrefsLoaded && mainDB)
750     gPrefs.set("tracking_enabled", aCheckbox.checked);
751   if (aCheckbox.checked)
752     startTracking();
753   else
754     endTracking();
755 }
756
757 function startTracking() {
758   if (gGeolocation) {
759     gActionLabel.textContent = "Establishing Position";
760     gAction.style.display = "block";
761     gGeoWatchID = gGeolocation.watchPosition(
762       function(position) {
763         if (gActionLabel.textContent) {
764           gActionLabel.textContent = "";
765           gAction.style.display = "none";
766         }
767         // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
768         var tPoint = {time: position.timestamp,
769                       coords: {latitude: position.coords.latitude,
770                                longitude: position.coords.longitude,
771                                altitude: position.coords.altitude,
772                                accuracy: position.coords.accuracy,
773                                altitudeAccuracy: position.coords.altitudeAccuracy,
774                                heading: position.coords.heading,
775                                speed: position.coords.speed},
776                       beginSegment: !gLastTrackPoint};
777         // Only add point to track is accuracy is good enough.
778         if (tPoint.coords.accuracy < gMinTrackAccuracy) {
779           gLastTrackPoint = tPoint;
780           gTrack.push(tPoint);
781           try { gTrackStore.push(tPoint); } catch(e) {}
782           var redrawn = false;
783           if (gCenterPosition) {
784             var posCoord = gps2xy(position.coords.latitude,
785                                   position.coords.longitude);
786             if (Math.abs(gPos.x - posCoord.x) > gMapCanvas.width * gZoomFactor / 4 ||
787                 Math.abs(gPos.y - posCoord.y) > gMapCanvas.height * gZoomFactor / 4) {
788               gPos.x = posCoord.x;
789               gPos.y = posCoord.y;
790               drawMap(); // This draws the current point as well.
791               redrawn = true;
792             }
793           }
794           if (!redrawn)
795             undrawCurrentLocation();
796             drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
797         }
798         drawCurrentLocation(tPoint);
799       },
800       function(error) {
801         // Ignore erros for the moment, but this is good for debugging.
802         // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
803         if (gDebug)
804           console.log(error.message);
805       },
806       {enableHighAccuracy: true}
807     );
808   }
809 }
810
811 function endTracking() {
812   if (gActionLabel.textContent) {
813     gActionLabel.textContent = "";
814     gAction.style.display = "none";
815   }
816   if (gGeoWatchID) {
817     gGeolocation.clearWatch(gGeoWatchID);
818   }
819 }
820
821 function clearTrack() {
822   gTrack = [];
823   gTrackStore.clear();
824   drawTrack();
825 }
826
827 var gTileService = {
828   objStore: "tilecache",
829
830   ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
831
832   get: function(aStyle, aCoords, aCallback) {
833     var norm = normalizeCoords(aCoords);
834     var dbkey = aStyle + "::" + norm.x + "," + norm.y + "," + norm.z;
835     this.getDBCache(dbkey, function(aResult, aEvent) {
836       if (aResult) {
837         // We did get a cached object.
838         aCallback(aResult.image, aStyle, aCoords);
839         // Look at the timestamp and return if it's not too old.
840         if (aResult.timestamp + gTileService.ageLimit > Date.now())
841           return;
842         // Reload cached tile otherwise.
843         var oldDate = new Date(aResult.timestamp);
844         console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
845       }
846       // Retrieve image from the web and store it in the cache.
847       var XHR = new XMLHttpRequest();
848       XHR.open("GET",
849                 gMapStyles[aStyle].url
850                   .replace("{x}", norm.x)
851                   .replace("{y}", norm.y)
852                   .replace("{z}", norm.z)
853                   .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
854                   .replace("[1-4]", 1 + Math.floor(Math.random() * 3)),
855                 true);
856       XHR.responseType = "blob";
857       XHR.addEventListener("load", function () {
858         if (XHR.status === 200) {
859           var blob = XHR.response;
860           aCallback(blob, aStyle, aCoords);
861           gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
862         }
863       }, false);
864       XHR.send();
865     });
866   },
867
868   getDBCache: function(aKey, aCallback) {
869     if (!mainDB)
870       return;
871     var transaction = mainDB.transaction([this.objStore]);
872     var request = transaction.objectStore(this.objStore).get(aKey);
873     request.onsuccess = function(event) {
874       aCallback(request.result, event);
875     };
876     request.onerror = function(event) {
877       // Errors can be handled here.
878       aCallback(undefined, event);
879     };
880   },
881
882   setDBCache: function(aKey, aValue, aCallback) {
883     if (!mainDB)
884       return;
885     var success = false;
886     var transaction = mainDB.transaction([this.objStore], "readwrite");
887     var objStore = transaction.objectStore(this.objStore);
888     var request = objStore.put(aValue, aKey);
889     request.onsuccess = function(event) {
890       success = true;
891       if (aCallback)
892         aCallback(success, event);
893     };
894     request.onerror = function(event) {
895       // Errors can be handled here.
896       if (aCallback)
897         aCallback(success, event);
898     };
899   },
900
901   unsetDBCache: function(aKey, aCallback) {
902     if (!mainDB)
903       return;
904     var success = false;
905     var transaction = mainDB.transaction([this.objStore], "readwrite");
906     var request = transaction.objectStore(this.objStore).delete(aKey);
907     request.onsuccess = function(event) {
908       success = true;
909       if (aCallback)
910         aCallback(success, event);
911     };
912     request.onerror = function(event) {
913       // Errors can be handled here.
914       if (aCallback)
915         aCallback(success, event);
916     }
917   },
918
919   clearDB: function(aCallback) {
920     if (!mainDB)
921       return;
922     var success = false;
923     var transaction = mainDB.transaction([this.objStore], "readwrite");
924     var request = transaction.objectStore(this.objStore).clear();
925     request.onsuccess = function(event) {
926       success = true;
927       if (aCallback)
928         aCallback(success, event);
929     };
930     request.onerror = function(event) {
931       // Errors can be handled here.
932       if (aCallback)
933         aCallback(success, event);
934     }
935   }
936 };