Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

clean up map fly animation code

Jason Kentaba0700c84c4
diff --git a/web/js/combine-ui.js b/web/js/combine-ui.js
index 572fedeee..43f921aa7 100644
--- a/web/js/combine-ui.js
+++ b/web/js/combine-ui.js
@@ -1,6 +1,5 @@
import util from './util/util';
import mapui from './map/ui';
-import mapAnimate from './map/animate';
const { events } = util;
@@ -19,7 +18,6 @@ export default function combineUi(models, config, store) {
};
store.subscribe(subscribeToStore);
ui.map = mapui(models, config, store, ui);
- ui.map.animate = mapAnimate(config, ui, store);
ui.supportsPassive = false;
try {
const opts = Object.defineProperty({}, 'passive', {
diff --git a/web/js/map/animate.js b/web/js/map/animate.js
deleted file mode 100644
index 350905f0d..000000000
--- a/web/js/map/animate.js
+++ /dev/null
@@ -1,94 +0,0 @@
-import * as olExtent from 'ol/extent';
-import OlGeomLineString from 'ol/geom/LineString';
-import Promise from 'bluebird';
-
-export default function mapAnimate(config, ui, store) {
- const self = {};
-
- /**
- * Moves the map with a "flying" animation
- *
- * @param {Array} endPoint Ending coordinates
- * @param {integer} endZoom Ending Zoom Level
- * @return {Promise} Promise that is fulfilled when animation completes
- */
- self.fly = function(endPoint, endZoom, rotation) {
- const state = store.getState();
- const view = ui.map.selected.getView();
- const polarProjectionCheck = state.proj.selected.id !== 'geographic'; // boolean if current projection is polar
- view.cancelAnimations();
- const startPoint = view.getCenter();
- const startZoom = Math.floor(view.getZoom());
- endZoom = endZoom || 5;
- if (endPoint.length > 2) endPoint = olExtent.getCenter(endPoint);
- const extent = view.calculateExtent();
- const hasEndInView = olExtent.containsCoordinate(extent, endPoint);
- const line = new OlGeomLineString([startPoint, endPoint]);
- const distance = line.getLength(); // In map units, which is usually degrees
- const distanceDuration = polarProjectionCheck ? distance / 50000 : distance; // limit large polar projection distances from coordinate transforms
- let duration = Math.floor(distanceDuration * 20 + 1000); // approx 6 seconds to go 360 degrees
- if (!rotation) rotation = 0;
- const animationPromise = function(...args) {
- return new Promise((resolve, reject) => {
- args.push((complete) => {
- if (complete) resolve();
- if (!complete) reject(new Error('Animation interrupted!'));
- });
- view.animate(...args);
- }).catch(() => {});
- };
- if (hasEndInView) {
- // allow faster fly with nearby events
- duration = duration < 1200 ? duration / 2 : duration;
- // If the event is already visible, don't zoom out
- return Promise.all([
- animationPromise({
- center: endPoint,
- duration,
- rotation,
- }),
- animationPromise({
- zoom: endZoom,
- duration,
- rotation,
- }),
- ]);
- }
- // Default animation zooms out to arc
- return Promise.all([
- animationPromise({
- center: endPoint,
- duration,
- rotation,
- }),
- animationPromise(
- {
- zoom: getBestZoom(distance, startZoom, endZoom, view),
- duration: duration / 2,
- rotation,
- },
- { zoom: endZoom, duration: duration / 2, rotation },
- ),
- ]);
- };
-
- /**
- * Gets the best zoom level for the middle of the flight animation
- *
- * @param {integer} distance distance of the animation in map units
- * @param {integer} start starting zoom level
- * @param {integer} end ending zoom level
- * @param {object} view map view
- * @return {integer} best zoom level for flight animation
- */
- const getBestZoom = function(distance, start, end, view) {
- const idealLength = 1500;
- const lines = [2, 3, 4, 5, 6, 7, 8].map((zoom) => ({
- zoom,
- pixels: distance / view.getResolutionForZoom(zoom),
- }));
- const bestFit = lines.sort((a, b) => Math.abs(idealLength - a.pixels) - Math.abs(idealLength - b.pixels))[0];
- return Math.max(2, Math.min(bestFit.zoom, start - 1, end - 1));
- };
- return self;
-}
diff --git a/web/js/map/natural-events/natural-events.js b/web/js/map/natural-events/natural-events.js
index 4dabf7e03..99e0a2357 100644
--- a/web/js/map/natural-events/natural-events.js
+++ b/web/js/map/natural-events/natural-events.js
@@ -18,6 +18,9 @@ import { getFilteredEvents } from '../../modules/natural-events/selectors';
import EventTrack from './event-track';
import EventMarkers from './event-markers';
+import { fly } from '../util';
+
+const { events } = util;
const zoomLevelReference = {
Wildfires: 8,
@@ -31,7 +34,6 @@ class NaturalEvents extends React.Component {
this.state = {
prevSelectedEvent: {},
};
-
this.selectEvent = this.selectEvent.bind(this);
}
@@ -87,7 +89,7 @@ class NaturalEvents extends React.Component {
selectEvent(id, date, isInitialLoad) {
const { prevSelectedEvent } = this.state;
const {
- mapUi, selectDate, selectEventFinished, eventsData, activateLayersForEventCategory,
+ selectDate, selectEventFinished, eventsData, activateLayersForEventCategory,
} = this.props;
const isIdChange = !prevSelectedEvent || prevSelectedEvent.id !== id;
@@ -125,9 +127,7 @@ class NaturalEvents extends React.Component {
}
// hack to update layers
if (isIdChange) {
- mapUi.reloadLayers();
- } else {
- mapUi.updateDate();
+ events.trigger('map:reload-layers');
}
selectEventFinished();
@@ -135,7 +135,7 @@ class NaturalEvents extends React.Component {
}
zoomToEvent = function(event, date, isSameEventID) {
- const { proj, map, mapUi } = this.props;
+ const { proj, map } = this.props;
const { crs } = proj.selected;
const category = event.categories[0].title;
const zoom = isSameEventID ? map.getView().getZoom() : zoomLevelReference[category];
@@ -151,7 +151,7 @@ class NaturalEvents extends React.Component {
} else {
coordinates = olProj.transform(geometry.coordinates, 'EPSG:4326', crs);
}
- return mapUi.animate.fly(coordinates, zoom, null);
+ return fly(map, proj, coordinates, zoom, null);
};
render() {
@@ -166,17 +166,17 @@ class NaturalEvents extends React.Component {
const mapStateToProps = (state) => {
const {
- events, map, proj, requestedEvents,
+ map, proj, requestedEvents,
} = state;
+ const { active, selected } = state.events;
const selectedMap = map.ui.selected;
return {
- eventsActive: events.active,
+ eventsActive: active,
map: selectedMap,
- mapUi: map.ui,
proj,
eventsDataIsLoading: requestedEvents.isLoading,
eventsData: getFilteredEvents(state),
- selectedEvent: events.selected,
+ selectedEvent: selected,
};
};
@@ -200,7 +200,6 @@ NaturalEvents.propTypes = {
selectEventFinished: PropTypes.func,
selectDate: PropTypes.func,
map: PropTypes.object,
- mapUi: PropTypes.object,
proj: PropTypes.object,
};
diff --git a/web/js/map/ui.js b/web/js/map/ui.js
index 5da485714..2f8e9010d 100644
--- a/web/js/map/ui.js
+++ b/web/js/map/ui.js
@@ -241,6 +241,8 @@ export default function mapui(models, config, store, ui) {
}, 100);
});
events.on('redux:action-dispatched', subscribeToStore);
+ events.on('map:reload-layers', reloadLayers);
+ events.on('map:update-date', updateDate);
updateProjection(true);
};
@@ -392,7 +394,7 @@ export default function mapui(models, config, store, ui) {
const zoom = self.selected.getView().getZoom();
const activeLayers = getActiveLayers(state).filter(({ projections }) => projections[proj.id]);
const maxZoom = getMaxZoomLevelLayerCollection(activeLayers, zoom, proj.id, sources);
- animateCoordinates({ ui: self }, config, coordinates, maxZoom);
+ animateCoordinates(self.selected, proj, coordinates, maxZoom);
}
// handle render initial tooltip
@@ -440,7 +442,6 @@ export default function mapui(models, config, store, ui) {
const map = self.selected;
const isProjectionRotatable = proj.id !== 'geographic' && proj.id !== 'webmerc';
-
const currentRotation = isProjectionRotatable ? map.getView().getRotation() : 0;
const rotationStart = isProjectionRotatable ? models.map.rotation : 0;
@@ -470,7 +471,6 @@ export default function mapui(models, config, store, ui) {
} else if (!models.map.extent && projId === 'geographic') {
extent = getLeadingExtent(config.pageLoadTime);
callback = () => {
- const map = self.selected;
const view = map.getView();
const extent = view.calculateExtent(map.getSize());
store.dispatch({ type: FITTED_TO_LEADING_EXTENT, extent });
@@ -478,7 +478,6 @@ export default function mapui(models, config, store, ui) {
}
if (projId !== 'geographic') {
callback = () => {
- const map = self.selected;
const view = map.getView();
view.setRotation(rotationStart);
};
@@ -519,6 +518,7 @@ export default function mapui(models, config, store, ui) {
map.addControl(map.wv.scaleMetric);
}
}
+
/*
* Hide Map
*
@@ -532,6 +532,7 @@ export default function mapui(models, config, store, ui) {
function hideMap(map) {
document.getElementById(`${map.getTarget()}`).style.display = 'none';
}
+
/*
* Show Map
*
@@ -545,6 +546,7 @@ export default function mapui(models, config, store, ui) {
function showMap(map) {
document.getElementById(`${map.getTarget()}`).style.display = 'block';
}
+
/*
* Remove Layers from map
*
@@ -565,6 +567,7 @@ export default function mapui(models, config, store, ui) {
});
cache.clear();
};
+
/*
* get layers from models obj
* and add each layer to the map
@@ -576,7 +579,7 @@ export default function mapui(models, config, store, ui) {
*
* @returns {void}
*/
- const reloadLayers = self.reloadLayers = function(map) {
+ function reloadLayers(map) {
map = map || self.selected;
const state = store.getState();
const { compare } = state;
@@ -614,7 +617,7 @@ export default function mapui(models, config, store, ui) {
}
}
updateLayerVisibilities();
- };
+ }
/**
* Create a Layergroup given the date and layerGroups
@@ -898,7 +901,6 @@ export default function mapui(models, config, store, ui) {
}
}
-
async function bufferQuickAnimate(arrowDown) {
const BUFFER_SIZE = 8;
const preloadPromises = [];
@@ -1210,5 +1212,9 @@ export default function mapui(models, config, store, ui) {
}
init();
- return self;
+ return {
+ ...self,
+ updateDate,
+ reloadLayers,
+ };
}
diff --git a/web/js/map/util.js b/web/js/map/util.js
index dc46c0fab..2b36787d7 100644
--- a/web/js/map/util.js
+++ b/web/js/map/util.js
@@ -1,4 +1,9 @@
-import { RESOLUTION_FOR_LARGE_WMS_TILES, RESOLUTION_FOR_SMALL_WMS_TILES } from '../modules/map/constants';
+import * as olExtent from 'ol/extent';
+import OlGeomLineString from 'ol/geom/LineString';
+import {
+ RESOLUTION_FOR_LARGE_WMS_TILES,
+ RESOLUTION_FOR_SMALL_WMS_TILES,
+} from '../modules/map/constants';
import util from '../util/util';
const ZOOM_DURATION = 250;
@@ -131,3 +136,87 @@ export function saveRotation(currentDeg, currentView) {
}
}
}
+
+/**
+ * Gets the best zoom level for the middle of the flight animation
+ *
+ * @param {integer} distance distance of the animation in map units
+ * @param {integer} start starting zoom level
+ * @param {integer} end ending zoom level
+ * @param {object} view map view
+ * @return {integer} best zoom level for flight animation
+ */
+const getBestZoom = function(distance, start, end, view) {
+ const idealLength = 1500;
+ const lines = [2, 3, 4, 5, 6, 7, 8].map((zoom) => ({
+ zoom,
+ pixels: distance / view.getResolutionForZoom(zoom),
+ }));
+ const bestFit = lines.sort((a, b) => Math.abs(idealLength - a.pixels) - Math.abs(idealLength - b.pixels))[0];
+ return Math.max(2, Math.min(bestFit.zoom, start - 1, end - 1));
+};
+
+/**
+ * Moves the map with a "flying" animation
+ *
+ * @param {Array} endPoint Ending coordinates
+ * @param {integer} endZoom Ending Zoom Level
+ * @return {Promise} Promise that is fulfilled when animation completes
+ */
+export function fly (map, proj, endPoint, endZoom = 5, rotation = 0) {
+ const view = map.getView();
+ const polarProjectionCheck = proj.selected.id !== 'geographic'; // boolean if current projection is polar
+ view.cancelAnimations();
+ const startPoint = view.getCenter();
+ const startZoom = Math.floor(view.getZoom());
+ if (endPoint.length > 2) endPoint = olExtent.getCenter(endPoint);
+ const extent = view.calculateExtent();
+ const hasEndInView = olExtent.containsCoordinate(extent, endPoint);
+ const line = new OlGeomLineString([startPoint, endPoint]);
+ const distance = line.getLength(); // In map units, which is usually degrees
+ const distanceDuration = polarProjectionCheck ? distance / 50000 : distance; // limit large polar projection distances from coordinate transforms
+ let duration = Math.floor(distanceDuration * 20 + 1000); // approx 6 seconds to go 360 degrees
+
+ const animationPromise = function(...args) {
+ return new Promise((resolve, reject) => {
+ args.push((complete) => {
+ if (complete) resolve();
+ if (!complete) reject(new Error('Animation interrupted!'));
+ });
+ view.animate(...args);
+ }).catch(() => {});
+ };
+ if (hasEndInView) {
+ // allow faster fly with nearby events
+ duration = duration < 1200 ? duration / 2 : duration;
+ // If the event is already visible, don't zoom out
+ return Promise.all([
+ animationPromise({
+ center: endPoint,
+ duration,
+ rotation,
+ }),
+ animationPromise({
+ zoom: endZoom,
+ duration,
+ rotation,
+ }),
+ ]);
+ }
+ // Default animation zooms out to arc
+ return Promise.all([
+ animationPromise({
+ center: endPoint,
+ duration,
+ rotation,
+ }),
+ animationPromise(
+ {
+ zoom: getBestZoom(distance, startZoom, endZoom, view),
+ duration: duration / 2,
+ rotation,
+ },
+ { zoom: endZoom, duration: duration / 2, rotation },
+ ),
+ ]);
+}
diff --git a/web/js/modules/location-search/util.js b/web/js/modules/location-search/util.js
index d2db5660e..0552e6520 100644
--- a/web/js/modules/location-search/util.js
+++ b/web/js/modules/location-search/util.js
@@ -11,6 +11,7 @@ import {
import { containsXY } from 'ol/extent';
import { coordinatesCRSTransform } from '../projection/util';
import safeLocalStorage from '../../util/local-storage';
+import { fly } from '../../map/util';
const { LOCATION_SEARCH_COLLAPSED } = safeLocalStorage.keys;
@@ -21,17 +22,14 @@ const { LOCATION_SEARCH_COLLAPSED } = safeLocalStorage.keys;
* @param {Array} coordinates
* @param {Number} zoom
*/
-export function animateCoordinates(map, config, coordinates, zoom) {
- const { projections } = config;
- const { selected } = map.ui;
- const { proj } = selected;
- const { crs } = projections[proj];
+export function animateCoordinates(map, proj, coordinates, zoom) {
+ const { crs } = proj.selected;
let [x, y] = coordinates;
if (proj !== 'geographic') {
[x, y] = coordinatesCRSTransform(coordinates, 'EPSG:4326', crs);
}
- map.ui.animate.fly([x, y], zoom);
+ fly(map, proj, [x, y], zoom);
}
/**