Interactive interface for browsing global, full-resolution satellite imagery
migrate image-download to worldview-components
Benjamin King82e97558dcf0
diff --git a/web/js/image/panel.js b/web/js/image/panel.jsindex a530819ee..a55bf3786 100644--- a/web/js/image/panel.js+++ b/web/js/image/panel.js@@ -4,25 +4,75 @@ import 'jquery-ui/dialog';import lodashEach from 'lodash/each';import lodashIsUndefined from 'lodash/isUndefined';import olProj from 'ol/proj';-import { GA as googleAnalytics } from 'worldview-components';+import { GA as googleAnalytics, ImageResSelection } from 'worldview-components';import util from '../util/util';import wvui from '../ui/ui';+import React from 'react';+import ReactDOM from 'react-dom';++const resolutionsGeo = {+ values: [+ { value: '0.125', text: '30m' },+ { value: '0.25', text: '60m' },+ { value: '0.5', text: '125m' },+ { value: '1', text: '250m' },+ { value: '2', text: '500m' },+ { value: '4', text: '1km' },+ { value: '20', text: '5km' },+ { value: '40', text: '10km' }+ ]+};+const resolutionsPolar = {+ values: [+ { value: '1', text: '250m' },+ { value: '2', text: '500m' },+ { value: '4', text: '1km' },+ { value: '20', text: '5km' },+ { value: '40', text: '10km' }+ ]+};+const fileTypesGeo = {+ values: [+ { value: 'image/jpeg', text: 'JPEG' },+ { value: 'image/png', text: 'PNG' },+ { value: 'image/geotiff', text: 'GeoTIFF' },+ { value: 'image/kmz', text: 'KMZ' }+ ]+};+const fileTypesPolar = {+ values: [+ { value: 'image/jpeg', text: 'JPEG' },+ { value: 'image/png', text: 'PNG' },+ { value: 'image/geotiff', text: 'GeoTIFF' }+ ]+};-export function imagePanel(models, ui, config) {+export function imagePanel (models, ui, config, dialogConfig) {var self = {};var container;var url;var alignTo = config.alignTo;- var containerId = 'imagedownload';- var id = containerId;var coords;var resolution = '1';var format = 'image/jpeg';var worldfile = 'false';var lastZoom = -1;-- var host, path;+ var htmlElements;+ var host;+ var path;+ var containerId = 'wv-image-button';+ var id = containerId;+ // state items as global vars+ var lonlats;+ var imgWorldfile;+ var imgFormat;+ var imgWidth;+ var imgHeight;+ var imgRes;+ var imgFilesize;+ var resolutions;+ var fileTypes;if (config.features.imageDownload) {host = config.features.imageDownload.host;@@ -37,111 +87,102 @@ export function imagePanel(models, ui, config) {util.warn('Redirecting image download to: ' + url);}- var init = function () {- ui.rubberband.events.on('update', update);- ui.rubberband.events.on('show', show);+ var init = function() {+ var options;++ checkConfig();+ htmlElements = document.createElement('div');+ setProjectionGlobals();+ options = {+ resolution: resolution,+ worldfile: worldfile,+ onSelectionChange: onSelectionChange,+ onDownloadClick: onDownload,+ fileType: format,+ valid: true,+ resolutions: resolutions,+ fileTypes: fileTypes+ };++ self.reactComponent = renderPanel(options, htmlElements);+ };+ var setProjectionGlobals = function() {+ if (models.proj.selected.id === 'geographic') {+ resolutions = resolutionsGeo;+ fileTypes = fileTypesGeo;+ } else {+ resolutions = resolutionsPolar;+ fileTypes = fileTypesPolar;+ }};+ var onSelectionChange = function(res, worldfile, format) {+ imgWorldfile = worldfile;+ imgFormat = format;+ imgRes = res;+ self.update(coords);+ };++ var checkConfig = function() {+ if (config.features.imageDownload) {+ host = config.features.imageDownload.host;+ path = config.parameters.imagegen || config.features.imageDownload.path;+ } else {+ host = 'http://map2.vis.earthdata.nasa.gov';+ path = 'imagegen/index.php';+ }+ url = host + '/' + path + '?';+ if (config.parameters.imagegen) {+ util.warn('Redirecting image download to: ' + url);+ }+ };+ var getUpdatedProps = function() {+ return {+ resolution: imgRes,+ proj: models.proj.selected.id,+ worldfile: worldfile,+ valid: fileSizeValid(),+ fileSize: imgFilesize,+ imgHeight: imgHeight,+ imgWidth: imgWidth,+ resolutions: resolutions,+ fileTypes: fileTypes+ };+ };+ var renderPanel = function(options, mountEl) {+ return ReactDOM.render(React.createElement(ImageResSelection, options), mountEl);+ };+ var updatePanel = function(options) {+ self.reactComponent.setState(options);+ };/*** Initialize a map object in Lat/Long projection, and add a "fake" layer to compute the map math.* Display the HTML UI with UI options. ** @this {Download}*/- var show = function () {+ self.show = function() {alignTo = {id: 'wv-image-button'};container = document.getElementById(containerId);if (container === null) {- throw new Error('Error: element \'' + containerId + '\' not found!');+ throw new Error("Error: element '" + containerId + "' not found!");}container.setAttribute('class', 'imagedownload');- setPosition();- $(window)- .resize(setPosition);-- var htmlElements =- '<div class=\'wv-image-header\'>' +- '<select id=\'wv-image-resolution\'>' +- '<option value=\'0.125\'>30m</option>' +- '<option value=\'0.25\'>60m</option>' +- '<option value=\'0.5\'>125m</option>' +- '<option value=\'1\' selected>250m</option>' +- '<option value=\'2\'>500m</option>' +- '<option value=\'4\'>1km</option>' +- '<option value=\'20\'>5km</option>' +- '<option value=\'40\'>10km</option>' +- '</select>Resolution (per pixel)</div>' +- '<div class=\'wv-image-header\'>' +- '<select id=\'wv-image-format\'>' +- '<option value=\'image/jpeg\'>JPEG</option>' +- '<option value=\'image/png\'>PNG</option>' +- '<option value=\'image/geotiff\'>GeoTIFF</option>' +- '<option value=\'image/kmz\'>KMZ</option>' +- '</select>Format</div>' +- '<div class=\'wv-image-header\'>' +- '<select id=\'wv-image-worldfile\' > ' +- '<option value=\'false\'>No</option>' +- '<option value=\'true\'>Yes</option>' +- '</select>Worldfile (.zip)</div>' +- '<table class=\'wv-image-download\'>' +- '<tr>' +- '<th>Raw Size</th>' +- '<th>Maximum</th>' +- '</tr>' +- '<tr>' +- '<td id=\'wv-image-size\' class=\'wv-image-size\'>000.00MB</td>' +- '<td class=\'wv-image-size\'>250 MB</td>' +- '</tr>' +- '<tr>' +- '<td><span id=\'wv-image-width\'>0000</span> x <span id=\'wv-image-height\'>0000</span> px</td>' +- '<td><button id=\'wv-image-download-button\'>Download</button>' +- '</tr>' +- '</table>' +- '</div>';-var $dialog = wvui.getDialog().html(htmlElements);- $dialog.dialog({- dialogClass: 'wv-panel wv-image',- title: 'Take a snapshot',- show: {- effect: 'slide',- direction: 'up'- },- hide: {- effect: 'slide',- direction: 'up'- },- width: 230,- height: 'auto',- minHeight: 10,- draggable: false,- resizable: false,- autoOpen: false- });+ $dialog.dialog(dialogConfig);// $("#wv-image-resolution").buttonset();// $("#wv-image-format").buttonset();$('#wv-image-download-button').button();$('.ui-dialog').zIndex(600);-- // Remove higher resolution options from polar views since no higher- // resolution polar layers currenly exist- if (models.proj.selected.id !== 'geographic') {- $('#wv-image-format [value=\'image/kmz\']')- .remove();- $('#wv-image-resolution [value=\'0.5\']')- .remove();- $('#wv-image-resolution [value=\'0.25\']')- .remove();- $('#wv-image-resolution [value=\'0.125\']')- .remove();- }+ $(window)+ .resize(setPosition);// Auto-set default resolution to map's current zoom level; round it// for incremental zoom steps@@ -150,7 +191,7 @@ export function imagePanel(models, ui, config) {// Don't do anything if the user hasn't changed zoom levels; we want to// preserve their existing settings- if (curZoom != lastZoom) {+ if (curZoom !== lastZoom) {lastZoom = curZoom;var nZoomLevels = models.proj.selected.resolutions.length;var curResolution = (curZoom >= nZoomLevels)@@ -158,11 +199,13 @@ export function imagePanel(models, ui, config) {: models.proj.selected.resolutions[curZoom];// Estimate the option value used by "wv-image-resolution"- var resolutionEstimate = (models.proj.selected.id == 'geographic')+ var resolutionEstimate = (models.proj.selected.id === 'geographic')? curResolution / 0.002197265625 : curResolution / 256.0;// Find the closest match of resolution within the available values- var possibleResolutions = (models.proj.selected.id == 'geographic') ? [0.125, 0.25, 0.5, 1, 2, 4, 20, 40] : [1, 2, 4, 20, 40];+ var possibleResolutions = (models.proj.selected.id === 'geographic')+ ? [0.125, 0.25, 0.5, 1, 2, 4, 20, 40]+ : [1, 2, 4, 20, 40];var bestDiff = Infinity;var bestIdx = -1;var currDiff = 0;@@ -177,7 +220,7 @@ export function imagePanel(models, ui, config) {// Bump up resolution in certain cases where default is too lowif (bestIdx > 0) {- if (models.proj.selected.id == 'geographic') {+ if (models.proj.selected.id === 'geographic') {switch (curZoom) {case 3:case 4:@@ -195,37 +238,10 @@ export function imagePanel(models, ui, config) {}}}+ imgRes = resolution;+ updatePanel(getUpdatedProps());}- $('#wv-image-format')- .change(function () {- format = $('#wv-image-format option:checked')- .val();- update(coords);- });-- $('#wv-image-worldfile')- .change(function () {- worldfile = $('#wv-image-worldfile option:checked')- .val();- update(coords);- });-- $('#wv-image-resolution option')- .removeAttr('selected');- $('#wv-image-resolution option[value=\'' + resolution + '\']')- .attr('selected', 'selected');-- $('#wv-image-format option')- .removeAttr('selected');- $('#wv-image-format option[value=\'' + format + '\']')- .attr('selected', 'selected');-- $('#wv-image-worldfile option')- .removeAttr('selected');- $('#wv-image-worldfile option[value=\'' + worldfile + '\']')- .attr('selected', 'selected');-wvui.positionDialog($dialog, {my: 'right top',at: 'right bottom+5',@@ -236,55 +252,24 @@ export function imagePanel(models, ui, config) {$('.wv-image-coords').show();};+ self.update = function(c) {+ var pixels, map, px, x1, y1, x2, y2, crs;- var setPosition = function () {- var offset = $('#' + alignTo.id)- .offset();- var left = offset.left + parseInt($('#' + alignTo.id)- .css('width')) - parseInt($('#' + id)- .css('width'));- $('#' + id)- .css('left', left + 'px');- };-- var update = function (c) {try {coords = c;- var map = ui.map.selected;- // What's this for?- // var bbox = map.getExtent();- var time = models.date.selected;- var pixels = coords;- var s = models.proj.selected.id;- var products = models.layers.get({- reverse: true,- renderable: true- });- // NOTE: This needs to be changed back to the projection model- // when the backfill removes the old projection.- var epsg = (models.proj.change) ? models.proj.change.epsg- : models.proj.selected.epsg;-- // get layer transparencies (opacities)- var opacities = [];- lodashEach(products, function (product) {- opacities.push((lodashIsUndefined(product.opacity)) ? 1 : product.opacity);- });-- // console.log("EPSG: " + epsg);-- var px = pixels;- var x1 = px.x;- var y1 = px.y;- var x2 = px.x2;- var y2 = px.y2;-- var crs = models.proj.selected.crs;- var lonlat1 = map.getCoordinateFromPixel([Math.floor(x1), Math.floor(y2)]);- var lonlat2 = map.getCoordinateFromPixel([Math.floor(x2), Math.floor(y1)]);-- var geolonlat1 = olProj.transform(lonlat1, crs, 'EPSG:4326');- var geolonlat2 = olProj.transform(lonlat2, crs, 'EPSG:4326');+ map = ui.map.selected;+ pixels = coords;+ px = pixels;+ x1 = px.x;+ y1 = px.y;+ x2 = px.x2;+ y2 = px.y2;+ crs = models.proj.selected.crs;++ lonlats = getCoordsFromPixelValues(x1, x2, y1, y2, map);++ var geolonlat1 = olProj.transform(lonlats[0], crs, 'EPSG:4326');+ var geolonlat2 = olProj.transform(lonlats[1], crs, 'EPSG:4326');var minLon = geolonlat1[0];var maxLon = geolonlat2[0];@@ -294,109 +279,135 @@ export function imagePanel(models, ui, config) {var ll = util.formatCoordinate([minLon, maxLat]);var ur = util.formatCoordinate([maxLon, minLat]);- if (x2 - x1 < 150) {- ll = '';- ur = '';- }-- $('#wv-image-top')- .css({- left: x1 - 10,- top: y1 - 20,- width: x2 - x1- })- .html(ur);- $('#wv-image-bottom')- .css({- left: x1,- top: y2,- width: x2 - x1- })- .html(ll);-- var dlURL = url;- var conversionFactor = 256;- if (s == 'geographic') {- conversionFactor = 0.002197;- }-- var dTime = time;- // Julian date, padded with two zeros (to ensure the julian date is always in DDD format).- var jStart = util.parseDateUTC(dTime.getUTCFullYear() + '-01-01');- var jDate = '00' + (1 + Math.ceil((dTime.getTime() - jStart) / 86400000));- dlURL += 'TIME=' + dTime.getUTCFullYear() + (jDate)- .substr((jDate.length) - 3);-- dlURL += '&extent=' + lonlat1[0] + ',' + lonlat1[1] + ',' + lonlat2[0] + ',' + lonlat2[1];-- // dlURL += "&switch="+s;- dlURL += '&epsg=' + epsg;- var layers = [];- lodashEach(products, function (layer) {- if (layer.projections[s].layer) {- layers.push(layer.projections[s].layer);- } else {- layers.push(layer.id);- }- });- dlURL += '&layers=' + layers.join(',');- dlURL += '&opacities=' + opacities.join(',');-- var imgWidth = 0;- var imgHeight = 0;- var imgRes, imgFileSize, imgFormat, imgWorldfile;-- $('#wv-image-resolution')- .unbind('change')- .change(function () {- imgRes = $('#wv-image-resolution option:checked')- .val();- resolution = imgRes;- imgWidth = Math.round((Math.abs(lonlat2[0] - lonlat1[0]) / conversionFactor) / Number(imgRes));- imgHeight = Math.round((Math.abs(lonlat2[1] - lonlat1[1]) / conversionFactor) / Number(imgRes));- imgFileSize = ((imgWidth * imgHeight * 24) / 8388608)- .toFixed(2);- imgFormat = $('#wv-image-format option:checked')- .val();- imgWorldfile = $('#wv-image-worldfile option:checked')- .val();- var invalid = (imgFileSize > 250 || imgHeight === 0 || imgWidth === 0);- var icon;- if (invalid) {- icon = '<i class=\'fa fa-times fa-fw\'></i>';- $('.wv-image-size')- .addClass('wv-image-size-invalid');- $('#wv-image-download-button')- .button('disable');- } else {- icon = '<i class=\'fa fa-check fa-fw\'></i>';- $('.wv-image-size')- .removeClass('wv-image-size-invalid');- $('#wv-image-download-button')- .button('enable');- }- $('#wv-image-width')- .html((imgWidth));- $('#wv-image-height')- .html((imgHeight));- $('#wv-image-size')- .html(icon + imgFileSize + ' MB');- })- .change();-- $('#wv-image-download-button')- .unbind('click')- .click(function () {- googleAnalytics.event('Image Download', 'Click', 'Download');- util.metrics('lc=' + encodeURIComponent(dlURL + '&worldfile=' + imgWorldfile + '&format=' + imgFormat + '&width=' + imgWidth + '&height=' + imgHeight));- window.open(dlURL + '&worldfile=' + imgWorldfile + '&format=' + imgFormat + '&width=' + imgWidth + '&height=' + imgHeight, '_blank');- });+ setBoundingBoxLabels(x1, x2, y1, y2, ll, ur);+ imgFilesize = calulateFileSize(imgRes, lonlats[0], lonlats[1]);+ updatePanel(getUpdatedProps());} catch (cause) {util.error(cause);}};+ var getEPSG = function() {+ // NOTE: This needs to be changed back to the projection model+ // when the backfill removes the old projection.- init();+ return (models.proj.change) ? models.proj.change.epsg : models.proj.selected.epsg;+ };+ /*+ * Sets labels of bounding box of Jcrop+ * selector+ *+ * @method setBoundingBoxLabels+ *+ * @param {Number} x1 - right x pixel value+ * @param {Number} x2 - left x pixel value+ * @param {Number} y1 - top y pixel value+ * @param {Number} y2 - bottom y pixel value+ *+ * @returns {void}+ */+ var setBoundingBoxLabels = function(x1, x2, y1, y2, ur, ll) {+ if (x2 - x1 < 150) {+ ll = '';+ ur = '';+ }+ $('#wv-image-top')+ .css({+ left: x1 - 10,+ top: y1 - 20,+ width: x2 - x1+ }).html(ur);++ $('#wv-image-bottom')+ .css({+ left: x1,+ top: y2,+ width: x2 - x1+ }).html(ll);+ };+ var getCoordsFromPixelValues = function(x1, x2, y1, y2, map) {+ return [+ map.getCoordinateFromPixel([Math.floor(x1), Math.floor(y2)]),+ map.getCoordinateFromPixel([Math.floor(x2), Math.floor(y1)])+ ];+ };+ var getLayerOpacities = function(products) {+ var opacities = [];+ lodashEach(products, function (product) {+ opacities.push((lodashIsUndefined(product.opacity)) ? 1 : product.opacity);+ });+ return opacities;+ };+ var getConversionFactor = function(proj) {+ if (proj === 'geographic') return 0.002197;+ return 256;+ };+ var calulateFileSize = function(imgRes, lonlat1, lonlat2) {+ var conversionFactor;+ conversionFactor = getConversionFactor(models.proj.selected.id);+ resolution = imgRes;+ imgWidth = Math.round((Math.abs(lonlat2[0] - lonlat1[0]) / conversionFactor) / Number(imgRes));+ imgHeight = Math.round((Math.abs(lonlat2[1] - lonlat1[1]) / conversionFactor) / Number(imgRes));++ return ((imgWidth * imgHeight * 24) / 8388608).toFixed(2);+ };+ var fileSizeValid = function() {+ return (imgFilesize < 250 && imgHeight !== 0 && imgWidth !== 0);+ };+ var onDownload = function() {+ var dlURL, products;++ products = models.layers.get({+ reverse: true,+ renderable: true+ });++ dlURL = createDownloadURL(models.date.selected, lonlats, getEPSG(), products, getLayerOpacities(products), url);+ googleAnalytics.event('Image Download', 'Click', 'Download');+ util.metrics('lc=' + encodeURIComponent(dlURL + '&worldfile=' + imgWorldfile + '&format=' + imgFormat + '&width=' + imgWidth + '&height=' + imgHeight));+ window.open(dlURL + '&worldfile=' + imgWorldfile + '&format=' + imgFormat + '&width=' + imgWidth + '&height=' + imgHeight, '_blank');+ };++ var setPosition = function() {+ var offset = $('#' + alignTo.id)+ .offset();+ var left = offset.left + parseInt($('#' + alignTo.id)+ .css('width')) - parseInt($('#' + id)+ .css('width'));+ $('#' + id)+ .css('left', left + 'px');+ };++ var createDownloadURL = function(time, lonlats, epsg, products, opacities, dlURL) {+ var layers, jStart, jDate;+ var dTime = time;++ layers = getLayers(products, models.proj.selected.id);+ // Julian date, padded with two zeros (to ensure the julian date is always in DDD format).+ jStart = util.parseDateUTC(dTime.getUTCFullYear() + '-01-01');+ jDate = '00' + (1 + Math.ceil((dTime.getTime() - jStart) / 86400000));+ dlURL += 'TIME=' + dTime.getUTCFullYear() + (jDate)+ .substr((jDate.length) - 3);++ dlURL += '&extent=' + lonlats[0][0] + ',' + lonlats[0][1] + ',' + lonlats[1][0] + ',' + lonlats[1][1];+ // dlURL += "&switch="+s;+ dlURL += '&epsg=' + epsg;+ dlURL += '&layers=' + layers.join(',');+ dlURL += '&opacities=' + opacities.join(',');++ return dlURL;+ };+ var getLayers = function(products, s) {+ var layers = [];+ lodashEach(products, function(layer) {+ if (layer.projections[s].layer) {+ layers.push(layer.projections[s].layer);+ } else {+ layers.push(layer.id);+ }+ });+ return layers;+ };+ init();return self;};diff --git a/web/js/image/rubberband.js b/web/js/image/rubberband.jsindex d782821be..63d95e7d0 100644--- a/web/js/image/rubberband.js+++ b/web/js/image/rubberband.js@@ -4,8 +4,28 @@ import 'jquery-jcrop';import lodashFind from 'lodash/find';import util from '../util/util';import wvui from '../ui/ui';+import { imagePanel } from './panel';++const dialogConfig = {+ dialogClass: 'wv-panel wv-image',+ title: 'Take a snapshot',+ show: {+ effect: 'slide',+ direction: 'up'+ },+ hide: {+ effect: 'slide',+ direction: 'up'+ },+ width: 230,+ height: 'auto',+ minHeight: 10,+ draggable: false,+ resizable: false,+ autoOpen: false+};-export function imageRubberband(models, ui, config) {+export function imageRubberband (models, ui, config) {var self = {};var PALETTE_WARNING =@@ -30,6 +50,8 @@ export function imageRubberband(models, ui, config) {var jcropAPI = null;var previousPalettes = null;var $button;++ self.panel = imagePanel(models, ui, config, dialogConfig);self.events = util.events();/**@@ -74,14 +96,12 @@ export function imageRubberband(models, ui, config) {};var toggle = function () {- var checked = $('#wv-image-button-check')- .prop('checked');var geographic = models.proj.selected.id === 'geographic';// Enables UI to select an area on the map while darkening the viewvar toggleOn = function () {state = 'on';toolbarButtons('disable');- self.events.trigger('show');+ self.panel.show();$('.ui-dialog').on('dialogclose', function () {if (state === 'on') {@@ -110,7 +130,7 @@ export function imageRubberband(models, ui, config) {models.layers.setVisibility('Graticule', false);toggle();};- if (state == 'off') {+ if (state === 'off') {var layers = models.layers.get({renderable: true});@@ -180,10 +200,10 @@ export function imageRubberband(models, ui, config) {* @param {String} coordinates object of JCrop**/- var setCoords = function (c) {+ var setCoords = function (c, panel) {previousCoords = coords;coords = c;- self.events.trigger('update', coords);+ self.panel.update(coords);};/**