remove 2D canvas, move draw() and resizeAndDraw() into gMap, only use stored position...
[lantea.git] / js / map.js
... / ...
CommitLineData
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
5var gGLMapCanvas, gTrackCanvas, gTrackContext, gGeolocation;
6var gDebug = false;
7
8var gMinTrackAccuracy = 1000; // meters
9var gTrackWidth = 2; // pixels
10var gTrackColor = "#FF0000";
11var gCurLocSize = 6; // pixels
12var gCurLocColor = "#A00000";
13
14var gMapStyles = {
15 // OSM tile usage policy: http://wiki.openstreetmap.org/wiki/Tile_usage_policy
16 // Find some more OSM ones at http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Tile_servers
17 osm_mapnik:
18 {name: "OpenStreetMap (Mapnik)",
19 url: "http://tile.openstreetmap.org/{z}/{x}/{y}.png",
20 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>'},
21 osm_cyclemap:
22 {name: "Cycle Map (OSM)",
23 url: "http://[a-c].tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
24 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>'},
25 osm_transmap:
26 {name: "Transport Map (OSM)",
27 url: "http://[a-c].tile2.opencyclemap.org/transport/{z}/{x}/{y}.png",
28 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>'},
29 mapquest_open:
30 {name: "MapQuest OSM",
31 url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png",
32 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>.'},
33 mapquest_aerial:
34 {name: "MapQuest Open Aerial",
35 url: "http://otile[1-4].mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg",
36 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.'},
37 opengeoserver_arial:
38 {name: "OpenGeoServer Aerial",
39 url: "http://services.opengeoserver.org/tiles/1.0.0/globe.aerial_EPSG3857/{z}/{x}/{y}.png?origin=nw",
40 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>.'},
41 google_map:
42 {name: "Google Maps",
43 url: " http://mt1.google.com/vt/x={x}&y={y}&z={z}",
44 copyright: 'Map data and imagery &copy; <a href="http://maps.google.com/">Google</a>'},
45};
46
47var gLastMouseX = 0;
48var gLastMouseY = 0;
49
50var gLoadingTile;
51
52var gMapPrefsLoaded = false;
53
54var gDragging = false;
55var gDragTouchID, gPinchStartWidth;
56
57var gGeoWatchID;
58var gTrack = [];
59var gLastTrackPoint, gLastDrawnPoint;
60var gCenterPosition = true;
61
62var gCurPosMapCache;
63
64function initMap() {
65 gGeolocation = navigator.geolocation;
66 // Set up canvas context.
67 gGLMapCanvas = document.getElementById("map");
68 try {
69 // Try to grab the standard context. If it fails, fallback to experimental.
70 // We also try to tell it we do not need a depth buffer.
71 gMap.gl = gGLMapCanvas.getContext("webgl", {depth: false}) ||
72 gGLMapCanvas.getContext("experimental-webgl", {depth: false});
73 }
74 catch(e) {}
75 // If we don't have a GL context, give up now
76 if (!gMap.gl) {
77 showGLWarningDialog();
78 gMap.gl = null;
79 }
80 gTrackCanvas = document.getElementById("track");
81 gTrackContext = gTrackCanvas.getContext("2d");
82 if (!gMap.activeMap)
83 gMap.activeMap = "osm_mapnik";
84
85 //gDebug = true;
86 if (gDebug) {
87 gGeolocation = geofake;
88 var hiddenList = document.getElementsByClassName("debugHide");
89 // last to first - list of elements with that class is changing!
90 for (var i = hiddenList.length - 1; i >= 0; i--) {
91 hiddenList[i].classList.remove("debugHide");
92 }
93 }
94
95 gAction.addEventListener("prefload-done", gMap.initGL, false);
96
97 console.log("map vars set, loading prefs...");
98 loadPrefs();
99}
100
101function loadPrefs(aEvent) {
102 if (aEvent && aEvent.type == "prefs-step") {
103 console.log("wait: " + gWaitCounter);
104 if (gWaitCounter == 0) {
105 gAction.removeEventListener(aEvent.type, loadPrefs, false);
106 gMapPrefsLoaded = true;
107 console.log("prefs loaded.");
108
109 gTrackCanvas.addEventListener("mouseup", mapEvHandler, false);
110 gTrackCanvas.addEventListener("mousemove", mapEvHandler, false);
111 gTrackCanvas.addEventListener("mousedown", mapEvHandler, false);
112 gTrackCanvas.addEventListener("mouseout", mapEvHandler, false);
113
114 gTrackCanvas.addEventListener("touchstart", mapEvHandler, false);
115 gTrackCanvas.addEventListener("touchmove", mapEvHandler, false);
116 gTrackCanvas.addEventListener("touchend", mapEvHandler, false);
117 gTrackCanvas.addEventListener("touchcancel", mapEvHandler, false);
118 gTrackCanvas.addEventListener("touchleave", mapEvHandler, false);
119
120 gTrackCanvas.addEventListener("wheel", mapEvHandler, false);
121
122 document.getElementById("body").addEventListener("keydown", mapEvHandler, false);
123
124 document.getElementById("copyright").innerHTML =
125 gMapStyles[gMap.activeMap].copyright;
126
127 gLoadingTile = new Image();
128 gLoadingTile.src = "style/loading.png";
129 gLoadingTile.onload = function() {
130 var throwEv = new CustomEvent("prefload-done");
131 gAction.dispatchEvent(throwEv);
132 };
133 }
134 }
135 else {
136 if (aEvent)
137 gAction.removeEventListener(aEvent.type, loadPrefs, false);
138 gAction.addEventListener("prefs-step", loadPrefs, false);
139 gWaitCounter++;
140 gPrefs.get("position", function(aValue) {
141 if (aValue && aValue.x && aValue.y && aValue.z) {
142 gMap.pos = aValue;
143 }
144 gWaitCounter--;
145 var throwEv = new CustomEvent("prefs-step");
146 gAction.dispatchEvent(throwEv);
147 });
148 gWaitCounter++;
149 gPrefs.get("center_map", function(aValue) {
150 if (aValue === undefined)
151 document.getElementById("centerCheckbox").checked = true;
152 else
153 document.getElementById("centerCheckbox").checked = aValue;
154 setCentering(document.getElementById("centerCheckbox"));
155 gWaitCounter--;
156 var throwEv = new CustomEvent("prefs-step");
157 gAction.dispatchEvent(throwEv);
158 });
159 gWaitCounter++;
160 gPrefs.get("tracking_enabled", function(aValue) {
161 if (aValue === undefined)
162 document.getElementById("trackCheckbox").checked = true;
163 else
164 document.getElementById("trackCheckbox").checked = aValue;
165 gWaitCounter--;
166 var throwEv = new CustomEvent("prefs-step");
167 gAction.dispatchEvent(throwEv);
168 });
169 gWaitCounter++;
170 var trackLoadStarted = false;
171 var redrawBase = 100;
172 gTrackStore.getListStepped(function(aTPoint) {
173 if (aTPoint) {
174 // Add in front and return new length.
175 var tracklen = gTrack.unshift(aTPoint);
176 // Redraw track periodically, larger distance the longer it gets.
177 // Initial paint will do initial track drawing.
178 if (tracklen % redrawBase == 0) {
179 drawTrack();
180 redrawBase = tracklen;
181 }
182 }
183 else {
184 // Last point received.
185 drawTrack();
186 }
187 if (!trackLoadStarted) {
188 // We have the most recent point, if present, rest will load async.
189 trackLoadStarted = true;
190 gWaitCounter--;
191 var throwEv = new CustomEvent("prefs-step");
192 gAction.dispatchEvent(throwEv);
193 }
194 });
195 }
196}
197
198var gMap = {
199 gl: null,
200 glShaderProgram: null,
201 glVertexPositionAttr: null,
202 glTextureCoordAttr: null,
203 glResolutionAttr: null,
204 glMapTexture: null,
205 glTextures: {},
206 glTextureKeys: {},
207
208 activeMap: "osm_mapnik",
209 tileSize: 256,
210 maxZoom: 18, // The minimum is 0.
211 zoomFactor: null,
212 pos: {
213 x: 35630000.0, // Current position in the map in pixels at the maximum zoom level (18)
214 y: 23670000.0, // The range is 0-67108864 (2^gMap.maxZoom * gMap.tileSize)
215 z: 5 // This could be fractional if supported being between zoom levels.
216 },
217
218 get width() { return gMap.gl ? gMap.gl.drawingBufferWidth : gGLMapCanvas.width; },
219 get height() { return gMap.gl ? gMap.gl.drawingBufferHeight : gGLMapCanvas.height; },
220
221 getVertShaderSource: function() {
222 return 'attribute vec2 aVertexPosition;\n' +
223 'attribute vec2 aTextureCoord;\n\n' +
224 'uniform vec2 uResolution;\n\n' +
225 'varying highp vec2 vTextureCoord;\n\n' +
226 'void main(void) {\n' +
227 // convert the rectangle from pixels to -1.0 to +1.0 (clipspace) 0.0 to 1.0
228 ' vec2 clipSpace = aVertexPosition * 2.0 / uResolution - 1.0;\n' +
229 ' gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);\n' +
230 ' vTextureCoord = aTextureCoord;\n' +
231 '}'; },
232 getFragShaderSource:function() {
233 return 'varying highp vec2 vTextureCoord;\n\n' +
234 'uniform sampler2D uImage;\n\n' +
235 'void main(void) {\n' +
236 ' gl_FragColor = texture2D(uImage, vTextureCoord);\n' +
237 '}'; },
238
239 initGL: function() {
240 // When called from the event listener, the "this" reference doesn't work, so use the object name.
241 if (gMap.gl) {
242 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
243 gMap.gl.clearColor(0.0, 0.0, 0.0, 0.5); // Set clear color to black, fully opaque.
244 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT|gMap.gl.DEPTH_BUFFER_BIT); // Clear the color.
245
246 // Create and initialize the shaders.
247 var vertShader = gMap.gl.createShader(gMap.gl.VERTEX_SHADER);
248 var fragShader = gMap.gl.createShader(gMap.gl.FRAGMENT_SHADER);
249 gMap.gl.shaderSource(vertShader, gMap.getVertShaderSource());
250 // Compile the shader program.
251 gMap.gl.compileShader(vertShader);
252 // See if it compiled successfully.
253 if (!gMap.gl.getShaderParameter(vertShader, gMap.gl.COMPILE_STATUS)) {
254 console.log("An error occurred compiling the vertex shader: " + gMap.gl.getShaderInfoLog(vertShader));
255 return null;
256 }
257 gMap.gl.shaderSource(fragShader, gMap.getFragShaderSource());
258 // Compile the shader program.
259 gMap.gl.compileShader(fragShader);
260 // See if it compiled successfully.
261 if (!gMap.gl.getShaderParameter(fragShader, gMap.gl.COMPILE_STATUS)) {
262 console.log("An error occurred compiling the fragment shader: " + gMap.gl.getShaderInfoLog(fragShader));
263 return null;
264 }
265
266 gMap.glShaderProgram = gMap.gl.createProgram();
267 gMap.gl.attachShader(gMap.glShaderProgram, vertShader);
268 gMap.gl.attachShader(gMap.glShaderProgram, fragShader);
269 gMap.gl.linkProgram(gMap.glShaderProgram);
270 // If creating the shader program failed, alert
271 if (!gMap.gl.getProgramParameter(gMap.glShaderProgram, gMap.gl.LINK_STATUS)) {
272 alert("Unable to initialize the shader program.");
273 }
274 gMap.gl.useProgram(gMap.glShaderProgram);
275 // Get locations of the attributes.
276 gMap.glVertexPositionAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aVertexPosition");
277 gMap.glTextureCoordAttr = gMap.gl.getAttribLocation(gMap.glShaderProgram, "aTextureCoord");
278 gMap.glResolutionAttr = gMap.gl.getUniformLocation(gMap.glShaderProgram, "uResolution");
279
280 var tileVerticesBuffer = gMap.gl.createBuffer();
281 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, tileVerticesBuffer);
282 // The vertices are the coordinates of the corner points of the square.
283 var vertices = [
284 0.0, 0.0,
285 1.0, 0.0,
286 0.0, 1.0,
287 0.0, 1.0,
288 1.0, 0.0,
289 1.0, 1.0,
290 ];
291 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(vertices), gMap.gl.STATIC_DRAW);
292 gMap.gl.enableVertexAttribArray(gMap.glTextureCoordAttr);
293 gMap.gl.vertexAttribPointer(gMap.glTextureCoordAttr, 2, gMap.gl.FLOAT, false, 0, 0);
294
295 gMap.loadImageToTexture(gLoadingTile, 0, "loading::0,0,0");
296
297 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
298
299 // Create a buffer for the position of the rectangle corners.
300 var mapVerticesTextureCoordBuffer = gMap.gl.createBuffer();
301 gMap.gl.bindBuffer(gMap.gl.ARRAY_BUFFER, mapVerticesTextureCoordBuffer);
302 gMap.gl.enableVertexAttribArray(gMap.glVertexPositionAttr);
303 gMap.gl.vertexAttribPointer(gMap.glVertexPositionAttr, 2, gMap.gl.FLOAT, false, 0, 0);
304 }
305
306 var throwEv = new CustomEvent("mapinit-done");
307 gAction.dispatchEvent(throwEv);
308 },
309
310 draw: function(aPixels, aOverdraw) {
311 gMap.drawGL(aPixels, aOverdraw);
312 drawTrack();
313 },
314
315 drawGL: function(aPixels, aOverdraw) {
316 if (!gMap.gl) { return; }
317 // aPixels is an object with left/right/top/bottom members telling how many
318 // pixels on the borders should actually be drawn.
319 // aOverdraw is a bool that tells if we should draw placeholders or draw
320 // straight over the existing content.
321 // XXX: Both those optimizations are OFF for GL right now!
322 //if (!aPixels)
323 aPixels = {left: gMap.gl.drawingBufferWidth, right: gMap.gl.drawingBufferWidth,
324 top: gMap.gl.drawingBufferHeight, bottom: gMap.gl.drawingBufferHeight};
325 if (!aOverdraw)
326 aOverdraw = false;
327
328 document.getElementById("zoomLevel").textContent = gMap.pos.z;
329 gMap.zoomFactor = Math.pow(2, gMap.maxZoom - gMap.pos.z);
330 var wid = gMap.gl.drawingBufferWidth * gMap.zoomFactor; // Width in level 18 pixels.
331 var ht = gMap.gl.drawingBufferHeight * gMap.zoomFactor; // Height in level 18 pixels.
332 var size = gMap.tileSize * gMap.zoomFactor; // Tile size in level 18 pixels.
333
334 var xMin = gMap.pos.x - wid / 2; // Corners of the window in level 18 pixels.
335 var yMin = gMap.pos.y - ht / 2;
336 var xMax = gMap.pos.x + wid / 2;
337 var yMax = gMap.pos.y + ht / 2;
338
339 if (gMapPrefsLoaded && mainDB)
340 gPrefs.set("position", gMap.pos);
341
342 var tiles = {left: Math.ceil((xMin + aPixels.left * gMap.zoomFactor) / size) -
343 (aPixels.left ? 0 : 1),
344 right: Math.floor((xMax - aPixels.right * gMap.zoomFactor) / size) -
345 (aPixels.right ? 1 : 0),
346 top: Math.ceil((yMin + aPixels.top * gMap.zoomFactor) / size) -
347 (aPixels.top ? 0 : 1),
348 bottom: Math.floor((yMax - aPixels.bottom * gMap.zoomFactor) / size) -
349 (aPixels.bottom ? 1 : 0)};
350
351 // Go through all the tiles in the map, find out if to draw them and do so.
352 for (var x = Math.floor(xMin / size); x < Math.ceil(xMax / size); x++) {
353 for (var y = Math.floor(yMin / size); y < Math.ceil(yMax / size); y++) { // slow script warnings on the tablet appear here!
354 // Only go to the drawing step if we need to draw this tile.
355 if (x < tiles.left || x > tiles.right ||
356 y < tiles.top || y > tiles.bottom) {
357 // Round here is **CRUCIAL** otherwise the images are filtered
358 // and the performance sucks (more than expected).
359 var xoff = Math.round((x * size - xMin) / gMap.zoomFactor);
360 var yoff = Math.round((y * size - yMin) / gMap.zoomFactor);
361 // Draw placeholder tile unless we overdraw.
362 if (!aOverdraw &&
363 (x < tiles.left -1 || x > tiles.right + 1 ||
364 y < tiles.top -1 || y > tiles.bottom + 1)) {
365 gMap.drawTileGL(xoff, yoff, 0);
366 }
367 // Initiate loading/drawing of the actual tile.
368 gTileService.get(gMap.activeMap, {x: x, y: y, z: gMap.pos.z},
369 function(aImage, aStyle, aCoords, aTileKey) {
370 // Only draw if this applies for the current view.
371 if ((aStyle == gMap.activeMap) && (aCoords.z == gMap.pos.z)) {
372 var ixMin = gMap.pos.x - wid / 2;
373 var iyMin = gMap.pos.y - ht / 2;
374 var ixoff = Math.round((aCoords.x * size - ixMin) / gMap.zoomFactor);
375 var iyoff = Math.round((aCoords.y * size - iyMin) / gMap.zoomFactor);
376 var URL = window.URL;
377 var imgURL = URL.createObjectURL(aImage);
378 var imgObj = new Image();
379 imgObj.src = imgURL;
380 imgObj.onload = function() {
381 // TODO: Do actually paint in a separate function, called on requestAnimationFrame.
382 var txIndex = gMap.glTextureKeys[aTileKey];
383 if (!txIndex) {
384 txIndex = Object.keys(gMap.glTextureKeys).length;
385 gMap.loadImageToTexture(imgObj, txIndex, aTileKey);
386 }
387 gMap.drawTileGL(ixoff, iyoff, txIndex);
388 URL.revokeObjectURL(imgURL);
389 }
390 }
391 });
392 }
393 }
394 }
395 },
396
397 resizeAndDraw: function() {
398 var viewportWidth = Math.min(window.innerWidth, window.outerWidth);
399 var viewportHeight = Math.min(window.innerHeight, window.outerHeight);
400 if (gGLMapCanvas && gTrackCanvas) {
401 gGLMapCanvas.width = viewportWidth;
402 gGLMapCanvas.height = viewportHeight;
403 gTrackCanvas.width = viewportWidth;
404 gTrackCanvas.height = viewportHeight;
405 if (gMap.gl) {
406 // Size viewport to canvas size.
407 gMap.gl.viewport(0, 0, gMap.gl.drawingBufferWidth, gMap.gl.drawingBufferHeight);
408 // Clear the color.
409 gMap.gl.clear(gMap.gl.COLOR_BUFFER_BIT);
410 // Make sure the vertex shader get the right resolution.
411 gMap.gl.uniform2f(gMap.glResolutionAttr, gGLMapCanvas.width, gGLMapCanvas.height);
412 }
413 gMap.draw();
414 showUI();
415 }
416 },
417
418 drawTileGL: function(aLeft, aRight, aTextureIndex) {
419 gMap.gl.activeTexture(gMap.gl.TEXTURE0 + aTextureIndex);
420 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTextureIndex]);
421 var x_start = aLeft;
422 var i_width = gMap.tileSize;
423 var y_start = aRight;
424 var i_height = gMap.tileSize;
425 var textureCoordinates = [
426 x_start, y_start,
427 x_start + i_width, y_start,
428 x_start, y_start + i_height,
429 x_start, y_start + i_height,
430 x_start + i_width, y_start,
431 x_start + i_width, y_start + i_height,
432 ];
433 gMap.gl.bufferData(gMap.gl.ARRAY_BUFFER, new Float32Array(textureCoordinates), gMap.gl.STATIC_DRAW);
434
435 // There are 6 indices in textureCoordinates.
436 gMap.gl.drawArrays(gMap.gl.TRIANGLES, 0, 6);
437 },
438
439 loadImageToTexture: function(aImage, aTextureIndex, aTileKey) {
440 gMap.glTextureKeys[aTileKey] = aTextureIndex;
441 // Create and bind texture.
442 gMap.glTextures[aTextureIndex] = gMap.gl.createTexture();
443 gMap.gl.activeTexture(gMap.gl.TEXTURE0 + aTextureIndex);
444 gMap.gl.bindTexture(gMap.gl.TEXTURE_2D, gMap.glTextures[aTextureIndex]);
445 gMap.gl.uniform1i(gMap.gl.getUniformLocation(gMap.glShaderProgram, "uImage"), 0);
446 // Set params for how the texture minifies and magnifies (wrap params are not needed as we're power-of-two).
447 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MIN_FILTER, gMap.gl.NEAREST);
448 gMap.gl.texParameteri(gMap.gl.TEXTURE_2D, gMap.gl.TEXTURE_MAG_FILTER, gMap.gl.NEAREST);
449 // Upload the image into the texture.
450 gMap.gl.texImage2D(gMap.gl.TEXTURE_2D, 0, gMap.gl.RGBA, gMap.gl.RGBA, gMap.gl.UNSIGNED_BYTE, aImage);
451 },
452}
453
454// Using scale(x, y) together with drawing old data on scaled canvas would be an improvement for zooming.
455// See https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Transformations#Scaling
456
457function zoomIn() {
458 if (gMap.pos.z < gMap.maxZoom) {
459 gMap.pos.z++;
460 gMap.draw();
461 }
462}
463
464function zoomOut() {
465 if (gMap.pos.z > 0) {
466 gMap.pos.z--;
467 gMap.draw();
468 }
469}
470
471function zoomTo(aTargetLevel) {
472 aTargetLevel = parseInt(aTargetLevel);
473 if (aTargetLevel >= 0 && aTargetLevel <= gMap.maxZoom) {
474 gMap.pos.z = aTargetLevel;
475 gMap.draw();
476 }
477}
478
479function gps2xy(aLatitude, aLongitude) {
480 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
481 var convLat = aLatitude * Math.PI / 180;
482 var rawY = (1 - Math.log(Math.tan(convLat) +
483 1 / Math.cos(convLat)) / Math.PI) / 2 * maxZoomFactor;
484 var rawX = (aLongitude + 180) / 360 * maxZoomFactor;
485 return {x: Math.round(rawX),
486 y: Math.round(rawY)};
487}
488
489function xy2gps(aX, aY) {
490 var maxZoomFactor = Math.pow(2, gMap.maxZoom) * gMap.tileSize;
491 var n = Math.PI - 2 * Math.PI * aY / maxZoomFactor;
492 return {latitude: 180 / Math.PI *
493 Math.atan(0.5 * (Math.exp(n) - Math.exp(-n))),
494 longitude: aX / maxZoomFactor * 360 - 180};
495}
496
497function setMapStyle() {
498 var mapSel = document.getElementById("mapSelector");
499 if (mapSel.selectedIndex >= 0 && gMap.activeMap != mapSel.value) {
500 gMap.activeMap = mapSel.value;
501 document.getElementById("copyright").innerHTML =
502 gMapStyles[gMap.activeMap].copyright;
503 showUI();
504 gMap.draw();
505 }
506}
507
508// A sane mod function that works for negative numbers.
509// Returns a % b.
510function mod(a, b) {
511 return ((a % b) + b) % b;
512}
513
514function normalizeCoords(aCoords) {
515 var zoomFactor = Math.pow(2, aCoords.z);
516 return {x: mod(aCoords.x, zoomFactor),
517 y: mod(aCoords.y, zoomFactor),
518 z: aCoords.z};
519}
520
521// Returns true if the tile is outside the current view.
522function isOutsideWindow(t) {
523 var pos = decodeIndex(t);
524
525 var zoomFactor = Math.pow(2, gMap.maxZoom - pos.z);
526 var wid = gMap.width * zoomFactor;
527 var ht = gMap.height * zoomFactor;
528
529 pos.x *= zoomFactor;
530 pos.y *= zoomFactor;
531
532 var sz = gMap.tileSize * zoomFactor;
533 if (pos.x > gMap.pos.x + wid / 2 || pos.y > gMap.pos.y + ht / 2 ||
534 pos.x + sz < gMap.pos.x - wid / 2 || pos.y - sz < gMap.pos.y - ht / 2)
535 return true;
536 return false;
537}
538
539function encodeIndex(x, y, z) {
540 var norm = normalizeCoords({x: x, y: y, z: z});
541 return norm.x + "," + norm.y + "," + norm.z;
542}
543
544function decodeIndex(encodedIdx) {
545 var ind = encodedIdx.split(",", 3);
546 return {x: ind[0], y: ind[1], z: ind[2]};
547}
548
549function drawTrack() {
550 gLastDrawnPoint = null;
551 gCurPosMapCache = undefined;
552 gTrackContext.clearRect(0, 0, gTrackCanvas.width, gTrackCanvas.height);
553 if (gTrack.length) {
554 for (var i = 0; i < gTrack.length; i++) {
555 drawTrackPoint(gTrack[i].coords.latitude, gTrack[i].coords.longitude,
556 (i + 1 >= gTrack.length));
557 }
558 }
559}
560
561function drawTrackPoint(aLatitude, aLongitude, lastPoint) {
562 var trackpoint = gps2xy(aLatitude, aLongitude);
563 // lastPoint is for optimizing (not actually executing the draw until the last)
564 trackpoint.optimized = (lastPoint === false);
565 var mappos = {x: Math.round((trackpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
566 y: Math.round((trackpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
567
568 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
569 gTrackContext.strokeStyle = gTrackColor;
570 gTrackContext.fillStyle = gTrackContext.strokeStyle;
571 gTrackContext.lineWidth = gTrackWidth;
572 gTrackContext.lineCap = "round";
573 gTrackContext.lineJoin = "round";
574 }
575 if (!gLastDrawnPoint || gLastDrawnPoint == trackpoint) {
576 // This breaks optimiziation, so make sure to close path and reset optimization.
577 if (gLastDrawnPoint && gLastDrawnPoint.optimized)
578 gTrackContext.stroke();
579 gTrackContext.beginPath();
580 trackpoint.optimized = false;
581 gTrackContext.arc(mappos.x, mappos.y,
582 gTrackContext.lineWidth, 0, Math.PI * 2, false);
583 gTrackContext.fill();
584 }
585 else {
586 if (!gLastDrawnPoint || !gLastDrawnPoint.optimized) {
587 gTrackContext.beginPath();
588 gTrackContext.moveTo(Math.round((gLastDrawnPoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
589 Math.round((gLastDrawnPoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2));
590 }
591 gTrackContext.lineTo(mappos.x, mappos.y);
592 if (!trackpoint.optimized)
593 gTrackContext.stroke();
594 }
595 gLastDrawnPoint = trackpoint;
596}
597
598function drawCurrentLocation(trackPoint) {
599 var locpoint = gps2xy(trackPoint.coords.latitude, trackPoint.coords.longitude);
600 var circleRadius = Math.round(gCurLocSize / 2);
601 var mappos = {x: Math.round((locpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
602 y: Math.round((locpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
603
604 undrawCurrentLocation();
605
606 // Cache overdrawn area.
607 gCurPosMapCache =
608 {point: locpoint,
609 radius: circleRadius,
610 data: gTrackContext.getImageData(mappos.x - circleRadius,
611 mappos.y - circleRadius,
612 circleRadius * 2, circleRadius * 2)};
613
614 gTrackContext.strokeStyle = gCurLocColor;
615 gTrackContext.fillStyle = gTrackContext.strokeStyle;
616 gTrackContext.beginPath();
617 gTrackContext.arc(mappos.x, mappos.y,
618 circleRadius, 0, Math.PI * 2, false);
619 gTrackContext.fill();
620}
621
622function undrawCurrentLocation() {
623 if (gCurPosMapCache) {
624 var oldpoint = gCurPosMapCache.point;
625 var oldmp = {x: Math.round((oldpoint.x - gMap.pos.x) / gMap.zoomFactor + gMap.width / 2),
626 y: Math.round((oldpoint.y - gMap.pos.y) / gMap.zoomFactor + gMap.height / 2)};
627 gTrackContext.putImageData(gCurPosMapCache.data,
628 oldmp.x - gCurPosMapCache.radius,
629 oldmp.y - gCurPosMapCache.radius);
630 gCurPosMapCache = undefined;
631 }
632}
633
634var mapEvHandler = {
635 handleEvent: function(aEvent) {
636 var touchEvent = aEvent.type.indexOf('touch') != -1;
637
638 if (touchEvent) {
639 aEvent.stopPropagation();
640 }
641
642 // Bail out if the event is happening on an input.
643 if (aEvent.target.tagName.toLowerCase() == "input")
644 return;
645
646 // Bail out on unwanted map moves, but not zoom or keyboard events.
647 if (aEvent.type.indexOf("mouse") === 0 || aEvent.type.indexOf("touch") === 0) {
648 // Bail out if this is neither a touch nor left-click.
649 if (!touchEvent && aEvent.button != 0)
650 return;
651
652 // Bail out if the started touch can't be found.
653 if (touchEvent && gDragging &&
654 !aEvent.changedTouches.identifiedTouch(gDragTouchID))
655 return;
656 }
657
658 var coordObj = touchEvent ?
659 aEvent.changedTouches.identifiedTouch(gDragTouchID) :
660 aEvent;
661
662 switch (aEvent.type) {
663 case "mousedown":
664 case "touchstart":
665 if (touchEvent) {
666 if (aEvent.targetTouches.length == 2) {
667 gPinchStartWidth = Math.sqrt(
668 Math.pow(aEvent.targetTouches.item(1).clientX -
669 aEvent.targetTouches.item(0).clientX, 2) +
670 Math.pow(aEvent.targetTouches.item(1).clientY -
671 aEvent.targetTouches.item(0).clientY, 2)
672 );
673 }
674 gDragTouchID = aEvent.changedTouches.item(0).identifier;
675 coordObj = aEvent.changedTouches.identifiedTouch(gDragTouchID);
676 }
677 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
678 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
679
680 if (touchEvent || aEvent.button === 0) {
681 gDragging = true;
682 }
683 gLastMouseX = x;
684 gLastMouseY = y;
685 showUI();
686 break;
687 case "mousemove":
688 case "touchmove":
689 if (touchEvent && aEvent.targetTouches.length == 2) {
690 curPinchStartWidth = Math.sqrt(
691 Math.pow(aEvent.targetTouches.item(1).clientX -
692 aEvent.targetTouches.item(0).clientX, 2) +
693 Math.pow(aEvent.targetTouches.item(1).clientY -
694 aEvent.targetTouches.item(0).clientY, 2)
695 );
696 if (!gPinchStartWidth)
697 gPinchStartWidth = curPinchStartWidth;
698
699 if (gPinchStartWidth / curPinchStartWidth > 1.7 ||
700 gPinchStartWidth / curPinchStartWidth < 0.6) {
701 var newZoomLevel = gMap.pos.z + (gPinchStartWidth < curPinchStartWidth ? 1 : -1);
702 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
703 // Calculate new center of the map - preserve middle of pinch.
704 // This means that pixel distance between old center and middle
705 // must equal pixel distance of new center and middle.
706 var x = (aEvent.targetTouches.item(1).clientX +
707 aEvent.targetTouches.item(0).clientX) / 2 -
708 gGLMapCanvas.offsetLeft;
709 var y = (aEvent.targetTouches.item(1).clientY +
710 aEvent.targetTouches.item(0).clientY) / 2 -
711 gGLMapCanvas.offsetTop;
712
713 // Zoom factor after this action.
714 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
715 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
716 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
717
718 if (gPinchStartWidth < curPinchStartWidth)
719 zoomIn();
720 else
721 zoomOut();
722
723 // Reset pinch start width and start another pinch gesture.
724 gPinchStartWidth = null;
725 }
726 }
727 // If we are in a pinch, do not drag.
728 break;
729 }
730 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
731 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
732 if (gDragging === true) {
733 var dX = x - gLastMouseX;
734 var dY = y - gLastMouseY;
735 gMap.pos.x -= dX * gMap.zoomFactor;
736 gMap.pos.y -= dY * gMap.zoomFactor;
737 if (false) { // use optimized path
738 /* TODO: investigate optimized path for GL - code below was 2D.
739 var mapData = gMapContext.getImageData(0, 0,
740 gMapCanvas.width,
741 gMapCanvas.height);
742 gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
743 gMapContext.putImageData(mapData, dX, dY);
744 gMap.draw({left: (dX > 0) ? dX : 0,
745 right: (dX < 0) ? -dX : 0,
746 top: (dY > 0) ? dY : 0,
747 bottom: (dY < 0) ? -dY : 0});
748 */
749 }
750 else {
751 gMap.draw(false, true);
752 }
753 showUI();
754 }
755 gLastMouseX = x;
756 gLastMouseY = y;
757 break;
758 case "mouseup":
759 case "touchend":
760 gPinchStartWidth = null;
761 gDragging = false;
762 showUI();
763 break;
764 case "mouseout":
765 case "touchcancel":
766 case "touchleave":
767 //gDragging = false;
768 break;
769 case "wheel":
770 // If we'd want pixels, we'd need to calc up using aEvent.deltaMode.
771 // See https://developer.mozilla.org/en-US/docs/Mozilla_event_reference/wheel
772
773 // Only accept (non-null) deltaY values
774 if (!aEvent.deltaY)
775 break;
776
777 // Debug output: "coordinates" of the point the mouse was over.
778 /*
779 var ptCoord = {x: gMap.pos.x + (x - gMap.width / 2) * gMap.zoomFactor,
780 y: gMap.pos.y + (x - gMap.height / 2) * gMap.zoomFactor};
781 var gpsCoord = xy2gps(ptCoord.x, ptCoord.y);
782 var pt2Coord = gps2xy(gpsCoord.latitude, gpsCoord.longitude);
783 console.log(ptCoord.x + "/" + ptCoord.y + " - " +
784 gpsCoord.latitude + "/" + gpsCoord.longitude + " - " +
785 pt2Coord.x + "/" + pt2Coord.y);
786 */
787
788 var newZoomLevel = gMap.pos.z + (aEvent.deltaY < 0 ? 1 : -1);
789 if ((newZoomLevel >= 0) && (newZoomLevel <= gMap.maxZoom)) {
790 // Calculate new center of the map - same point stays under the mouse.
791 // This means that the pixel distance between the old center and point
792 // must equal the pixel distance of the new center and that point.
793 var x = coordObj.clientX - gGLMapCanvas.offsetLeft;
794 var y = coordObj.clientY - gGLMapCanvas.offsetTop;
795
796 // Zoom factor after this action.
797 var newZoomFactor = Math.pow(2, gMap.maxZoom - newZoomLevel);
798 gMap.pos.x -= (x - gMap.width / 2) * (newZoomFactor - gMap.zoomFactor);
799 gMap.pos.y -= (y - gMap.height / 2) * (newZoomFactor - gMap.zoomFactor);
800
801 if (aEvent.deltaY < 0)
802 zoomIn();
803 else
804 zoomOut();
805 }
806 break;
807 case "keydown":
808 // Allow keyboard control to move and zoom the map.
809 // Should use aEvent.key instead of aEvent.which but needs bug 680830.
810 // See https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keydown
811 var dX = 0;
812 var dY = 0;
813 switch (aEvent.which) {
814 case 39: // right
815 dX = -gMap.tileSize / 2;
816 break;
817 case 37: // left
818 dX = gMap.tileSize / 2;
819 break;
820 case 38: // up
821 dY = gMap.tileSize / 2;
822 break;
823 case 40: // down
824 dY = -gMap.tileSize / 2;
825 break;
826 case 87: // w
827 case 107: // + (numpad)
828 case 171: // + (normal key)
829 zoomIn();
830 break;
831 case 83: // s
832 case 109: // - (numpad)
833 case 173: // - (normal key)
834 zoomOut();
835 break;
836 case 48: // 0
837 case 49: // 1
838 case 50: // 2
839 case 51: // 3
840 case 52: // 4
841 case 53: // 5
842 case 54: // 6
843 case 55: // 7
844 case 56: // 8
845 zoomTo(aEvent.which - 38);
846 break;
847 case 57: // 9
848 zoomTo(9);
849 break;
850 case 96: // 0 (numpad)
851 case 97: // 1 (numpad)
852 case 98: // 2 (numpad)
853 case 99: // 3 (numpad)
854 case 100: // 4 (numpad)
855 case 101: // 5 (numpad)
856 case 102: // 6 (numpad)
857 case 103: // 7 (numpad)
858 case 104: // 8 (numpad)
859 zoomTo(aEvent.which - 86);
860 break;
861 case 105: // 9 (numpad)
862 zoomTo(9);
863 break;
864 default: // not supported
865 console.log("key not supported: " + aEvent.which);
866 break;
867 }
868
869 // Move if needed.
870 if (dX || dY) {
871 gMap.pos.x -= dX * gMap.zoomFactor;
872 gMap.pos.y -= dY * gMap.zoomFactor;
873 if (false) { // use optimized path
874 /* TODO: investigate optimized path for GL - code below was 2D.
875 var mapData = gMapContext.getImageData(0, 0,
876 gMapCanvas.width,
877 gMapCanvas.height);
878 gMapContext.clearRect(0, 0, gMapCanvas.width, gMapCanvas.height);
879 gMapContext.putImageData(mapData, dX, dY);
880 gMap.draw({left: (dX > 0) ? dX : 0,
881 right: (dX < 0) ? -dX : 0,
882 top: (dY > 0) ? dY : 0,
883 bottom: (dY < 0) ? -dY : 0});
884 */
885 }
886 else {
887 gMap.draw(false, true);
888 }
889 }
890 break;
891 }
892 }
893};
894
895var geofake = {
896 tracking: false,
897 lastPos: {x: undefined, y: undefined},
898 watchPosition: function(aSuccessCallback, aErrorCallback, aPrefObject) {
899 this.tracking = true;
900 var watchCall = function() {
901 // calc new position in lat/lon degrees
902 // 90° on Earth surface are ~10,000 km at the equator,
903 // so try moving at most 10m at a time
904 if (geofake.lastPos.x)
905 geofake.lastPos.x += (Math.random() - .5) * 90 / 1000000
906 else
907 geofake.lastPos.x = 48.208174
908 if (geofake.lastPos.y)
909 geofake.lastPos.y += (Math.random() - .5) * 90 / 1000000
910 else
911 geofake.lastPos.y = 16.373819
912 aSuccessCallback({timestamp: Date.now(),
913 coords: {latitude: geofake.lastPos.x,
914 longitude: geofake.lastPos.y,
915 accuracy: 20}});
916 if (geofake.tracking)
917 setTimeout(watchCall, 1000);
918 };
919 setTimeout(watchCall, 1000);
920 return "foo";
921 },
922 clearWatch: function(aID) {
923 this.tracking = false;
924 }
925}
926
927function setCentering(aCheckbox) {
928 if (gMapPrefsLoaded && mainDB)
929 gPrefs.set("center_map", aCheckbox.checked);
930 gCenterPosition = aCheckbox.checked;
931}
932
933function setTracking(aCheckbox) {
934 if (gMapPrefsLoaded && mainDB)
935 gPrefs.set("tracking_enabled", aCheckbox.checked);
936 if (aCheckbox.checked)
937 startTracking();
938 else
939 endTracking();
940}
941
942function startTracking() {
943 if (gGeolocation) {
944 gActionLabel.textContent = "Establishing Position";
945 gAction.style.display = "block";
946 gGeoWatchID = gGeolocation.watchPosition(
947 function(position) {
948 if (gActionLabel.textContent) {
949 gActionLabel.textContent = "";
950 gAction.style.display = "none";
951 }
952 // Coords spec: https://developer.mozilla.org/en/XPCOM_Interface_Reference/NsIDOMGeoPositionCoords
953 var tPoint = {time: position.timestamp,
954 coords: {latitude: position.coords.latitude,
955 longitude: position.coords.longitude,
956 altitude: position.coords.altitude,
957 accuracy: position.coords.accuracy,
958 altitudeAccuracy: position.coords.altitudeAccuracy,
959 heading: position.coords.heading,
960 speed: position.coords.speed},
961 beginSegment: !gLastTrackPoint};
962 // Only add point to track is accuracy is good enough.
963 if (tPoint.coords.accuracy < gMinTrackAccuracy) {
964 gLastTrackPoint = tPoint;
965 gTrack.push(tPoint);
966 try { gTrackStore.push(tPoint); } catch(e) {}
967 var redrawn = false;
968 if (gCenterPosition) {
969 var posCoord = gps2xy(position.coords.latitude,
970 position.coords.longitude);
971 if (Math.abs(gMap.pos.x - posCoord.x) > gMap.width * gMap.zoomFactor / 4 ||
972 Math.abs(gMap.pos.y - posCoord.y) > gMap.height * gMap.zoomFactor / 4) {
973 gMap.pos.x = posCoord.x;
974 gMap.pos.y = posCoord.y;
975 gMap.draw(); // This draws the current point as well.
976 redrawn = true;
977 }
978 }
979 if (!redrawn)
980 undrawCurrentLocation();
981 drawTrackPoint(position.coords.latitude, position.coords.longitude, true);
982 }
983 drawCurrentLocation(tPoint);
984 },
985 function(error) {
986 // Ignore erros for the moment, but this is good for debugging.
987 // See https://developer.mozilla.org/en/Using_geolocation#Handling_errors
988 if (gDebug)
989 console.log(error.message);
990 },
991 {enableHighAccuracy: true}
992 );
993 }
994}
995
996function endTracking() {
997 if (gActionLabel.textContent) {
998 gActionLabel.textContent = "";
999 gAction.style.display = "none";
1000 }
1001 if (gGeoWatchID) {
1002 gGeolocation.clearWatch(gGeoWatchID);
1003 }
1004}
1005
1006function clearTrack() {
1007 gTrack = [];
1008 gTrackStore.clear();
1009 drawTrack();
1010}
1011
1012var gTileService = {
1013 objStore: "tilecache",
1014
1015 ageLimit: 14 * 86400 * 1000, // 2 weeks (in ms)
1016
1017 get: function(aStyle, aCoords, aCallback) {
1018 var norm = normalizeCoords(aCoords);
1019 var dbkey = aStyle + "::" + norm.x + "," + norm.y + "," + norm.z;
1020 this.getDBCache(dbkey, function(aResult, aEvent) {
1021 if (aResult) {
1022 // We did get a cached object.
1023 aCallback(aResult.image, aStyle, aCoords, dbkey);
1024 // Look at the timestamp and return if it's not too old.
1025 if (aResult.timestamp + gTileService.ageLimit > Date.now())
1026 return;
1027 // Reload cached tile otherwise.
1028 var oldDate = new Date(aResult.timestamp);
1029 console.log("reload cached tile: " + dbkey + " - " + oldDate.toUTCString());
1030 }
1031 // Retrieve image from the web and store it in the cache.
1032 var XHR = new XMLHttpRequest();
1033 XHR.open("GET",
1034 gMapStyles[aStyle].url
1035 .replace("{x}", norm.x)
1036 .replace("{y}", norm.y)
1037 .replace("{z}", norm.z)
1038 .replace("[a-c]", String.fromCharCode(97 + Math.floor(Math.random() * 2)))
1039 .replace("[1-4]", 1 + Math.floor(Math.random() * 3)),
1040 true);
1041 XHR.responseType = "blob";
1042 XHR.addEventListener("load", function () {
1043 if (XHR.status === 200) {
1044 var blob = XHR.response;
1045 aCallback(blob, aStyle, aCoords, dbkey);
1046 gTileService.setDBCache(dbkey, {image: blob, timestamp: Date.now()});
1047 }
1048 }, false);
1049 XHR.send();
1050 });
1051 },
1052
1053 getDBCache: function(aKey, aCallback) {
1054 if (!mainDB)
1055 return;
1056 var transaction = mainDB.transaction([this.objStore]);
1057 var request = transaction.objectStore(this.objStore).get(aKey);
1058 request.onsuccess = function(event) {
1059 aCallback(request.result, event);
1060 };
1061 request.onerror = function(event) {
1062 // Errors can be handled here.
1063 aCallback(undefined, event);
1064 };
1065 },
1066
1067 setDBCache: function(aKey, aValue, aCallback) {
1068 if (!mainDB)
1069 return;
1070 var success = false;
1071 var transaction = mainDB.transaction([this.objStore], "readwrite");
1072 var objStore = transaction.objectStore(this.objStore);
1073 var request = objStore.put(aValue, aKey);
1074 request.onsuccess = function(event) {
1075 success = true;
1076 if (aCallback)
1077 aCallback(success, event);
1078 };
1079 request.onerror = function(event) {
1080 // Errors can be handled here.
1081 if (aCallback)
1082 aCallback(success, event);
1083 };
1084 },
1085
1086 unsetDBCache: function(aKey, aCallback) {
1087 if (!mainDB)
1088 return;
1089 var success = false;
1090 var transaction = mainDB.transaction([this.objStore], "readwrite");
1091 var request = transaction.objectStore(this.objStore).delete(aKey);
1092 request.onsuccess = function(event) {
1093 success = true;
1094 if (aCallback)
1095 aCallback(success, event);
1096 };
1097 request.onerror = function(event) {
1098 // Errors can be handled here.
1099 if (aCallback)
1100 aCallback(success, event);
1101 }
1102 },
1103
1104 clearDB: function(aCallback) {
1105 if (!mainDB)
1106 return;
1107 var success = false;
1108 var transaction = mainDB.transaction([this.objStore], "readwrite");
1109 var request = transaction.objectStore(this.objStore).clear();
1110 request.onsuccess = function(event) {
1111 success = true;
1112 if (aCallback)
1113 aCallback(success, event);
1114 };
1115 request.onerror = function(event) {
1116 // Errors can be handled here.
1117 if (aCallback)
1118 aCallback(success, event);
1119 }
1120 }
1121};