Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

TileScheduler is only created if the browser supports web workers

Mike McGanna56c7ec3502d
diff --git a/src/js/Worldview/Map.js b/src/js/Worldview/Map.js
index 759ae65f4..502ec6511 100644
--- a/src/js/Worldview/Map.js
+++ b/src/js/Worldview/Map.js
@@ -1,14 +1,14 @@
/*
* NASA Worldview
- *
+ *
* This code was originally developed at NASA/Goddard Space Flight Center for
- * the Earth Science Data and Information System (ESDIS) project.
+ * the Earth Science Data and Information System (ESDIS) project.
*
- * Copyright (C) 2013 United States Government as represented by the
+ * Copyright (C) 2013 United States Government as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All Rights Reserved.
*/
-
+
/**
* @module Worldview
*/
@@ -16,83 +16,83 @@ Worldview.namespace("Map");
/**
* Utilities for OpenLayers.
- *
+ *
* @class Map
* @static
*/
$(function(ns) {
-
+
var logPosition = Logging.getLogger("Worldview.Map.Position");
-
+
ns.CRS_WGS_84 = "EPSG:4326";
-
+
ns.CRS_WGS_84_QUERY_EXTENT = new OpenLayers.Bounds(-180, -60, 180, 60);
-
- ns.CRS_WGS_84_QUERY_MASK =
+
+ ns.CRS_WGS_84_QUERY_MASK =
new OpenLayers.Geometry.MultiPolygon([
new OpenLayers.Bounds(-180, -90, 180, -60).toGeometry(),
new OpenLayers.Bounds(-180, 60, 180, 90).toGeometry()
]);
-
+
/**
* An object that contains OpenLayers.Control.MousePosition objects
* that update the current latitude/longitude values on the map as the
* mouse moves. Keyed by projection name, either "geographic", "arctic",
* or "antarctic".
- *
+ *
* Example:
- *
+ *
* var control = Worldview.Map.COORDINATE_CONTROLS["geographic"];
- *
+ *
* @attribute COORDINATE_CONTROLS
* @final
*/
ns.COORDINATE_CONTROLS = {
"geographic": new OpenLayers.Control.MousePosition({
- formatOutput: function(mouseLonLat) {
+ formatOutput: function(mouseLonLat) {
if ( logPosition.isDebugEnabled() ) {
- logPosition.debug(mouseLonLat.lon.toFixed(3) + "," +
- mouseLonLat.lat.toFixed(3));
- }
- return mouseLonLat.lon.toFixed(3) + "°, " +
+ logPosition.debug(mouseLonLat.lon.toFixed(3) + "," +
+ mouseLonLat.lat.toFixed(3));
+ }
+ return mouseLonLat.lon.toFixed(3) + "°, " +
mouseLonLat.lat.toFixed(3) + "°";
- }
+ }
}),
"arctic": new OpenLayers.Control.MousePosition({
projection: "EPSG:3413",
- formatOutput: function(mouseLonLat) {
+ formatOutput: function(mouseLonLat) {
if ( logPosition.isDebugEnabled() ) {
- logPosition.debug(Math.round(mouseLonLat.lon) + "," +
- Math.round(mouseLonLat.lat));
- }
- return this.projection + " " +
- Math.round(mouseLonLat.lon) + "m, " +
- Math.round(mouseLonLat.lat) + "m";
+ logPosition.debug(Math.round(mouseLonLat.lon) + "," +
+ Math.round(mouseLonLat.lat));
+ }
+ return this.projection + " " +
+ Math.round(mouseLonLat.lon) + "m, " +
+ Math.round(mouseLonLat.lat) + "m";
}
}),
"antarctic": new OpenLayers.Control.MousePosition({
- formatOutput: function(mouseLonLat) {
+ formatOutput: function(mouseLonLat) {
if ( logPosition.isDebugEnabled() ) {
- logPosition.debug(Math.round(mouseLonLat.lon) + "," +
- Math.round(mouseLonLat.lat));
- }
- return "EPSG:3031 " +
- Math.round(mouseLonLat.lon) + "m, " +
- Math.round(mouseLonLat.lat) + "m";
+ logPosition.debug(Math.round(mouseLonLat.lon) + "," +
+ Math.round(mouseLonLat.lat));
+ }
+ return "EPSG:3031 " +
+ Math.round(mouseLonLat.lon) + "m, " +
+ Math.round(mouseLonLat.lat) + "m";
},
})
};
-
+
/**
* Determines if an exent object contains valid values.
- *
+ *
* @method isExtentValid
- * @static
- *
+ * @static
+ *
* @param extent {OpenLayers.Bound} The extent to check.
- *
- * @return {boolean} False if any of the values is NaN, otherwise returns
+ *
+ * @return {boolean} False if any of the values is NaN, otherwise returns
* true.
*/
ns.isExtentValid = function(extent) {
@@ -103,58 +103,60 @@ $(function(ns) {
$.each(extent.toArray(), function(index, value) {
if ( isNaN(value) ) {
valid = false;
- }
+ }
});
return valid;
};
-
+
/**
* Scheduler used to render canvas tiles.
- *
+ *
* @attribute TILE_SCHEDULER {Scheduler}
* @static
* @readOnly
*/
- ns.TILE_SCHEDULER = Worldview.Scheduler({
- script: "js/Worldview/Map/TileWorker.js?v=" + Worldview.BUILD_NONCE,
- max: 4
- });
+ ns.TILE_SCHEDULER = Worldview.Scheduler.isSupported()
+ ? Worldview.Scheduler({
+ script: "js/Worldview/Map/TileWorker.js?v=" + Worldview.BUILD_NONCE,
+ max: 4
+ })
+ : null;
/**
* Sets the opacity of a layer. Since the backbuffer can interfere with
- * tile layers that have transparency, the transition effect is set to
+ * tile layers that have transparency, the transition effect is set to
* none if the opacity is not equal to one.
- *
+ *
* @method setOpacity
* @static
- *
+ *
* @param layer {OpenLayers.Layer} The layer to set the opacity
* @param opacity {float} A value from 0 (transparent) to 1 (opaque).
*/
- ns.setOpacity = function(layer, opacity) {
+ ns.setOpacity = function(layer, opacity) {
layer.setOpacity(opacity);
if ( opacity === 1 ) {
var effect = layer.originalTransitionEffect || "resize";
- layer.transitionEffect = effect;
+ layer.transitionEffect = effect;
} else {
layer.originalTransitionEffect = layer.transitionEffect;
layer.transitionEffect = "none";
- }
+ }
};
-
+
/**
- * Sets the visiblity of a layer. If the layer is supposed to be not
- * visible, this actually sets the opacity to zero. This allows the
+ * Sets the visiblity of a layer. If the layer is supposed to be not
+ * visible, this actually sets the opacity to zero. This allows the
* quick transition effects between days.
- *
+ *
* @method setVisibility
* @static
- *
+ *
* @param layer {OpenLayers.Layer} The layer to set the visiblity.
- *
+ *
* @param visible {boolean} True if the layer should be visible, otherwise
* false.
- *
+ *
* @param opacity {float} The opacity that this layer should be if it
* is visible. A value from 0 (transparent) to 1 (opaque).
*/
@@ -163,23 +165,23 @@ $(function(ns) {
layer.setVisibility(visible);
} else {
var actualOpacity = ( visible ) ? opacity : 0;
- layer.div.style.opacity = actualOpacity;
+ layer.div.style.opacity = actualOpacity;
if ( visible && opacity > 0 && !layer.getVisibility() ) {
layer.setVisibility(true);
}
}
};
-
+
ns.getLayerByName = function(map, name) {
var layers = map.getLayersByName(name);
if ( layers && layers.length > 1 ) {
- throw new Error("Multiple layers found for: " + name);
+ throw new Error("Multiple layers found for: " + name);
}
if ( layers ) {
return layers[0];
}
};
-
+
ns.isPolygonValid = function(polygon, maxDistance) {
var outerRing = polygon.components[0];
for ( var i = 0; i < outerRing.components.length - 1; i++ ) {
@@ -188,10 +190,10 @@ $(function(ns) {
if ( Math.abs(p2.x - p1.x) > maxDistance ) {
return false;
}
- }
+ }
return true;
};
-
+
ns.adjustAntiMeridian = function(polygon, adjustSign) {
var outerRing = polygon.components[0];
var points = outerRing.components.slice();
@@ -202,45 +204,45 @@ $(function(ns) {
points[i].x + 360, points[i].y);
}
if ( adjustSign < 0 && points[i].x > 0 ) {
- points[i] = new OpenLayers.Geometry.Point(
+ points[i] = new OpenLayers.Geometry.Point(
points[i].x - 360, points[i].y);
- }
+ }
}
return new OpenLayers.Geometry.Polygon(
[new OpenLayers.Geometry.LinearRing(points)]
);
};
-
+
ns.distance2D = function(p1, p2) {
- return Math.sqrt(Math.pow(p1.x - p2.x, 2) +
+ return Math.sqrt(Math.pow(p1.x - p2.x, 2) +
(Math.pow(p1.y - p2.y, 2)));
};
-
+
ns.distanceX = function(p1, p2) {
return Math.abs(p2.x - p1.x);
};
-
+
ns.interpolate2D = function(p1, p2, amount) {
var distX = p2.x - p1.x;
var distY = p2.y - p1.y;
-
+
var interpX = p1.x + (distX * amount);
var interpY = p1.y + (distY * amount);
-
+
return new OpenLayers.Geometry.Point(interpX, interpY);
};
-
+
// If multipolygon, return a list of the polygons. If polygon, return
// the single item in a list
ns.toPolys = function(geom) {
var polys = [];
if ( geom.CLASS_NAME === "OpenLayers.Geometry.MultiPolygon" ) {
- polys = geom.components;
+ polys = geom.components;
} else {
polys = [geom];
}
- return polys;
+ return polys;
};
-
-
+
+
}(Worldview.Map));
diff --git a/src/js/Worldview/Scheduler.js b/src/js/Worldview/Scheduler.js
index 45f40d380..1849981eb 100644
--- a/src/js/Worldview/Scheduler.js
+++ b/src/js/Worldview/Scheduler.js
@@ -1,10 +1,10 @@
/*
* NASA Worldview
- *
+ *
* This code was originally developed at NASA/Goddard Space Flight Center for
- * the Earth Science Data and Information System (ESDIS) project.
+ * the Earth Science Data and Information System (ESDIS) project.
*
- * Copyright (C) 2013 United States Government as represented by the
+ * Copyright (C) 2013 United States Government as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All Rights Reserved.
*/
@@ -12,42 +12,42 @@
/**
* Class: Worldview.Scheduler
* Executes jobs in web workers and queues requests if busy.
- *
- * Logger:
+ *
+ * Logger:
* Worldview.Scheduler
- *
+ *
* Constructor: Scheduler
* Creates a new instance.
- *
- * Parameters:
+ *
+ * Parameters:
* config.script - The path to the script that contains the code for the
- * web worker. This path should be relative to the application
+ * web worker. This path should be relative to the application
* root.
* config.max - Number of workers to start. Requests up to this number can
- * run concurrently--after this jobs are queued.
+ * run concurrently--after this jobs are queued.
* config.factory - Use this function to create web workers instead of invoking
* new directly.
- *
+ *
*/
Worldview.Scheduler = function(config) {
-
+
var log = Logging.getLogger("Worldview.Scheduler");
var self = {};
-
+
// Array of web workers equal to the size of maxWorkers
var workers = [];
-
+
// For each worker, contains the job identifier that is currently being
// executed
var jobExecuting = [];
-
+
// Jobs which cannot be submitted immedately are placed in this queyue.
var queue = [];
-
+
// Each job is assigned an ID. This holds the next available number.
var nextId = 1;
-
- // Information about jobs being tracked is place here keyed by jobId.
+
+ // Information about jobs being tracked is place here keyed by jobId.
// Includes:
// jobId: job identifier
// callback: callback to be invoked after work has completed.
@@ -56,13 +56,13 @@ Worldview.Scheduler = function(config) {
// postedTime: time in ms that the job was posted to the worker for
// execution.
var jobs = {};
-
+
// Number of jobs that are currently being executed
var executing = 0;
-
+
// Number of workers to start
var maxWorkers = config.max || 1;
-
+
//-------------------------------------------------------------------------
// Public
//-------------------------------------------------------------------------
@@ -70,26 +70,26 @@ Worldview.Scheduler = function(config) {
var init = function() {
var factory = config.factory || function() {
return new Worker(config.script);
- }
+ };
var max = config.max || 1;
-
+
for ( var i = 0; i < max; i++ ) {
- var worker = factory(config.script);
- worker.addEventListener("message", onSuccess, false);
- worker.addEventListener("error", onError, false);
+ var worker = factory(config.script);
+ worker.addEventListener("message", onSuccess, false);
+ worker.addEventListener("error", onError, false);
workers[i] = worker;
// Attach the index of the worker itself to the worker. This is
// useful for identifying the correct worker on an error event.
- workers[i].id = i;
+ workers[i].id = i;
}
};
-
+
/**
* Property: profile
* If true, statistics are collected in the <stats> property.
*/
self.profile = false;
-
+
/**
* Property: stats
* If <profile> is set to true, <Stats> will be collected in this object.
@@ -104,29 +104,29 @@ Worldview.Scheduler = function(config) {
averageExecutionTime: 0.0,
maximumExecutionTime: 0.0,
};
-
+
/**
* Function: submit
- *
+ *
* Submit a job to be executed when a worker becomes available.
- *
+ *
* Parameters:
* spec.message - Data sent to the worker.
- * spec.callback - Callback to be executed when the job completes. The
- * callback should accept one argument, a <Results>
+ * spec.callback - Callback to be executed when the job completes. The
+ * callback should accept one argument, a <Results>
* object.
- * spec.self - If needed, the this object to be returned in the
+ * spec.self - If needed, the this object to be returned in the
* callback.
- *
+ *
* Returns:
* The numeric identifier assigned to this job.
- *
+ *
* Throws:
* An exception if spec.callback is not a function.
*/
self.submit = function(spec) {
if ( typeof spec.callback !== "function" ) {
- throw new Error("spec.callback is not defined or is not a " +
+ throw new Error("spec.callback is not defined or is not a " +
"function");
}
@@ -137,21 +137,21 @@ Worldview.Scheduler = function(config) {
callback: spec.callback,
self: spec.self || null
};
-
+
if ( self.profile ) {
job.creationTime = new Date();
}
jobs[id] = job;
-
+
log.debug("Executing: " + executing);
if ( executing < maxWorkers ) {
execute(job);
} else {
enqueue(job);
- }
- return id;
+ }
+ return id;
};
-
+
/**
* Function: cancel
* Clears all jobs from the queue and messages all active works to stop.
@@ -160,57 +160,57 @@ Worldview.Scheduler = function(config) {
if ( log.isDebugEnabled() ) {
$.each(job, function(index, queue) {
log.debug("Removed job " + job.id + " from queue");
- })
+ });
}
queue = [];
$.each(worker, function(jobId, workers) {
log.debug("Cancelling job " + jobId);
- worker.postMessage({command: "cancel"});
+ worker.postMessage({command: "cancel"});
});
};
-
+
//-------------------------------------------------------------------------
// Private
//-------------------------------------------------------------------------
-
+
/*
* Called when the worker completes a job.
*/
- var onSuccess = function(event) {
+ var onSuccess = function(event) {
var results = event.data;
- log.debug("Completed job " + results.id + ", backlog: " +
+ log.debug("Completed job " + results.id + ", backlog: " +
queue.length);
notify(event, jobs[results.id]);
};
-
+
/*
- * Called when the worker fails due to a thrown exception.
+ * Called when the worker fails due to a thrown exception.
*/
var onError = function(event) {
// Grab the worker id that was stuffed into the worker object and
// use that to lookup the job id
workerId = event.target.id;
jobId = jobExecuting[workerId];
-
+
results = {
id: jobId,
- status: "error",
- }
+ status: "error",
+ };
event.data = results;
- log.debug("Error on job " + results.id + ": " + event.message +
+ log.debug("Error on job " + results.id + ": " + event.message +
", " + "backlog: " + queue.length);
notify(event, jobs[results.id]);
};
-
+
/*
- * Notifies via callback that work has completed, collects statistics
+ * Notifies via callback that work has completed, collects statistics
* if needed, and processes the next item in the queue.
*/
var notify = function(event, job, callback) {
executing--;
if ( self.profile ) {
collectStatistics(job);
- }
+ }
job.callback({
id: job.id,
message: event.data.message,
@@ -220,18 +220,18 @@ Worldview.Scheduler = function(config) {
delete jobs[job.id];
var workerId = event.target.id;
delete jobExecuting[workerId];
-
+
processQueue();
};
-
+
/*
* Executes the given job in the next available web worker.
- */
+ */
var execute = function(job) {
var workerId = executing++;
- log.debug("Executing job " + job.id + ", worker " + workerId +
+ log.debug("Executing job " + job.id + ", worker " + workerId +
", backlog: " + queue.length);
-
+
if ( self.profile ) {
job.postedTime = new Date();
}
@@ -239,17 +239,17 @@ Worldview.Scheduler = function(config) {
command: "execute",
id: job.id,
message: job.message,
- }
+ };
jobExecuting[workerId] = job.id;
- workers[workerId].postMessage(post);
+ workers[workerId].postMessage(post);
};
-
+
/*
* Places a job in the queue
*/
var enqueue = function(job) {
var queueLength = queue.length + 1;
- log.debug("Queueing job " + job.id + ", backlog: " + queueLength);
+ log.debug("Queueing job " + job.id + ", backlog: " + queueLength);
if ( self.profile ) {
self.stats.queued++;
job.queuedTime = new Date().getTime();
@@ -259,7 +259,7 @@ Worldview.Scheduler = function(config) {
queue.push(job);
//queue.shift(job);
};
-
+
/*
* If the queue is not empty, dequeues the next job and executes.
*/
@@ -270,9 +270,9 @@ Worldview.Scheduler = function(config) {
//var job = queue.shift();
var job = queue.pop();
execute(job);
- }
+ }
};
-
+
/*
* Collect statistics after a job has been executed
*/
@@ -281,98 +281,98 @@ Worldview.Scheduler = function(config) {
var endTime = new Date();
var totalTime = endTime - job.creationTime;
var executionTime = endTime - job.postedTime;
-
+
stats.executed++;
var previousRatio = (stats.executed - 1) / stats.executed;
var thisRatio = 1 / stats.executed;
-
- stats.averageTime =
+
+ stats.averageTime =
(stats.averageTime * previousRatio) + (totalTime * thisRatio);
- stats.maximumTime =
+ stats.maximumTime =
Math.max(totalTime, stats.maximumTime);
- stats.averageExecutionTime =
- (stats.averageExecutionTime * previousRatio) +
+ stats.averageExecutionTime =
+ (stats.averageExecutionTime * previousRatio) +
(executionTime * thisRatio);
- stats.maximumExecutionTime =
+ stats.maximumExecutionTime =
Math.max(executionTime, stats.maximumExecutionTime);
-
+
var queueTime = 0;
if ( job.queuedTime ) {
queueTime = job.postedTime - job.queuedTime;
previousRatio = (stats.queued - 1) / stats.queued;
thisRatio = 1 / stats.queued;
-
- stats.averageQueueTime =
+
+ stats.averageQueueTime =
(stats.averageQueueTime * previousRatio) +
(queueTime * thisRatio);
stats.maximumQueueTime =
Math.max(stats.maximumQueueTime, queueTime);
}
log.debug("Job " + job.id + ": total " + totalTime + "ms, queue " +
- queueTime + "ms, execution " + executionTime + "ms");
- };
+ queueTime + "ms, execution " + executionTime + "ms");
+ };
init();
return self;
-
+
};
/**
* Section: Static Functions
- *
+ *
* Function: isSupported
* Returns true if Worker is defined in the window object.
*/
Worldview.Scheduler.isSupported = function() {
return window.Worker !== undefined;
-}
+};
/**
* Class: Worldview.Scheduler.Stats
- * Contains statistics gathered from the <Scheduler> when <Scheduler.profile>
+ * Contains statistics gathered from the <Scheduler> when <Scheduler.profile>
* is set to true.
- *
+ *
* Property: queued
- * Total number of jobs that could not be serviced immedately and were placed
+ * Total number of jobs that could not be serviced immedately and were placed
* in the queue.
- *
+ *
* Property: executed
* Total number of jobs that have been executed.
- *
+ *
* Property: averageTime
* Average time, in milliseconds, taken to complete requests.
- *
+ *
* Property: maxmimumTime
* Maximum time, in milliseconds, taken to complete requests.
- *
+ *
* Property: averageQueueTime
- * Average time, in milliseconds, that jobs waited in the queue before being
+ * Average time, in milliseconds, that jobs waited in the queue before being
* executed.
- *
+ *
* Property: maximumQueueTime
- * Maximum time, in milliseconds, that a job waited in the queue before being
+ * Maximum time, in milliseconds, that a job waited in the queue before being
* executed.
- *
+ *
* Property: averageExecutionTime
* Average time, in milliseconds, that jobs took to execute in the web worker.
- *
+ *
* Property: maximumExecutionTime
* Maximum time, in milliseconds, that a job took to execute in the web worker.
*/
-/**
+/**
* Class: Worldview.Scheduler.Results
* Object that contains information on a completed job.
- *
+ *
* Property: id
* The numeric identifier assigned to this job
- *
+ *
* Property: message
* The data content returned by the worker.
- *
+ *
* Property: status
* Either "success", "error", or "cancel"
- *
+ *
* Property: self
* If provided, the "this" context of the caller.
*/
\ No newline at end of file