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/. */
5 var gMapCanvas, gMapContext, gTrackCanvas, gTrackContext, gGeolocation;
9 var gMaxZoom = 18; // The minimum is 0.
11 var gMinTrackAccuracy = 1000; // meters
12 var gTrackWidth = 2; // pixels
13 var gTrackColor = "#FF0000";
14 var gCurLocSize = 6; // pixels
15 var gCurLocColor = "#A00000";
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
21 {name: "OpenStreetMap (Mapnik)",
22 url: "http://tile.openstreetmap.org/{z}/{x}/{y}.png",
23 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
25 {name: "Cycle Map (OSM)",
26 url: "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
27 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
29 {name: "Transport Map (OSM)",
30 url: "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png",
31 copyright: 'Map data and imagery © <a href="http://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="http://www.openstreetmap.org/copyright">ODbL/CC-BY-SA</a>'},
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 © <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>.'},
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.'},
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>.'},
46 url: " http://mt1.google.com/vt/x={x}&y={y}&z={z}",
47 copyright: 'Map data and imagery © <a href="http://maps.google.com/">Google</a>'},
49 var gActiveMap = "osm_mapnik";
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.
61 var gMapPrefsLoaded = false;
63 var gDragging = false;
68 var gLastTrackPoint, gLastDrawnPoint;
69 var gCenterPosition = true;
74 gGeolocation = navigator.geolocation;
75 gMapCanvas = document.getElementById("map");
76 gMapContext = gMapCanvas.getContext("2d");
77 gTrackCanvas = document.getElementById("track");
78 gTrackContext = gTrackCanvas.getContext("2d");
80 gActiveMap = "osm_mapnik";
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");
93 var getPersistentPrefs = function() {
96 gPrefs.get("position", function(aValue) {
103 gPrefs.get("center_map", function(aValue) {
104 if (aValue === undefined)
105 document.getElementById("centerCheckbox").checked = true;
107 document.getElementById("centerCheckbox").checked = aValue;
108 setCentering(document.getElementById("centerCheckbox"));
112 gPrefs.get("tracking_enabled", function(aValue) {
113 if (aValue === undefined)
114 document.getElementById("trackCheckbox").checked = true;
116 document.getElementById("trackCheckbox").checked = aValue;
120 gTrackStore.getList(function(aTPoints) {
122 console.log(aTPoints.length + " points loaded.");
123 if (aTPoints.length) {
130 setTimeout(getPersistentPrefs, 100);
133 console.log("Loading prefs failed.");
136 getPersistentPrefs();
138 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
139 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
140 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
141 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
143 gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
144 gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
145 gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
146 gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
147 gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
149 gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
151 document.getElementById("copyright").innerHTML =
152 gMapStyles[gActiveMap].copyright;
154 gLoadingTile = new Image();
155 gLoadingTile.src = "style/loading.png";
157 gLoadingTile.onload = function() { gWaitCounter--; };
160 function resizeAndDraw() {
161 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
162 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
163 if (gMapCanvas && gTrackCanvas) {
164 gMapCanvas.width = viewportWidth;
165 gMapCanvas.height = viewportHeight;
166 gTrackCanvas.width = viewportWidth;
167 gTrackCanvas.height = viewportHeight;
173 // Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
174 // See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
177 if (gPos.z < gMaxZoom) {
190 function gps2xy(aLatitude, aLongitude) {
191 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
192 var convLat = aLatitude * Math.PI / 180;
193 var rawY = (1 - Math.log(Math.tan(convLat) +
194 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
195 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
196 return {x: Math.round(rawX),
197 y: Math.round(rawY)};
200 function xy2gps(aX, aY) {
201 var maxZoomFactor = Math.pow(2, gMaxZoom) * gTileSize;
202 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
203 return {latitude: 180 / Math.PI *
204 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
205 longitude: aX / maxZoomFactor * 360 - 180};
208 function setMapStyle() {
209 var mapSel = document.getElementById("mapSelector");
210 if (mapSel.selectedIndex >= 0 && gActiveMap != mapSel.value) {
211 gActiveMap = mapSel.value;
212 document.getElementById("copyright").innerHTML =
213 gMapStyles[gActiveMap].copyright;
219 // A sane mod function that works for negative numbers.
222 return ((a % b) + b) % b;
225 function normalizeCoords(aCoords) {
226 var zoomFactor = Math.pow(2, aCoords.z);
227 return {x: mod(aCoords.x, zoomFactor),
228 y: mod(aCoords.y, zoomFactor),
232 // Returns true if the tile is outside the current view.
233 function isOutsideWindow(t) {
234 var pos = decodeIndex(t);
236 var zoomFactor = Math.pow(2, gMaxZoom - pos.z);
237 var wid = gMapCanvas.width * zoomFactor;
238 var ht = gMapCanvas.height * zoomFactor;
243 var sz = gTileSize * zoomFactor;
244 if (pos.x > gPos.x + wid / 2 || pos.y > gPos.y + ht / 2 ||
245 pos.x + sz < gPos.x - wid / 2 || pos.y - sz < gPos.y - ht / 2)
250 function encodeIndex(x, y, z) {
251 var norm = normalizeCoords({x: x, y: y, z: z});
252 return norm.x + "," + norm.y + "," + norm.z;
255 function decodeIndex(encodedIdx) {
256 var ind = encodedIdx.split(",", 3);
257 return {x: ind[0], y: ind[1], z: ind[2]};
260 function drawMap(aPixels, aOverdraw) {
261 // aPixels is an object with left/right/top/bottom members telling how many
262 // pixels on the borders should actually be drawn.
263 // aOverdraw is a bool that tells if we should draw placeholders or draw
264 // straight over the existing content.
266 aPixels = {left: gMapCanvas.width, right: gMapCanvas.width,
267 top: gMapCanvas.height, bottom: gMapCanvas.height};
271 document.getElementById("zoomLevel").textContent = gPos.z;
272 gZoomFactor = Math.pow(2, gMaxZoom - gPos.z);
273 var wid = gMapCanvas.width * gZoomFactor; // Width in level 18 pixels.
274 var ht = gMapCanvas.height * gZoomFactor; // Height in level 18 pixels.
275 var size = gTileSize * gZoomFactor; // Tile size in level 18 pixels.
277 var xMin = gPos.x - wid / 2; // Corners of the window in level 18 pixels.
278 var yMin = gPos.y - ht / 2;
279 var xMax = gPos.x + wid / 2;
280 var yMax = gPos.y + ht / 2;
282 if (gMapPrefsLoaded && mainDB)
283 gPrefs.set("position", gPos);
285 var tiles = {left: Math.ceil((xMin + aPixels.left * gZoomFactor) / size) -
286 (aPixels.left ? 0 : 1),
287 right: Math.floor((xMax - aPixels.right * gZoomFactor) / size) -
288 (aPixels.right ? 1 : 0),
289 top: Math.ceil((yMin + aPixels.top * gZoomFactor) / size) -
290 (aPixels.top ? 0 : 1),
291 bottom: Math.floor((yMax - aPixels.bottom * gZoomFactor) / size) -
292 (aPixels.bottom ? 1 : 0)};
294 // Go through all the tiles in the map, find out if to draw them and do so.
295 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
296 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
297 // Only go to the drawing step if we need to draw this tile.
298 if (x < tiles.left || x > tiles.right ||
299 y < tiles.top || y > tiles.bottom) {
300 // Round here is **CRUCIAL** otherwise the images are filtered
301 // and the performance sucks (more than expected).
302 var xoff = Math.round((x * size - xMin) / gZoomFactor);
303 var yoff = Math.round((y * size - yMin) / gZoomFactor);
304 // Draw placeholder tile unless we overdraw.
306 (x < tiles.left -1 || x > tiles.right + 1 ||
307 y < tiles.top -1 || y > tiles.bottom + 1))
308 gMapContext.drawImage(gLoadingTile, xoff, yoff);
310 // Initiate loading/drawing of the actual tile.
311 gTileService.get(gActiveMap, {x: x, y: y, z: gPos.z},
312 function(aImage, aStyle, aCoords) {
313 // Only draw if this applies for the current view.
314 if ((aStyle == gActiveMap) && (aCoords.z == gPos.z)) {
315 var ixMin = gPos.x - wid / 2;
316 var iyMin = gPos.y - ht / 2;
317 var ixoff = Math.round((aCoords.x * size - ixMin) / gZoomFactor);
318 var iyoff = Math.round((aCoords.y * size - iyMin) / gZoomFactor);
319 var URL = window.URL;
320 var imgURL = URL.createObjectURL(aImage);
321 var imgObj = new Image();
323 imgObj.onload = function() {
324 gMapContext.drawImage(imgObj, ixoff, iyoff);
325 URL.revokeObjectURL(imgURL);
332 gLastDrawnPoint = null;
333 gCurPosMapCache = undefined;
334 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
336 for (var i = 0; i < gTrack.length; i++) {
337 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
338 (i + 1 >= gTrack.length));
343 function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
344 var trackpoint = gps2xy(aLatitude, aLongitude);
345 // lastPoint is for optimizing (not actually executing the draw until the last)
346 trackpoint.optimized = (lastPoint === false);
347 var mappos = {x: Math.round((trackpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
348 y: Math.round((trackpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
350 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
351 gTrackContext.strokeStyle = gTrackColor;
352 gTrackContext.fillStyle = gTrackContext.strokeStyle;
353 gTrackContext.lineWidth = gTrackWidth;
354 gTrackContext.lineCap = "round";
355 gTrackContext.lineJoin = "round";
357 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
358 // This breaks optimiziation, so make sure to close path and reset optimization.
359 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
360 gTrackContext.stroke();
361 gTrackContext.beginPath();
362 trackpoint.optimized = false;
363 gTrackContext.arc(mappos.x, mappos.y,
364 gTrackContext.lineWidth, 0, Math.PI * 2, false);
365 gTrackContext.fill();
368 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
369 gTrackContext.beginPath();
370 gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
371 Math.round((gLastDrawnPoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2));
373 gTrackContext.lineTo(mappos.x, mappos.y);
374 if (!trackpoint.optimized)
375 gTrackContext.stroke();
377 gLastDrawnPoint = trackpoint;
380 function drawCurrentLocation(trackPoint) {
381 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
382 var circleRadius = Math.round(gCurLocSize / 2);
383 var mappos = {x: Math.round((locpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
384 y: Math.round((locpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
386 undrawCurrentLocation();
388 // Cache overdrawn area.
391 radius: circleRadius,
392 data: gTrackContext.getImageData(mappos.x - circleRadius,
393 mappos.y - circleRadius,
394 circleRadius * 2, circleRadius * 2)};
396 gTrackContext.strokeStyle = gCurLocColor;
397 gTrackContext.fillStyle = gTrackContext.strokeStyle;
398 gTrackContext.beginPath();
399 gTrackContext.arc(mappos.x, mappos.y,
400 circleRadius, 0, Math.PI * 2, false);
401 gTrackContext.fill();
404 function undrawCurrentLocation() {
405 if (gCurPosMapCache) {
406 var oldpoint = gCurPosMapCache.point;
407 var oldmp = {x: Math.round((oldpoint.x - gPos.x) / gZoomFactor + gMapCanvas.width / 2),
408 y: Math.round((oldpoint.y - gPos.y) / gZoomFactor + gMapCanvas.height / 2)};
409 gTrackContext.putImageData(gCurPosMapCache.data,
410 oldmp.x - gCurPosMapCache.radius,
411 oldmp.y - gCurPosMapCache.radius);
412 gCurPosMapCache = undefined;
417 handleEvent: function(aEvent) {
418 var touchEvent = aEvent.type.indexOf('touch') != -1;
420 // Bail out on unwanted map moves, but not zoom-changing events.
421 if (aEvent.type != "DOMMouseScroll" && aEvent.type != "mousewheel") {
422 // Bail out if this is neither a touch nor left-click.
423 if (!touchEvent && aEvent.button != 0)
426 // Bail out if the started touch can't be found.
427 if (touchEvent && gDragging &&
428 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
432 var coordObj = touchEvent ?
433 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
436 switch (aEvent.type) {
440 gDragTouchID = aEvent.changedTouches.item(0).identifier;
441 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
443 var x = coordObj.clientX - gMapCanvas.offsetLeft;
444 var y = coordObj.clientY - gMapCanvas.offsetTop;
446 if (touchEvent || aEvent.button === 0) {
455 var x = coordObj.clientX - gMapCanvas.offsetLeft;
456 var y = coordObj.clientY - gMapCanvas.offsetTop;
457 if (gDragging === true) {
458 var dX = x - gLastMouseX;
459 var dY = y - gLastMouseY;
460 gPos.x -= dX * gZoomFactor;
461 gPos.y -= dY * gZoomFactor;
462 var mapData = gMapContext.getImageData(0, 0, gMapCanvas.width, gMapCanvas.height);
463 gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
464 gMapContext.putImageData(mapData, dX, dY);
465 drawMap({left: (dX > 0) ? dX : 0,
466 right: (dX < 0) ? -dX : 0,
467 top: (dY > 0) ? dY : 0,
468 bottom: (dY < 0) ? -dY : 0});
485 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
486 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
488 // Only accept (non-null) deltaY values
492 // Debug output: "coordinates" of the point the mouse was over.
494 var ptCoord = {x: gPos.x + (x - gMapCanvas.width / 2) * gZoomFactor,
495 y: gPos.y + (x - gMapCanvas.height / 2) * gZoomFactor};
496 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
497 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
498 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
499 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
500 pt2Coord.x + "/" + pt2Coord.y);
503 var newZoomLevel = gPos.z + (aEvent.deltaY < 0 ? 1 : -1);
504 if ((newZoomLevel >= 0) && (newZoomLevel <= gMaxZoom)) {
505 // Calculate new center of the map - same point stays under the mouse.
506 // This means that the pixel distance between the old center and point
507 // must equal the pixel distance of the new center and that point.
508 var x = coordObj.clientX - gMapCanvas.offsetLeft;
509 var y = coordObj.clientY - gMapCanvas.offsetTop;
511 // Zoom factor after this action.
512 var newZoomFactor = Math.pow(2, gMaxZoom - newZoomLevel);
513 gPos.x -= (x - gMapCanvas.width / 2) * (newZoomFactor - gZoomFactor);
514 gPos.y -= (y - gMapCanvas.height / 2) * (newZoomFactor - gZoomFactor);
516 if (aEvent.deltaY < 0)
528 lastPos: {x: undefined, y: undefined},
529 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
530 this.tracking = true;
531 var watchCall = function() {
532 // calc new position in lat/lon degrees
533 // 90° on Earth surface are ~10,000 km at the equator,
534 // so try moving at most 10m at a time
535 if (geofake.lastPos.x)
536 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
538 geofake.lastPos.x = 48.208174
539 if (geofake.lastPos.y)
540 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
542 geofake.lastPos.y = 16.373819
543 aSuccessCallback({timestamp: Date.now(),
544 coords: {latitude: geofake.lastPos.x,
545 longitude: geofake.lastPos.y,
547 if (geofake.tracking)
548 setTimeout(watchCall, 1000);
550 setTimeout(watchCall, 1000);
553 clearWatch: function(aID) {
554 this.tracking = false;
558 function setCentering(aCheckbox) {
559 if (gMapPrefsLoaded && mainDB)
560 gPrefs.set("center_map", aCheckbox.checked);
561 gCenterPosition = aCheckbox.checked;
564 function setTracking(aCheckbox) {
565 if (gMapPrefsLoaded && mainDB)
566 gPrefs.set("tracking_enabled", aCheckbox.checked);
567 if (aCheckbox.checked)
573 function startTracking() {
575 gActionLabel.textContent = "Establishing Position";
576 gAction.style.display = "block";
577 gGeoWatchID = gGeolocation.watchPosition(
579 if (gActionLabel.textContent) {
580 gActionLabel.textContent = "";
581 gAction.style.display = "none";
583 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
584 var tPoint = {time: position.timestamp,
585 coords: {latitude: position.coords.latitude,
586 longitude: position.coords.longitude,
587 altitude: position.coords.altitude,
588 accuracy: position.coords.accuracy,
589 altitudeAccuracy: position.coords.altitudeAccuracy,
590 heading: position.coords.heading,
591 speed: position.coords.speed},
592 beginSegment: !gLastTrackPoint};
593 // Only add point to track is accuracy is good enough.
594 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
595 gLastTrackPoint = tPoint;
597 try { gTrackStore.push(tPoint); } catch(e) {}
599 if (gCenterPosition) {
600 var posCoord = gps2xy(position.coords.latitude,
601 position.coords.longitude);
602 if (Math.abs(gPos.x - posCoord.x) > gMapCanvas.width * gZoomFactor / 4 ||
603 Math.abs(gPos.y - posCoord.y) > gMapCanvas.height * gZoomFactor / 4) {
606 drawMap(); // This draws the current point as well.
611 undrawCurrentLocation();
612 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
614 drawCurrentLocation(tPoint);
617 // Ignore erros for the moment, but this is good for debugging.
618 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
620 console.log(error.message);
622 {enableHighAccuracy: true}
627 function endTracking() {
628 if (gActionLabel.textContent) {
629 gActionLabel.textContent = "";
630 gAction.style.display = "none";
633 gGeolocation.clearWatch(gGeoWatchID);
637 function clearTrack() {
644 objStore: "tilecache",
646 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
648 get: function(aStyle, aCoords, aCallback) {
649 var norm = normalizeCoords(aCoords);
650 var dbkey = aStyle + "::" + norm.x + "," + norm.y + "," + norm.z;
651 this.getDBCache(dbkey, function(aResult, aEvent) {
653 // We did get a cached object.
654 aCallback(aResult.image, aStyle, aCoords);
655 // Look at the timestamp and return if it's not too old.
656 if (aResult.timestamp + gTileService.ageLimit > Date.now())
658 // Reload cached tile otherwise.
659 var oldDate = new Date(aResult.timestamp);
660 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
662 // Retrieve image from the web and store it in the cache.
663 var XHR = new XMLHttpRequest();
665 gMapStyles[aStyle].url
666 .replace("{x}", norm.x)
667 .replace("{y}", norm.y)
668 .replace("{z}", norm.z)
669 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
670 .replace("[1-4]", 1 + Math.floor(Math.random() * 3)),
672 XHR.responseType = "blob";
673 XHR.addEventListener("load", function () {
674 if (XHR.status === 200) {
675 var blob = XHR.response;
676 aCallback(blob, aStyle, aCoords);
677 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
684 getDBCache: function(aKey, aCallback) {
687 var transaction = mainDB.transaction([this.objStore]);
688 var request = transaction.objectStore(this.objStore).get(aKey);
689 request.onsuccess = function(event) {
690 aCallback(request.result, event);
692 request.onerror = function(event) {
693 // Errors can be handled here.
694 aCallback(undefined, event);
698 setDBCache: function(aKey, aValue, aCallback) {
702 var transaction = mainDB.transaction([this.objStore], "readwrite");
703 var objStore = transaction.objectStore(this.objStore);
704 var request = objStore.put(aValue, aKey);
705 request.onsuccess = function(event) {
708 aCallback(success, event);
710 request.onerror = function(event) {
711 // Errors can be handled here.
713 aCallback(success, event);
717 unsetDBCache: function(aKey, aCallback) {
721 var transaction = mainDB.transaction([this.objStore], "readwrite");
722 var request = transaction.objectStore(this.objStore).delete(aKey);
723 request.onsuccess = function(event) {
726 aCallback(success, event);
728 request.onerror = function(event) {
729 // Errors can be handled here.
731 aCallback(success, event);
735 clearDB: function(aCallback) {
739 var transaction = mainDB.transaction([this.objStore], "readwrite");
740 var request = transaction.objectStore(this.objStore).clear();
741 request.onsuccess = function(event) {
744 aCallback(success, event);
746 request.onerror = function(event) {
747 // Errors can be handled here.
749 aCallback(success, event);