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