Interactive interface for browsing global, full-resolution satellite imagery
WV-2228: Dateline granule crossing (#3863)
Jason Kent18bec58cfe6a
diff --git a/package-lock.json b/package-lock.jsonindex 2e5451508..47211f284 100644--- a/package-lock.json+++ b/package-lock.json@@ -6,7 +6,7 @@"packages": {"": {"name": "worldview",- "version": "3.22.0",+ "version": "3.23.0","hasInstallScript": true,"license": "NASA-1.3","dependencies": {@@ -31,6 +31,7 @@"geographiclib": "^1.50.0","history": "^4.7.2","immutability-helper": "^3.0.1",+ "jsdom-worker": "^0.2.1","lodash": "^4.17.21","moment": "^2.29.2","moment-locales-webpack-plugin": "^1.1.2",@@ -14381,6 +14382,18 @@}}},+ "node_modules/jsdom-worker": {+ "version": "0.2.1",+ "resolved": "https://registry.npmjs.org/jsdom-worker/-/jsdom-worker-0.2.1.tgz",+ "integrity": "sha512-LwGtjkIfbDObphy4lUJmmAmo5cM/WS8r1A61apecFeqkjUvOhhinxM8wQFS51ndR+6jXxzAX3bhxMOG3njckaw==",+ "dependencies": {+ "mitt": "^1.1.3",+ "uuid-v4": "^0.1.0"+ },+ "peerDependencies": {+ "node-fetch": "*"+ }+ },"node_modules/jsdom/node_modules/parse5": {"version": "5.1.1","dev": true,@@ -15495,6 +15508,11 @@"node": ">=4.0.0"}},+ "node_modules/mitt": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-1.2.0.tgz",+ "integrity": "sha512-r6lj77KlwqLhIUku9UWYes7KJtsczvolZkzp8hbaDPPaE24OmWl5s539Mytlj22siEQKosZ26qCBgda2PKwoJw=="+ },"node_modules/mixin-deep": {"version": "1.3.2","license": "MIT",@@ -15998,7 +16016,6 @@},"node_modules/node-fetch": {"version": "2.6.7",- "dev": true,"license": "MIT","dependencies": {"whatwg-url": "^5.0.0"@@ -16017,17 +16034,14 @@},"node_modules/node-fetch/node_modules/tr46": {"version": "0.0.3",- "dev": true,"license": "MIT"},"node_modules/node-fetch/node_modules/webidl-conversions": {"version": "3.0.1",- "dev": true,"license": "BSD-2-Clause"},"node_modules/node-fetch/node_modules/whatwg-url": {"version": "5.0.0",- "dev": true,"license": "MIT","dependencies": {"tr46": "~0.0.3",@@ -26250,6 +26264,14 @@"uuid": "bin/uuid"}},+ "node_modules/uuid-v4": {+ "version": "0.1.0",+ "resolved": "https://registry.npmjs.org/uuid-v4/-/uuid-v4-0.1.0.tgz",+ "integrity": "sha1-YtezEEBvbOz+oVKMafHo4LzsWjo=",+ "engines": {+ "node": "*"+ }+ },"node_modules/v8-compile-cache": {"version": "2.1.0","dev": true,@@ -37688,6 +37710,15 @@}}},+ "jsdom-worker": {+ "version": "0.2.1",+ "resolved": "https://registry.npmjs.org/jsdom-worker/-/jsdom-worker-0.2.1.tgz",+ "integrity": "sha512-LwGtjkIfbDObphy4lUJmmAmo5cM/WS8r1A61apecFeqkjUvOhhinxM8wQFS51ndR+6jXxzAX3bhxMOG3njckaw==",+ "requires": {+ "mitt": "^1.1.3",+ "uuid-v4": "^0.1.0"+ }+ },"jsesc": {"version": "2.5.2","dev": true@@ -38420,6 +38451,11 @@"through2": "^2.0.0"}},+ "mitt": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-1.2.0.tgz",+ "integrity": "sha512-r6lj77KlwqLhIUku9UWYes7KJtsczvolZkzp8hbaDPPaE24OmWl5s539Mytlj22siEQKosZ26qCBgda2PKwoJw=="+ },"mixin-deep": {"version": "1.3.2","requires": {@@ -38776,22 +38812,18 @@},"node-fetch": {"version": "2.6.7",- "dev": true,"requires": {"whatwg-url": "^5.0.0"},"dependencies": {"tr46": {- "version": "0.0.3",- "dev": true+ "version": "0.0.3"},"webidl-conversions": {- "version": "3.0.1",- "dev": true+ "version": "3.0.1"},"whatwg-url": {"version": "5.0.0",- "dev": true,"requires": {"tr46": "~0.0.3","webidl-conversions": "^3.0.0"@@ -45608,6 +45640,11 @@"version": "3.3.3","dev": true},+ "uuid-v4": {+ "version": "0.1.0",+ "resolved": "https://registry.npmjs.org/uuid-v4/-/uuid-v4-0.1.0.tgz",+ "integrity": "sha1-YtezEEBvbOz+oVKMafHo4LzsWjo="+ },"v8-compile-cache": {"version": "2.1.0","dev": truediff --git a/package.json b/package.jsonindex 13f97dee3..3bfcfd3d3 100644--- a/package.json+++ b/package.json@@ -184,6 +184,7 @@"geographiclib": "^1.50.0","history": "^4.7.2","immutability-helper": "^3.0.1",+ "jsdom-worker": "^0.2.1","lodash": "^4.17.21","moment": "^2.29.2","moment-locales-webpack-plugin": "^1.1.2",@@ -233,7 +234,8 @@],"jest": {"setupFiles": [- "jest-canvas-mock"+ "jest-canvas-mock",+ "jsdom-worker"],"moduleDirectories": ["node_modules"diff --git a/web/js/components/timeline/date-util.js b/web/js/components/timeline/date-util.jsindex a485bd1c3..127eb92ee 100644--- a/web/js/components/timeline/date-util.js+++ b/web/js/components/timeline/date-util.js@@ -19,7 +19,6 @@ export const getDaysInYear = (date) => {// return string in ISO format "2018-03-16T06:17:30Z"export const getISODateFormatted = (date) => `${new Date(date).toISOString().split('.')[0]}Z`;-// display date as '2000 OCT 28' for default or '2000 OCT 28 20:28Z' for subdailyexport const getDisplayDate = (date, isSubdaily) => {const displayDate = formatDisplayDate(new Date(date), isSubdaily);diff --git a/web/js/containers/map-interactions/ol-vector-interactions.js b/web/js/containers/map-interactions/ol-vector-interactions.jsindex bc7da2cae..b592e1cd5 100644--- a/web/js/containers/map-interactions/ol-vector-interactions.js+++ b/web/js/containers/map-interactions/ol-vector-interactions.js@@ -12,8 +12,8 @@ import { transform } from 'ol/proj';import { isFromActiveCompareRegion } from '../../modules/compare/util';import {hasNonClickableVectorLayer,- areCoordinatesAndPolygonExtentValid,} from '../../modules/layers/util';+import { areCoordinatesAndPolygonExtentValid } from '../../map/granule/util';import {getActiveLayers, getGranulePlatform, getActiveGranuleFootPrints,} from '../../modules/layers/selectors';@@ -25,6 +25,7 @@ import { changeCursor as changeCursorActionCreator } from '../../modules/map/actimport { ACTIVATE_VECTOR_ZOOM_ALERT, ACTIVATE_VECTOR_EXCEEDED_ALERT, DISABLE_VECTOR_EXCEEDED_ALERT } from '../../modules/alerts/constants';import util from '../../util/util';+import { FULL_MAP_EXTENT } from '../../modules/map/constants';const { events } = util;@@ -57,17 +58,18 @@ export class VectorInteractions extends React.Component {** @return {Boolean} to indicate if valid for parent mouseMove function*/- handleGranuleHover = (crs, pixels, coord) => {+ handleGranuleHover = (crs, pixels, mouseCoords) => {const {compareState,granulePlatform,granuleFootprints,- maxExtent,swipeOffset,+ visibleExtent,} = this.props;const { active, activeString } = compareState;-+ const polygon = new OlGeomPolygon([]);let toggledGranuleFootprint;+// reverse granule geometry so most recent granules are on topconst footprints = Object.keys(granuleFootprints)@@ -83,29 +85,17 @@ export class VectorInteractions extends React.Component {}}- const polygon = new OlGeomPolygon([]);- for (let i = 0; i < footprints.length; i += 1) {- const date = Object.keys(footprints[i])[0];- const geom = Object.values(footprints[i])[0];-- const geomVertices = geom.map((xy) => {- const coordNums = [parseFloat(xy[0]), parseFloat(xy[1])];- // transform for non geographic projections- if (crs !== 'EPSG:4326') {- return transform(coordNums, 'EPSG:4326', crs);- }- return coordNums;- });-- // update geom polygon for precise coordinate intersect inclusion check- polygon.setCoordinates([geomVertices]);- // check if coordinates and polygon extent are within and not exceeding max extent- const isValidPolygon = areCoordinatesAndPolygonExtentValid(polygon, [coord[0], coord[1]], maxExtent);+ // check if coordinates and polygon extent are within and not exceeding max extent+ footprints.forEach((footprint) => {+ const [date] = Object.keys(footprint);+ const [points] = Object.values(footprint);+ polygon.setCoordinates([points]);+ const isValidPolygon = areCoordinatesAndPolygonExtentValid(polygon, mouseCoords, visibleExtent);if (isValidPolygon) {toggledGranuleFootprint = true;events.trigger('granule-hovered', granulePlatform, date);}- }+ });if (!toggledGranuleFootprint) {events.trigger('granule-hovered', granulePlatform, null);@@ -250,6 +240,7 @@ function mapStateToProps(state) {const granulePlatform = getGranulePlatform(state);const { maxExtent } = config.projections[proj.id];+ const visibleExtent = proj.selected.crs === 'EPSG:4326' ? FULL_MAP_EXTENT : maxExtent;return {activeLayers,@@ -269,7 +260,7 @@ function mapStateToProps(state) {granulePlatform,swipeOffset,proj,- maxExtent,+ visibleExtent,modalState: modal,};}@@ -331,6 +322,7 @@ VectorInteractions.propTypes = {changeCursor: PropTypes.func.isRequired,getDialogObject: PropTypes.func.isRequired,isShowingClick: PropTypes.bool.isRequired,+ visibleExtent: PropTypes.array,measureIsActive: PropTypes.bool.isRequired,modalState: PropTypes.object.isRequired,onCloseModal: PropTypes.func.isRequired,@@ -349,7 +341,6 @@ VectorInteractions.propTypes = {isCoordinateSearchActive: PropTypes.bool,isMobile: PropTypes.bool,lastSelected: PropTypes.object,- maxExtent: PropTypes.array,proj: PropTypes.object,swipeOffset: PropTypes.number,};diff --git a/web/js/map/granule/granule-layer-builder.js b/web/js/map/granule/granule-layer-builder.jsindex f12da6779..952d89b03 100644--- a/web/js/map/granule/granule-layer-builder.js+++ b/web/js/map/granule/granule-layer-builder.js@@ -1,12 +1,6 @@import OlLayerGroup from 'ol/layer/Group';--import {- throttle as lodashThrottle,- each as lodashEach,-} from 'lodash';-import {- DEFAULT_NUM_GRANULES,-} from '../../modules/layers/constants';+import { throttle as lodashThrottle } from 'lodash';+import { DEFAULT_NUM_GRANULES } from '../../modules/layers/constants';import { updateGranuleLayerState } from '../../modules/layers/actions';import { getGranuleLayer } from '../../modules/layers/selectors';import {@@ -14,6 +8,7 @@ import {stopLoading,LOADING_GRANULES,} from '../../modules/loading/actions';+import { FULL_MAP_EXTENT } from '../../modules/map/constants';import { openBasicContent } from '../../modules/modal/actions';import { getCacheOptions } from '../../modules/layers/util';import { getGranulesUrl as getGranulesUrlSelector } from '../../modules/smart-handoff/selectors';@@ -21,18 +16,21 @@ import {getCMRQueryDates,getCMRQueryDateUpdateOptions,isWithinDateRange,- getGranuleDateData,+ transformGranuleData,+ datelineShiftGranules,+ transformGranulesForProj,} from './util';+import util from '../../util/util';+const { toISOStringSeconds } = util;const dayNightFilter = 'DAY'; // 'DAY', 'NIGHT', 'BOTH'export default function granuleLayerBuilder(cache, store, createLayerWMTS) {+ const CMRDataStore = {};const CMRDateRanges = {active: {},activeB: {},};- const CMRDataStore = {};-const getGranuleUrl = getGranulesUrlSelector(store.getState());const baseGranuleUrl = getGranuleUrl();const CMR_AJAX_OPTIONS = {@@ -42,7 +40,6 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {dataType: 'json',timeout: 30 * 1000,};-const throttleDispathCMRErrorDialog = lodashThrottle(dispathCMRErrorDialog.bind(this),CMR_AJAX_OPTIONS.timeout,@@ -71,13 +68,13 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {* @param {id} layer id*/const addGranuleCMRDateData = (data, id) => {- const { proj: { selected: { id: projection } } } = store.getState();+ const { proj: { selected: { crs } } } = store.getState();if (!CMRDataStore[id]) {CMRDataStore[id] = {};}- lodashEach(Object.values(data), (entry) => {- const date = `${entry.time_start.split('.')[0]}Z`;- CMRDataStore[id][date] = getGranuleDateData(entry, date, projection);+ Object.values(data).forEach((entry) => {+ const date = toISOStringSeconds(entry.time_start);+ CMRDataStore[id][date] = transformGranuleData(entry, date, crs);});};@@ -162,8 +159,8 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {* @returns {Array} reducedGranuleDates*/const getGranules = (layerId, selectedDate, startQueryDate) => {- const selected = `${new Date(selectedDate).toISOString().split('.')[0]}Z`;- const queryStart = `${new Date(startQueryDate).toISOString().split('.')[0]}Z`;+ const selected = toISOStringSeconds(selectedDate);+ const queryStart = toISOStringSeconds(startQueryDate);const granuleDates = CMRDataStore[layerId];const granuleDateKeys = granuleDates ? Object.keys(granuleDates) : [];let hitSelectedDate;@@ -186,20 +183,25 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {* @param {object} attributes - Layer specs* @returns {array} collection of OpenLayers TileLayers*/- const createGranuleTileLayers = async (granuleDates, def, attributes) => {+ const createGranuleTileLayers = async (granules, def, attributes) => {const { period, id } = def;const { group, proj } = attributes;- const layerPromises = granuleDates.map(async (granuleDate) => {- const { date, polygons } = granuleDate;- const granuleISOKey = `${id}:${proj}:${date}::${group}`;+ const layerPromises = granules.map(async (granule) => {+ const { date, polygon, shifted } = granule;+ const granuleISOKey = `${id}:${proj}:${date}::${group}:${shifted ? 'shifted' : ''}`;let tileLayer = cache.getItem(granuleISOKey);if (tileLayer) {return tileLayer;}const granuleISODate = new Date(date);- const dateOption = { date: granuleISODate, polygons };- tileLayer = await createLayerWMTS(def, dateOption, null, store.getState(), { polygons });+ const options = {+ date: granuleISODate,+ polygon,+ shifted,+ };+ tileLayer = await createLayerWMTS(def, options, null, store.getState());+attributes.key = granuleISOKey;attributes.date = granuleISODate;tileLayer.wv = attributes;@@ -220,16 +222,26 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {* @returns {object} - Granule layer*/const createGranuleLayer = async (def, attributes, options) => {+ const { proj: { selected: { crs, maxExtent } } } = store.getState();const { id } = def;- const { group } = attributes;+ const { date, group } = attributes;const granuleAttributes = await getGranuleAttributes(def, options);const { filteredGranules } = granuleAttributes;- const tileLayers = await createGranuleTileLayers(filteredGranules, def, attributes);- const layer = new OlLayerGroup({ layers: tileLayers });+ const granules = datelineShiftGranules(filteredGranules, date, crs);+ const tileLayers = await createGranuleTileLayers(granules, def, attributes);+ const layer = new OlLayerGroup({+ layers: tileLayers,+ extent: crs === 'EPSG:4326' ? FULL_MAP_EXTENT : maxExtent,+ });+layer.set('granuleGroup', true);layer.set('layerId', `${id}-${group}`);- layer.wv = { ...attributes, ...granuleAttributes };+ layer.wv = {+ ...attributes,+ ...granuleAttributes,+ filteredGranules: granules,+ };store.dispatch(updateGranuleLayerState(layer));return layer;@@ -249,6 +261,7 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {*/const getGranuleAttributes = async (def, options) => {const state = store.getState();+ const { proj: { selected: { crs } } } = state;let reorderedGranules = false;let count = DEFAULT_NUM_GRANULES;@@ -268,8 +281,12 @@ export default function granuleLayerBuilder(cache, store, createLayerWMTS) {}// get granule dates waiting for CMR query and filtering (if necessary)- const availableGranuleDates = await getQueriedGranuleDates(def, options.date, options.group);- const filteredGranules = filterGranules(def.dateRanges, availableGranuleDates, count);+ const availableGranules = await getQueriedGranuleDates(def, options.date, options.group);+ const filteredGranules = transformGranulesForProj(+ filterGranules(def.dateRanges, availableGranules, count),+ crs,+ );+return {count,granuleDates: filteredGranules.map(({ date }) => date),diff --git a/web/js/map/granule/ui.js b/web/js/map/granule/ui.jsdeleted file mode 100644index 4b6340499..000000000--- a/web/js/map/granule/ui.js+++ /dev/null@@ -1,110 +0,0 @@-import * as olProj from 'ol/proj';-import OlFeature from 'ol/Feature';-import {- Polygon as OlGeomPolygon,-} from 'ol/geom';-import { Vector as OlVectorLayer } from 'ol/layer';-import { Vector as OlVectorSource } from 'ol/source';-import {- Fill as OlStyleFill,- Stroke as OlStyleStroke,- Style as OlStyle,- Text as OlText,-} from 'ol/style';--export default function granuleFootprint(map) {- const self = {};- self.currentGranule = {};- self.vectorLayer = {};-- const vectorSource = new OlVectorSource({- wrapX: false,- useSpatialIndex: false,- });- self.getVectorLayer = (text) => new OlVectorLayer({- className: 'granule-map-footprint',- source: vectorSource,- style: [- new OlStyle({- fill: new OlStyleFill({ color: 'rgb(0, 123, 255, 0.25)' }),- stroke: new OlStyleStroke({- color: 'rgb(0, 123, 255, 0.65)',- width: 3,- }),- text: new OlText({- textAlign: 'center',- text,- font: '18px monospace',- fill: new OlStyleFill({ color: 'white' }),- stroke: new OlStyleStroke({ color: 'black', width: 2 }),- overflow: true,- }),- }),- ],- });-- /*- * Draw granule footprint- *- * @method drawFootprint- * @static- *- * @param {array} granuleGeometry - array of granule points- * example: [- * ['73.512657', '67.650986'],- * ['-113.950806', '84.85434'],- * ['-35.026161', '68.983681'],- * ['27.586159', '59.548096'],- * ['73.512657', '67.650986']- * ]- * @param {string} date - granule date- * @param {string} projCodeCRS - string of projection CRS code- *- * @returns {void}- */- self.drawFootprint = (granuleGeometry, date, projCodeCRS) => {- if (self.currentGranule[date]) {- return;- }- const clearGranule = () => {- self.currentGranule = {};- map.removeLayer(self.vectorLayer);- vectorSource.clear();- };- if (!self.currentGranule[date]) {- clearGranule();- }- if (!granuleGeometry || !date) {- clearGranule();- return;- }-- self.currentGranule[date] = true;-- const res = [].concat(...granuleGeometry);- const points = [];- // iterate the new array and push a coordinate pair into a new array- for (let i = 0; i < res[0].length; i += 2) {- const coord1 = parseFloat(res[i]);- const coord2 = parseFloat(res[i + 1]);- if (coord1 && coord2) {- points.push(olProj.transform([coord1, coord2], 'EPSG:4326', projCodeCRS));- }- }-- // create polygon footprint- const featureFootprint = new OlFeature({- geometry: new OlGeomPolygon([points]),- });-- // add the feature vector to the layer vector- vectorSource.addFeature(featureFootprint);- // add text to vector layer and set current vector layer- const newVectorLayer = self.getVectorLayer(date);- self.vectorLayer = newVectorLayer;- // add layer to map- map.addLayer(self.vectorLayer);- };-- return self;-}diff --git a/web/js/map/granule/util.js b/web/js/map/granule/util.jsindex 389696b1f..c1990cee5 100644--- a/web/js/map/granule/util.js+++ b/web/js/map/granule/util.js@@ -1,6 +1,58 @@+import OlFeature from 'ol/Feature';+import { Vector as OlVectorLayer } from 'ol/layer';+import { Vector as OlVectorSource } from 'ol/source';+import {+ Fill as OlStyleFill,+ Stroke as OlStyleStroke,+ Style as OlStyle,+ Text as OlText,+} from 'ol/style';import OlGeomLineString from 'ol/geom/LineString';+import { transform } from 'ol/proj';+import { Polygon as OlGeomPolygon } from 'ol/geom';+import * as OlExtent from 'ol/extent';import util from '../../util/util';+/**+ * Shift granules to hande dateline cross. Granules are shifted if:+ * - granule date is same as app date and lat < 0+ * - granule is from previous day+ *+ * @param {*} granules+ * @param {*} currentDate+ * @returns+ */+export const datelineShiftGranules = (granules, currentDate, crs) => {+ const currentDayDate = new Date(currentDate).getUTCDate();+ const datelineShiftNeeded = () => {+ if (crs !== 'EPSG:4326') return false;+ const sameDays = granules.every(({ date }) => new Date(date).getUTCDate() === currentDayDate);+ const someCross = granules.some(({ polygon }) => polygon.some(([lon]) => lon > 180 || lon < -180));+ return someCross && !sameDays;+ };++ return !datelineShiftNeeded() ? granules : granules.map((granule) => {+ const { date, polygon } = granule;+ const sameDay = currentDayDate === new Date(date).getUTCDate();+ const westSide = polygon.some(([lon]) => lon < 0);+ const shifted = !sameDay || (sameDay && westSide);+ return {+ date,+ polygon: shifted ? polygon.map(([lon, lat]) => [lon + 360, lat]) : polygon,+ shifted,+ };+ });+};++/**+ * Determine map extent for a single granule tile+ */+export const getGranuleTileLayerExtent = (polygon, extent) => {+ const polygonFootprint = new OlGeomPolygon([polygon]);+ const polygonExtent = polygonFootprint.getExtent();+ return Number.isFinite(polygonExtent[0]) ? polygonExtent : extent;+};+/*** Helper to find index for date string to add to sorted array of date strings*@@ -37,6 +89,11 @@ export const isWithinDateRange = (date, startDate, endDate) => (startDate && end? date.getTime() <= new Date(endDate).getTime() && date.getTime() >= new Date(startDate).getTime(): false);+/**+ *+ * @param {*} layer+ * @returns+ */export const getGranuleFootprints = (layer) => {const {def, filteredGranules, granuleDates,@@ -47,16 +104,15 @@ export const getGranuleFootprints = (layer) => {const isMostRecentDateOutOfRange = new Date(mostRecentGranuleDate) > new Date(endDate);// create geometry object with date:polygons key/value pair filtering out granules outside date range- return filteredGranules.reduce((dates, { date, polygons }) => {+ return filteredGranules.reduce((dates, { date, polygon }) => {const granuleDate = new Date(date);-if (!isMostRecentDateOutOfRange && isWithinDateRange(granuleDate, startDate, endDate)) {// Only include granules that have imagery in this proj (determined by layer dateRanges)const hasImagery = dateRanges.some(({ startDate: start, endDate: end }) => isWithinDateRange(granuleDate, start, end),);if (hasImagery) {- dates[date] = polygons;+ dates[date] = polygon;}}return dates;@@ -195,62 +251,137 @@ export const getCMRQueryDateUpdateOptions = (CMRDateStoreForLayer, date, startQu};};--export const getGranuleDateData = (entry, date, projection) => {+/**+ * Transform granule data from CMR response+ *+ * @param {*} entry+ * @param {*} date+ * @param {*} projection+ * @returns+ */+export const transformGranuleData = (entry, date, crs) => {const line = new OlGeomLineString([]);- const maxDistance = projection === 'geographic' ? 270 : Number.POSITIVE_INFINITY;- const polygons = entry.polygons[0][0].split(' ');+ const maxDistance = crs === 'EPSG:4326' ? 270 : Number.POSITIVE_INFINITY;+ const points = entry.polygons[0][0].split(' ');const dayNight = entry.day_night_flag;+ const polygonCoords = [];- // build the array of arrays polygon- let polygonReorder = [];- for (let i = 0; i < polygons.length; i += 2) {- const coordPair = [];- coordPair.unshift(polygons[i]);- coordPair.unshift(polygons[i + 1]);- polygonReorder.push(coordPair);+ for (let i = 0; i < points.length; i += 2) {+ const lat = Number(points[i]);+ const lon = Number(points[i + 1]);+ polygonCoords.push([lon, lat]);}- // add coordinates that exceeed max distance to table for revision- const coordOverMaxDistance = {};- const firstCoords = polygonReorder[0];- for (let j = 0; j < polygonReorder.length; j += 1) {- // get current long coord in pair and measure against first coord to get length- const currentCoords = polygonReorder[j];- line.setCoordinates([firstCoords, currentCoords]);- const lineLength = line.getLength();-- // if length is over max distance (geographic restriction only) add to table- if (lineLength > maxDistance) {- const longCoord = currentCoords[0];- if (coordOverMaxDistance[longCoord]) {- coordOverMaxDistance[longCoord] += 1;- } else {- coordOverMaxDistance[longCoord] = 1;- }+ const firstCoords = polygonCoords[0];+ const polygon = polygonCoords.map(([lon, lat]) => {+ let newLon = lon;+ line.setCoordinates([firstCoords, [lon, lat]]);+ // Modify coords if length exceeded+ if (line.getLength() > maxDistance) {+ newLon = lon > 0 ? lon - 360 : lon + 360;}- }-- // check if long coord exceeded max and revise coord +/- 360 to handle meridian crossing- const coordinatesRevised = Object.keys(coordOverMaxDistance).length >= 1;- if (coordinatesRevised) {- polygonReorder = polygonReorder.map((coord) => {- const ind0 = coord[0];- if (coordOverMaxDistance[ind0] && coordOverMaxDistance[ind0] >= 1) {- const numInd0 = Number(ind0);- const revise = numInd0 > 0- ? numInd0 - 360- : numInd0 + 360;- coord[0] = revise.toString();- }- return coord;- });- }+ return [newLon, lat];+ });return {date,- polygons: polygonReorder,+ polygon,dayNight,};};+export const transformGranulesForProj = (granules, crs) => granules.map((granule) => {+ const transformedPolygon = granule.polygon.map((coords) => transform(coords, 'EPSG:4326', crs));+ return {+ ...granule,+ polygon: transformedPolygon,+ };+});++/**+ * Check if coordinates and polygon extent are within and not exceeding max extent+ *+ * @param {Object} polygon+ * @param {Array} coords+ * @param {Array} maxExtent+ *+ * @return {Boolean}+ */+export const areCoordinatesAndPolygonExtentValid = (polygon, coords, maxExtent) => {+ const areCoordsWithinPolygon = polygon.intersectsCoordinate(coords);+ // check is polygon footprint is within max extent, will allow partial corners within max extent+ const doesPolygonIntersectMaxExtent = polygon.intersectsExtent(maxExtent);+ // check if polygon is larger than maxExtent - helpful to catch most large polar granules+ const polygonExtent = polygon.getExtent();+ const isPolygonLargerThanMaxExtent = OlExtent.containsExtent(polygonExtent, maxExtent);++ return areCoordsWithinPolygon+ && doesPolygonIntersectMaxExtent+ && !isPolygonLargerThanMaxExtent;+};++/**+ * Exposes methods to create vector layer for a granule polygon and add to the map+ *+ * @param {*} map+ * @returns+ */+export const granuleFootprint = (map) => {+ let currentGranule = {};+ let vectorLayer = {};+ const vectorSource = new OlVectorSource({+ wrapX: false,+ useSpatialIndex: false,+ });++ const getVectorLayer = (text) => new OlVectorLayer({+ className: 'granule-map-footprint',+ source: vectorSource,+ style: [+ new OlStyle({+ fill: new OlStyleFill({ color: 'rgb(0, 123, 255, 0.25)' }),+ stroke: new OlStyleStroke({+ color: 'rgb(0, 123, 255, 0.65)',+ width: 3,+ }),+ text: new OlText({+ textAlign: 'center',+ text,+ font: '18px monospace',+ fill: new OlStyleFill({ color: 'white' }),+ stroke: new OlStyleStroke({ color: 'black', width: 2 }),+ overflow: true,+ }),+ }),+ ],+ });++ const drawFootprint = (granuleGeometry, date) => {+ if (currentGranule[date]) {+ return;+ }+ const clearGranule = () => {+ currentGranule = {};+ map.removeLayer(vectorLayer);+ vectorSource.clear();+ };+ if (!currentGranule[date]) {+ clearGranule();+ }+ if (!granuleGeometry || !date) {+ clearGranule();+ return;+ }+ currentGranule[date] = true;+ const geometry = new OlGeomPolygon([granuleGeometry]);+ const featureFootprint = new OlFeature({ geometry });+ vectorSource.addFeature(featureFootprint);+ const newVectorLayer = getVectorLayer(date);+ vectorLayer = newVectorLayer;+ map.addLayer(vectorLayer);+ };++ return {+ drawFootprint,+ };+};diff --git a/web/js/map/layerbuilder.js b/web/js/map/layerbuilder.jsindex eaa65f052..e22149137 100644--- a/web/js/map/layerbuilder.js+++ b/web/js/map/layerbuilder.js@@ -10,8 +10,7 @@ import OlStroke from 'ol/style/Stroke';import OlText from 'ol/style/Text';import OlFill from 'ol/style/Fill';import OlGraticule from 'ol/layer/Graticule';-import * as olProj from 'ol/proj';-import { Polygon as OlGeomPolygon } from 'ol/geom';+import MVT from 'ol/format/MVT';import LayerVectorTile from 'ol/layer/VectorTile';import SourceVectorTile from 'ol/source/VectorTile';@@ -22,6 +21,7 @@ import lodashGet from 'lodash/get';import util from '../util/util';import lookupFactory from '../ol/lookupimagetile';import granuleLayerBuilder from './granule/granule-layer-builder';+import { getGranuleTileLayerExtent } from './granule/util';import { createVectorUrl, getGeographicResolutionWMS, mergeBreakpointLayerAttributes } from './util';import { datesInDateRanges, prevDateInDateRange } from '../modules/layers/util';import { getSelectedDate } from '../modules/date/selectors';@@ -40,6 +40,10 @@ import {} from '../modules/layers/util';import { startLoading, stopLoading, LOADING_TILES } from '../modules/loading/actions';+import {+ LEFT_WING_EXTENT, RIGHT_WING_EXTENT, LEFT_WING_ORIGIN, RIGHT_WING_ORIGIN, CENTER_MAP_ORIGIN,+} from '../modules/map/constants';+let loadingCounter = 0;export default function mapLayerBuilder(config, cache, store) {@@ -352,17 +356,17 @@ export default function mapLayerBuilder(config, cache, store) {* @param {*} proj - current projection*/const calcExtentsFromLimits = (matrixSet, matrixSetLimits, day, proj) => {- let extent; let- origin;+ let extent;+ let origin;switch (day) {case 1:- extent = [-250, -90, -180, 90];- origin = [-540, 90];+ extent = LEFT_WING_EXTENT;+ origin = LEFT_WING_ORIGIN;break;case -1:- extent = [180, -90, 250, 90];- origin = [180, 90];+ extent = RIGHT_WING_EXTENT;+ origin = RIGHT_WING_ORIGIN;break;default:extent = proj.maxExtent;@@ -409,16 +413,17 @@ export default function mapLayerBuilder(config, cache, store) {* @param {object} options - Layer options* @param {number/null} day* @param {object} state- * @param {object} attributes - contain layer options (granule polygons array)* @returns {object} OpenLayers WMTS layer*/- function createLayerWMTS (def, options, day, state, attributes) {+ function createLayerWMTS (def, options, day, state) {const { proj } = state;const {id, layer, format, matrixIds, matrixSet, matrixSetLimits, period, source, style, wrapadjacentdays,} = def;const configSource = config.sources[source];+ const { date, polygon, shifted } = options;const isSubdaily = period === 'subdaily';+if (!source) {throw new Error(`${id}: Invalid source: ${source}`);}@@ -426,7 +431,8 @@ export default function mapLayerBuilder(config, cache, store) {if (!configMatrixSet) {throw new Error(`${id}: Undefined matrix set: ${matrixSet}`);}- let layerDate = options.date || getSelectedDate(state);++ let layerDate = date || getSelectedDate(state);if (isSubdaily && !layerDate) {layerDate = getRequestDates(def, options).closestDate;layerDate = new Date(layerDate.getTime());@@ -434,31 +440,15 @@ export default function mapLayerBuilder(config, cache, store) {if (day && wrapadjacentdays && !isSubdaily) {layerDate = util.dateAdd(layerDate, 'day', day);}+const { tileMatrices, resolutions, tileSize } = configMatrixSet;const { origin, extent } = calcExtentsFromLimits(configMatrixSet, matrixSetLimits, day, proj.selected);const sizes = !tileMatrices ? [] : tileMatrices.map(({ matrixWidth, matrixHeight }) => [matrixWidth, -matrixHeight]);- // Conditionally set extent for granule tile here with polygon array- let tileLayerExtent = extent;- if (attributes.polygons) {- const res = [].concat(...attributes.polygons);- const points = [];- // iterate the new array and push a coordinate pair into a new array- for (let i = 0; i < res[0].length; i += 2) {- const coord1 = parseFloat(res[i]);- const coord2 = parseFloat(res[i + 1]);- if (coord1 && coord2) {- points.push(olProj.transform([coord1, coord2], 'EPSG:4326', proj.selected.crs));- }- }- const polygonFootprint = new OlGeomPolygon([points]);- const polygonExtent = polygonFootprint.getExtent();- tileLayerExtent = Number.isFinite(polygonExtent[0]) ? polygonExtent : extent;- }-+ // Also need to shift this if granule is shiftedconst tileGridOptions = {- origin,- extent,+ origin: shifted ? RIGHT_WING_ORIGIN : origin,+ extent: shifted ? RIGHT_WING_EXTENT : extent,sizes,resolutions,matrixIds: matrixIds || resolutions.map((set, index) => index),@@ -486,8 +476,11 @@ export default function mapLayerBuilder(config, cache, store) {const tileSource = new OlSourceWMTS(sourceOptions);tileSource.on('tileloadstart', tileLoadStart);tileSource.on('tileloadend', tileLoadEnd);++ const granuleExtent = polygon && getGranuleTileLayerExtent(polygon, extent);+return new OlLayerTile({- extent: tileLayerExtent,+ extent: polygon ? granuleExtent : extent,preload: 0,className: def.id,source: tileSource,@@ -534,13 +527,13 @@ export default function mapLayerBuilder(config, cache, store) {if (day) {if (day === 1) {- layerExtent = [-250, -90, -180, 90];- start = [-180, 90];+ layerExtent = LEFT_WING_EXTENT;+ start = CENTER_MAP_ORIGIN;gridExtent = [110, -90, 180, 90];} else {gridExtent = [-180, -90, -110, 90];- layerExtent = [180, -90, 250, 90];- start = [-180, 90];+ layerExtent = RIGHT_WING_EXTENT;+ start = CENTER_MAP_ORIGIN;}}@@ -640,11 +633,11 @@ export default function mapLayerBuilder(config, cache, store) {}if (day) {if (day === 1) {- extent = [-250, -90, -180, 90];- start = [-540, 90];+ extent = LEFT_WING_EXTENT;+ start = LEFT_WING_ORIGIN;} else {- extent = [180, -90, 250, 90];- start = [180, 90];+ extent = RIGHT_WING_EXTENT;+ start = RIGHT_WING_ORIGIN;}}const parameters = {diff --git a/web/js/map/map.js b/web/js/map/map.jsindex 855440d76..8f0188bad 100644--- a/web/js/map/map.js+++ b/web/js/map/map.js@@ -185,7 +185,7 @@ export function mapIsPolygonValid(polygon, maxDistance) {* @static** @param polygon {object} GeoJSON poylgon geometry Object- *+* @param adjustSign {number} a value of 1 or -1** @return {obj} Adjusted GeoJSON poylgon geometry Objectdiff --git a/web/js/map/ui.js b/web/js/map/ui.jsindex ee7293bab..2420b103f 100644--- a/web/js/map/ui.js+++ b/web/js/map/ui.js@@ -33,7 +33,7 @@ import mapLayerBuilder from './layerbuilder';import MapRunningData from './runningdata';import { getActiveLayerGroup, fly, saveRotation } from './util';import mapCompare from './compare/compare';-import granuleFootprint from './granule/ui';+import { granuleFootprint } from './granule/util';import { LOCATION_POP_ACTION } from '../redux-location-state-customs';import { CHANGE_PROJECTION } from '../modules/projection/constants';import { CHANGE_TAB } from '../modules/sidebar/constants';@@ -253,11 +253,12 @@ export default function mapui(models, config, store) {const onGranuleHover = (instrument, date) => {const state = store.getState();+ const proj = self.selected.getView().getProjection().getCode();let geometry;if (instrument && date) {geometry = getActiveGranuleFootPrints(state)[date];}- return granuleFootprintDraw(geometry, date);+ return granuleFootprints[proj].drawFootprint(geometry, date);};/**@@ -1086,19 +1087,6 @@ export default function mapui(models, config, store) {}};- /*- * Add granule footprint to map- *- * @method granuleFootprintDraw- * @static- *- * @returns {void}- */- const granuleFootprintDraw = (granuleGeometry, date) => {- const proj = self.selected.getView().getProjection().getCode();- granuleFootprints[proj].drawFootprint(granuleGeometry, date, proj);- };-/** Create map object*diff --git a/web/js/modules/layers/actions.js b/web/js/modules/layers/actions.jsindex 8af296fa0..0e1eb9415 100644--- a/web/js/modules/layers/actions.js+++ b/web/js/modules/layers/actions.js@@ -328,7 +328,6 @@ export function updateGranuleLayerState(layer) {if (existingLayer) {dispatch(updateGranuleLayerGeometry(layer, updatedDates, granuleFootprints));}- console.debug(granuleFootprints);dispatch(addGranuleLayerDates(layer, granuleFootprints, `${subtitle}`));};}diff --git a/web/js/modules/layers/util.js b/web/js/modules/layers/util.jsindex 44e341352..245c1f0f4 100644--- a/web/js/modules/layers/util.js+++ b/web/js/modules/layers/util.js@@ -8,7 +8,7 @@ import {isEqual as lodashIsEqual,} from 'lodash';import moment from 'moment';-import * as OlExtent from 'ol/extent';+import googleTagManager from 'googleTagManager';import update from 'immutability-helper';import {@@ -1397,29 +1397,6 @@ export function adjustStartDates(layers) {return Object.values(layers).forEach(applyDateAdjustment);}-/**- * Check if coordinates and polygon extent are within and not exceeding max extent- *- * @param {Object} polygon- * @param {Array} coords- * @param {Array} maxExtent- *- * @return {Boolean}- */-export const areCoordinatesAndPolygonExtentValid = (polygon, coords, maxExtent) => {- // check if cursor coordinates within granule footprint- const areCoordsWithinPolygon = polygon.intersectsCoordinate(coords);- // check is polygon footprint is within max extent, will allow partial corners within max extent- const doesPolygonIntersectMaxExtent = polygon.intersectsExtent(maxExtent);- // check if polygon is larger than maxExtent - helpful to catch most large polar granules- const polygonExtent = polygon.getExtent();- const isPolygonLargerThanMaxExtent = OlExtent.containsExtent(polygonExtent, maxExtent);-- return areCoordsWithinPolygon- && doesPolygonIntersectMaxExtent- && !isPolygonLargerThanMaxExtent;-};-/*** For subdaily layers, if the layer date is within 30 minutes of current* time, set expiration to ten minutes from nowdiff --git a/web/js/modules/map/constants.js b/web/js/modules/map/constants.jsindex ea1b169ae..c687f1043 100644--- a/web/js/modules/map/constants.js+++ b/web/js/modules/map/constants.js@@ -7,6 +7,15 @@ export const FITTED_TO_LEADING_EXTENT = 'MAP/FITTED_TO_LEADING_EXTENT';export const CHANGE_CURSOR = 'MAP/CHANGE_CURSOR';export const REFRESH_ROTATE = 'MAP/REFRESH_ROTATE';+export const LEFT_WING_EXTENT = [-250, -90, -180, 90];+export const CENTER_MAP_EXTENT = [180, -90, -180, 90];+export const RIGHT_WING_EXTENT = [180, -90, 250, 90];+export const FULL_MAP_EXTENT = [-250, -90, 250, 90];++export const LEFT_WING_ORIGIN = [-540, 90];+export const RIGHT_WING_ORIGIN = [180, 90];+export const CENTER_MAP_ORIGIN = [-180, 90];+export const RESOLUTION_FOR_LARGE_WMS_TILES = [0.3515625,0.17578125,diff --git a/web/js/util/util.js b/web/js/util/util.jsindex 374bfed5c..8274da68e 100644--- a/web/js/util/util.js+++ b/web/js/util/util.js@@ -228,7 +228,9 @@ export default (function(self) {* @return {string} ISO string in the form of `YYYY-MM-DDThh:mm:ssZ`.*/self.toISOStringSeconds = function(date) {- return `${date.toISOString().split('.')[0]}Z`;+ const isString = typeof date === 'string' || date instanceof String;+ const dateString = isString ? date : date.toISOString();+ return `${dateString.split('.')[0]}Z`;};/**