Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

geosearch init

Ed Platod45c0abd9984
diff --git a/config/default/common/features.json b/config/default/common/features.json
index 1fb746c92..7b49f54d5 100644
--- a/config/default/common/features.json
+++ b/config/default/common/features.json
@@ -8,6 +8,7 @@
"tour": true,
"feedback": true,
"previewSnapshots": true,
+ "geocodeSearch": true,
"googleTagManager": {
"id": "GTM-WNP7MLF"
},
diff --git a/package.json b/package.json
index 8ac0d96dc..68f65e739 100644
--- a/package.json
+++ b/package.json
@@ -178,6 +178,7 @@
"cachai": "^1.0.2",
"canvg-browser": "^1.0.0",
"compression": "^1.7.4",
+ "coordinate-parser": "^1.0.4",
"core-js": "^3.6.4",
"elm-pep": "^1.0.6",
"file-saver": "^2.0.2",
@@ -197,6 +198,7 @@
"prop-types": "^15.7.2",
"rc-slider": "9.2.2",
"react": "16.11.x",
+ "react-autocomplete": "^1.8.1",
"react-beautiful-dnd": "^13.0.0",
"react-copy-to-clipboard": "^5.0.2",
"react-dom": "^16.12.0",
diff --git a/web/css/geosearch.css b/web/css/geosearch.css
new file mode 100644
index 000000000..caf533275
--- /dev/null
+++ b/web/css/geosearch.css
@@ -0,0 +1,137 @@
+.geosearch-results-menu {
+ position: absolute;
+ width: 250px;
+}
+
+.geosearch-item:hover {
+ cursor: pointer;
+}
+
+.geosearch-input-container {
+ margin-right: 5px;
+}
+
+.geosearch-autocomplete {
+ padding: 0 5px;
+}
+
+.geosearch-autocomplete::placeholder {
+ color: #999;
+}
+
+.geosearch-item {
+ padding: 5px 0 5px 7px;
+ color: #333;
+}
+
+.geosearch-component-expanded-search {
+ position: absolute;
+ right: 0;
+ width: 350px;
+ transition: width 0.4s, height 0.4s;
+}
+
+.geosearch-component-expanded-search > div {
+ background: #fff;
+ padding: 1px;
+ border-radius: 2px;
+}
+
+.geosearch-component-minimized-button {
+ border-radius: 10px;
+ padding: 1px;
+}
+
+.geosearch-component-minimized-button.ui-button-click-prevent {
+ pointer-events: none;
+}
+
+.geosearch-component-minimized-button.ui-button-click-prevent svg.svg-inline--fa {
+ opacity: 0.4;
+}
+
+.geosearch-component-minimized-button svg.svg-inline--fa {
+ display: block;
+ width: 38px;
+ padding: 5px;
+ height: 45px;
+ color: #fff;
+}
+
+.geosearch-component-minimized-button svg.svg-inline--fa:hover {
+ color: #000;
+}
+
+.geosearch-component-minimized-button:hover {
+ background-color: #fff;
+ color: #1a1a1a;
+ border: 1px solid #333;
+}
+
+.geosearch-search-submit-container {
+ position: absolute;
+ border: 1px solid transparent;
+}
+
+.geosearch-search-submit-container .input-group-append .btn {
+ background: #fff;
+ border-top: 1px solid #ced4da;
+ border-bottom: 1px solid #ced4da;
+ margin-right: 2px;
+}
+
+.geosearch-search-submit-container .btn {
+ background: #fff;
+ border: none;
+ color: #808080;
+}
+
+.geosearch-coordinate-button-group .btn-group > .btn-group:not(:last-child) > .btn, .btn-group > .btn:not(:last-child):not(.dropdown-toggle) {
+ border-top-left-radius: 10px;
+ border-bottom-left-radius: 10px;
+}
+
+.geosearch-coordinate-button-group .btn-group > .btn-group:not(:first-child) > .btn, .btn-group > .btn:not(:first-child) {
+ border-top-right-radius: 10px;
+ border-bottom-right-radius: 10px;
+}
+
+.geosearch-coordinate-button-group .btn {
+ background: #0070c8;
+}
+.geosearch-coordinate-button-group .btn:hover {
+ background: #00457b;
+}
+
+.geosearch-component-expanded-search .minimized {
+ width: 42px;
+}
+
+.geosearch-component-expanded-search .expanded {
+ width: 350px;
+ height: 33.25px;
+ opacity: 1;
+}
+
+.geosearch-component-button-container {
+ position: absolute;
+ right: 11px;
+ top: 95px;
+ z-index: 10000;
+ background: none rgba(40, 40, 40, 0.85);
+ border-radius: 10px;
+ width: 42px;
+ height: 49px;
+ transition: width 0.4s, height 0.4s;
+}
+
+.geosearch-component-button-container.expanded {
+ border-radius: 1px;
+ width: 349.95px;
+ height: 33.25px;
+}
+
+.geosearch-coordinate-button-remove p {
+ font-weight: 700;
+ font-size: 1.3em;
+}
diff --git a/web/images/map-pin.png b/web/images/map-pin.png
new file mode 100644
index 000000000..6ec75b1d8
Binary files /dev/null and b/web/images/map-pin.png differ
diff --git a/web/js/app.js b/web/js/app.js
index 441854efb..dc06ad634 100644
--- a/web/js/app.js
+++ b/web/js/app.js
@@ -16,6 +16,8 @@ import Toolbar from './containers/toolbar';
import Sidebar from './containers/sidebar/sidebar';
// Modal
import Modal from './containers/modal';
+// GeoSearch
+import Geosearch from './components/geosearch/geosearch';
// Other/MISC
import Brand from './brand';
@@ -85,6 +87,7 @@ import '../css/geostationary-modal.css';
import '../css/orbitTracks.css';
import '../css/facets.css';
import '../css/recent-layers.css';
+import '../css/geosearch.css';
import '../pages/css/document.css';
require('@elastic/react-search-ui-views/lib/styles/styles.css');
@@ -177,7 +180,12 @@ class App extends React.Component {
render() {
const {
- isAnimationWidgetActive, isTourActive, locationKey, modalId, mapMouseEvents, parameters,
+ isAnimationWidgetActive,
+ isTourActive,
+ locationKey,
+ mapMouseEvents,
+ modalId,
+ parameters,
} = this.props;
return (
<div className="wv-content" id="wv-content" data-role="content">
@@ -197,6 +205,7 @@ class App extends React.Component {
<div id="wv-animation-widet-case">
{isAnimationWidgetActive ? <AnimationWidget key={locationKey || '2'} /> : null}
</div>
+ <Geosearch />
<MeasureButton />
<Modal key={modalId} />
<ErrorBoundary>
@@ -235,6 +244,7 @@ export default connect(
mapDispatchToProps,
)(App);
App.propTypes = {
+ // config: PropTypes.object,
isAnimationWidgetActive: PropTypes.bool,
isTourActive: PropTypes.bool,
keyPressAction: PropTypes.func,
diff --git a/web/js/components/geosearch/geosearch-helpers.js b/web/js/components/geosearch/geosearch-helpers.js
new file mode 100644
index 000000000..30500e40c
--- /dev/null
+++ b/web/js/components/geosearch/geosearch-helpers.js
@@ -0,0 +1,103 @@
+import safeLocalStorage from '../../util/local-storage';
+
+const { SEARCH_TOKEN } = safeLocalStorage.keys;
+
+export function getTokenDataFromStorage() {
+ const tokenData = safeLocalStorage.getItem(SEARCH_TOKEN);
+ if (tokenData) {
+ return JSON.parse(tokenData);
+ }
+ return {};
+}
+
+export function getTokenFromStorage() {
+ const tokenData = getTokenDataFromStorage();
+ return tokenData.token;
+}
+
+function getTokenExpiryFromStorage() {
+ const tokenData = getTokenDataFromStorage();
+ return tokenData.expires;
+}
+
+export function isTokenExpired() {
+ const time = Date.now();
+ const expires = getTokenExpiryFromStorage();
+ if (!expires) {
+ return true;
+ }
+ return expires <= time;
+}
+
+function setTokenDataToStorage(tokenData) {
+ safeLocalStorage.setItem(SEARCH_TOKEN, JSON.stringify(tokenData));
+}
+
+export function setTokenFromStorage() {
+ return fetchToken().then((result) => {
+ const req = JSON.parse(result);
+ const expires = Date.now() + req.expires_in * 1000; // 7200 -> 7200000 -or- 2 hours
+ const tokenData = {
+ expires,
+ token: req.access_token,
+ };
+ return tokenData;
+ }).then((tokenData) => new Promise((resolve) => setTimeout(() => resolve(tokenData), 8000)))
+ .then((tokenData) => {
+ setTokenDataToStorage(tokenData);
+ return tokenData;
+ });
+}
+
+export function fetchTokenData() {
+ const y = setTokenFromStorage();
+ return {
+ token: wrapPromise(y),
+ };
+}
+
+// Suspense integrations like Relay implement
+// a contract like this to integrate with React.
+// Real implementations can be significantly more complex.
+// Don't copy-paste this into your project!
+function wrapPromise(promise) {
+ let status = 'pending';
+ let result;
+ const suspender = promise.then(
+ (r) => {
+ status = 'success';
+ result = r;
+ },
+ (e) => {
+ status = 'error';
+ result = e;
+ },
+ );
+ return {
+ read() {
+ if (status === 'pending') {
+ throw suspender;
+ } else if (status === 'error') {
+ throw result;
+ } else if (status === 'success') {
+ return result;
+ }
+ },
+ };
+}
+
+// TODO: ADD ENV VARIABLES FOR CLIENT ID, CLIENT SECRET
+const formdata = new FormData();
+
+const requestOptions = {
+ method: 'POST',
+ body: formdata,
+ redirect: 'follow',
+};
+
+function fetchToken() {
+ return fetch('https://www.arcgis.com/sharing/rest/oauth2/token', requestOptions)
+ .then((response) => response.text())
+ .then((result) => result)
+ .catch((error) => console.log('error', error));
+}
diff --git a/web/js/components/geosearch/geosearch-input.js b/web/js/components/geosearch/geosearch-input.js
new file mode 100644
index 000000000..5825e681e
--- /dev/null
+++ b/web/js/components/geosearch/geosearch-input.js
@@ -0,0 +1,136 @@
+import React, { Component } from 'react';
+import PropTypes from 'prop-types';
+import Autocomplete from 'react-autocomplete';
+import isValidCoordinates from './util';
+import { reverseGeocode, suggest, processMagicKey } from '../../modules/geosearch/selectors';
+
+
+class SearchBox extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ searchResults: [],
+ };
+ this.requestTimer = null;
+ }
+
+ componentDidMount() {
+ this.input.focus();
+ }
+
+ updateSearchResults = (searchResults) => this.setState({ searchResults });
+
+ // handle selecting menu item in search results
+ onSelect=(value, item) => {
+ const { selectCoordinatesToFly, updateValue } = this.props;
+ // set the menu to only the selected item
+
+ this.updateSearchResults([item]);
+ updateValue(value);
+ const {
+ magicKey,
+ // text,
+ } = item;
+
+ processMagicKey(magicKey).then((result) => {
+ const firstCandidate = result.candidates[0];
+ const { location } = firstCandidate;
+ // TODO TEST NO FIRST CANDIDATE
+ const { x, y } = location;
+ const parsedX = parseFloat(x.toPrecision(7));
+ const parsedY = parseFloat(y.toPrecision(7));
+ selectCoordinatesToFly([parsedX, parsedY]);
+ });
+ }
+
+ // handle input value change including text/coordinates typing, pasting, cutting
+ onChange=(e, value) => {
+ // e.preventDefault();
+ const { selectCoordinatesToFly, updateValue } = this.props;
+
+ updateValue(value);
+ // check for coordinate value
+ const coordinatesInputValue = isValidCoordinates(value);
+ if (coordinatesInputValue) {
+ clearTimeout(this.requestTimer);
+ this.updateSearchResults([]);
+
+ const { latitude, longitude } = coordinatesInputValue;
+ // TODO: require click/enter to search coordinates
+ reverseGeocode([longitude, latitude]).then((results) => {
+ selectCoordinatesToFly([longitude, latitude], results);
+ });
+ } else {
+ clearTimeout(this.requestTimer);
+ if (!value) {
+ this.updateSearchResults([]);
+ } else {
+ // provide suggestions to populate search result menu item(s)
+ this.requestTimer = suggest(value).then((items) => {
+ const { suggestions } = items;
+ this.updateSearchResults(suggestions);
+ });
+ }
+ }
+ }
+
+ // search result menu item container
+ renderMenu= (children) => (
+ <div className="geosearch-results-menu">
+ {children}
+ </div>
+ )
+
+ // individual menu items with conditional styling
+ renderItem=(item, isHighlighted) => (
+ <div
+ className="geosearch-item"
+ style={{
+ background: isHighlighted ? '#0070c8' : '#fff',
+ color: isHighlighted ? '#fff' : '#000',
+ }}
+ key={item.text}
+ >
+ {item.text}
+ </div>
+ )
+
+ render() {
+ const { searchResults } = this.state;
+ const { coordinates, inputValue } = this.props;
+ const wrapperStyleWidth = `${coordinates.length > 0 ? '250px' : '283px'}`;
+
+ return (
+ <div className="geosearch-input-container">
+ <Autocomplete
+ // eslint-disable-next-line no-return-assign
+ ref={(el) => this.input = el}
+ inputProps={{
+ className: 'form-control geosearch-autocomplete',
+ id: 'geosearch-autocomplete',
+ placeholder: 'Search for places and coordinates',
+ }}
+ wrapperStyle={{
+ width: wrapperStyleWidth,
+ }}
+ value={inputValue}
+ items={searchResults}
+ getItemValue={(item) => item.text}
+ onSelect={this.onSelect}
+ onChange={this.onChange}
+ renderMenu={this.renderMenu}
+ renderItem={this.renderItem}
+ />
+ </div>
+ );
+ }
+}
+
+SearchBox.propTypes = {
+ selectCoordinatesToFly: PropTypes.func,
+ coordinates: PropTypes.array,
+ inputValue: PropTypes.string,
+ updateValue: PropTypes.func,
+};
+
+export default SearchBox;
diff --git a/web/js/components/geosearch/geosearch-modal.js b/web/js/components/geosearch/geosearch-modal.js
new file mode 100644
index 000000000..65da0f4fc
--- /dev/null
+++ b/web/js/components/geosearch/geosearch-modal.js
@@ -0,0 +1,120 @@
+import PropTypes from 'prop-types';
+import React, { Component } from 'react';
+import {
+ ButtonGroup, Button, InputGroup, InputGroupAddon,
+} from 'reactstrap';
+import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
+import {
+ faSearchLocation,
+ faMapMarkerAlt,
+ faChevronRight,
+} from '@fortawesome/free-solid-svg-icons';
+import SearchBox from './geosearch-input';
+
+class SearchComponent extends Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ inputValue: '',
+ };
+ }
+
+ updateValue = (inputValue) => {
+ this.setState({
+ inputValue,
+ });
+ }
+
+ selectCoordinatesFromMap = (e) => {
+ const { toggleReverseGeocodeActive } = this.props;
+ e.preventDefault();
+ toggleReverseGeocodeActive(true);
+ }
+
+ selectCoordinatesToFly = (coordinates) => {
+ const { selectCoordinatesToFly } = this.props;
+ selectCoordinatesToFly(coordinates);
+ }
+
+ render() {
+ const {
+ coordinates, clearCoordinates, shouldHide, toggleShowGeosearch,
+ } = this.props;
+ const { inputValue } = this.state;
+ const hasCoordinates = coordinates.length > 0;
+ const textEntered = inputValue;
+ const containerClass = `geosearch-component-expanded-search ${!shouldHide ? 'expanded' : ''}`;
+
+ return (
+ <div className={containerClass}>
+ <div>
+ <InputGroup>
+ <InputGroupAddon addonType="prepend">
+ <Button
+ className="geosearch-search-minimize-button"
+ title="Minimize search box"
+ onClick={toggleShowGeosearch}
+ >
+ <FontAwesomeIcon icon={faChevronRight} size="1x" />
+ </Button>
+ </InputGroupAddon>
+ <SearchBox
+ coordinates={coordinates}
+ selectCoordinatesToFly={this.selectCoordinatesToFly}
+ isCoordinateSearchActive={false}
+ updateValue={this.updateValue}
+ inputValue={inputValue}
+ />
+ <InputGroupAddon className={`geosearch-search-submit-container ${hasCoordinates ? 'grouped' : ''}`} addonType="append">
+ <Button
+ style={{
+ color: `${textEntered ? '#0070c8' : ''}`,
+ left: `${hasCoordinates ? '244px' : '279px'}`,
+ }}
+ disabled={!textEntered}
+ className="geosearch-search-submit-button"
+ title="Search by place name or reverse search using coordinates"
+ >
+ <FontAwesomeIcon icon={faSearchLocation} size="1x" />
+ </Button>
+ </InputGroupAddon>
+ <InputGroupAddon addonType="append" className={`geosearch-coordinate-group-container ${hasCoordinates ? 'grouped' : ''}`}>
+ <ButtonGroup className="geosearch-coordinate-button-group">
+ <Button
+ onTouchEnd={this.selectCoordinatesFromMap}
+ onMouseDown={this.selectCoordinatesFromMap}
+ className="geosearch-coordinate-button-addpoint"
+ title="Add coordinates marker onto map"
+ >
+ <FontAwesomeIcon icon={faMapMarkerAlt} size="1x" />
+ </Button>
+ {hasCoordinates
+ && (
+ <Button
+ onTouchEnd={clearCoordinates}
+ onMouseDown={clearCoordinates}
+ className="geosearch-coordinate-button-remove"
+ title="Clear coordinates marker from map"
+ >
+ <p>X</p>
+ </Button>
+ )}
+ </ButtonGroup>
+ </InputGroupAddon>
+ </InputGroup>
+ </div>
+ </div>
+ );
+ }
+}
+
+SearchComponent.propTypes = {
+ coordinates: PropTypes.array,
+ selectCoordinatesToFly: PropTypes.func,
+ toggleReverseGeocodeActive: PropTypes.func,
+ clearCoordinates: PropTypes.func,
+ shouldHide: PropTypes.bool,
+ toggleShowGeosearch: PropTypes.func,
+};
+
+export default SearchComponent;
diff --git a/web/js/components/geosearch/geosearch.js b/web/js/components/geosearch/geosearch.js
new file mode 100644
index 000000000..d3bf0fae3
--- /dev/null
+++ b/web/js/components/geosearch/geosearch.js
@@ -0,0 +1,140 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+import { connect } from 'react-redux';
+import { Button } from 'reactstrap';
+// import googleTagManager from 'googleTagManager';
+import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
+import { faSearchLocation } from '@fortawesome/free-solid-svg-icons';
+import GeosearchModal from './geosearch-modal';
+import {
+ clearCoordinates,
+ selectCoordinatesToFly,
+ toggleShowGeosearch,
+ toggleReverseGeocodeActive,
+} from '../../modules/geosearch/actions';
+
+class Geosearch extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = {
+ };
+ }
+
+ renderSearchComponent = () => {
+ const {
+ coordinates,
+ clearCoordinates,
+ isDistractionFreeModeActive,
+ isExpanded,
+ selectCoordinatesToFly,
+ shouldBeCollapsed,
+ toggleShowGeosearch,
+ toggleReverseGeocodeActive,
+ } = this.props;
+ const shouldHide = shouldBeCollapsed || isDistractionFreeModeActive || !isExpanded;
+ return (
+ <GeosearchModal
+ coordinates={coordinates}
+ shouldHide={shouldHide}
+ clearCoordinates={clearCoordinates}
+ selectCoordinatesToFly={selectCoordinatesToFly}
+ toggleShowGeosearch={toggleShowGeosearch}
+ toggleReverseGeocodeActive={toggleReverseGeocodeActive}
+ />
+ );
+ }
+
+ renderSearchButton = () => {
+ const { isExpanded, toggleShowGeosearch } = this.props;
+ return (
+ <Button
+ id="wv-geosearch-button"
+ className="geosearch-component-minimized-button"
+ title="Search by place name or reverse search using coordinates"
+ onTouchEnd={toggleShowGeosearch}
+ onMouseDown={toggleShowGeosearch}
+ disabled={isExpanded}
+ color="none"
+ >
+ <FontAwesomeIcon icon={faSearchLocation} size="1x" />
+ </Button>
+ );
+ }
+
+ render() {
+ const {
+ isExpanded,
+ isFeatureEnabled,
+ } = this.props;
+ if (!isFeatureEnabled) {
+ return null;
+ }
+
+ const containerClass = `geosearch-component-button-container ${isExpanded ? 'expanded' : ''}`;
+ return (
+ <>
+ <div className={containerClass}>
+ {isExpanded
+ ? this.renderSearchComponent()
+ : this.renderSearchButton()}
+ </div>
+ </>
+ );
+ }
+}
+
+const mapStateToProps = (state) => {
+ const {
+ config,
+ modal,
+ measure,
+ animation,
+ geosearch,
+ ui,
+ } = state;
+ const { features: { geocodeSearch: search } } = config;
+ const { coordinates, isExpanded } = geosearch;
+ const { isDistractionFreeModeActive } = ui;
+ const snapshotModalOpen = modal.isOpen && modal.id === 'TOOLBAR_SNAPSHOT';
+ // Collapse when Image download / GIF / is open or measure tool active
+ const shouldBeCollapsed = snapshotModalOpen || measure.isActive || animation.gifActive;
+
+ return {
+ coordinates,
+ isExpanded,
+ shouldBeCollapsed,
+ isFeatureEnabled: search,
+ isDistractionFreeModeActive,
+ };
+};
+const mapDispatchToProps = (dispatch) => ({
+ selectCoordinatesToFly: (coordinates) => {
+ dispatch(selectCoordinatesToFly(coordinates));
+ },
+ toggleShowGeosearch: () => {
+ dispatch(toggleShowGeosearch());
+ },
+ clearCoordinates: () => {
+ dispatch(clearCoordinates());
+ },
+ toggleReverseGeocodeActive: (isActive) => {
+ dispatch(toggleReverseGeocodeActive(isActive));
+ },
+});
+
+Geosearch.propTypes = {
+ isFeatureEnabled: PropTypes.bool.isRequired,
+ clearCoordinates: PropTypes.func,
+ coordinates: PropTypes.array,
+ isExpanded: PropTypes.bool,
+ isDistractionFreeModeActive: PropTypes.bool,
+ selectCoordinatesToFly: PropTypes.func,
+ shouldBeCollapsed: PropTypes.bool,
+ toggleReverseGeocodeActive: PropTypes.func,
+ toggleShowGeosearch: PropTypes.func,
+};
+
+export default connect(
+ mapStateToProps,
+ mapDispatchToProps,
+)(Geosearch);
diff --git a/web/js/components/geosearch/util.js b/web/js/components/geosearch/util.js
new file mode 100644
index 000000000..306d77114
--- /dev/null
+++ b/web/js/components/geosearch/util.js
@@ -0,0 +1,56 @@
+import CoordinateParser from 'coordinate-parser';
+// import safeLocalStorage from '../../util/local-storage';
+
+// const { SEARCH_TOKEN } = safeLocalStorage.keys;
+
+// export function getTokenDataFromStorage() {
+// const tokenData = safeLocalStorage.getItem(SEARCH_TOKEN);
+// if (tokenData) {
+// return JSON.parse(tokenData);
+// }
+// return {};
+// }
+
+// export function getTokenFromStorage() {
+// const tokenData = getTokenDataFromStorage();
+// return tokenData.token;
+// }
+
+// function getTokenExpiryFromStorage() {
+// const tokenData = getTokenDataFromStorage();
+// return tokenData.expires;
+// }
+
+// export function isTokenExpired() {
+// const time = Date.now();
+// const expires = getTokenExpiryFromStorage();
+// if (!expires) {
+// return true;
+// }
+// return expires <= time;
+// }
+
+// function setTokenDataToStorage(tokenData) {
+// safeLocalStorage.setItem(SEARCH_TOKEN, JSON.stringify(tokenData));
+// }
+
+// TEMP TOKEN FUNC USED IN COMPONENT
+// function Token() {
+// // Try to read user info, although it might not have loaded yet
+// let token;
+// if (isTokenExpired()) {
+// token = tokenData.token.read();
+// } else {
+// token = getTokenFromStorage();
+// }
+// return <h1>{token.access_token}</h1>;
+// }
+
+export default function isValidCoordinates(position) {
+ try {
+ const validatedCoordinates = new CoordinateParser(position);
+ return validatedCoordinates;
+ } catch (error) {
+ return false;
+ }
+}
diff --git a/web/js/components/map/ol-coordinates.js b/web/js/components/map/ol-coordinates.js
index 5bef0d107..5abb2bedb 100644
--- a/web/js/components/map/ol-coordinates.js
+++ b/web/js/components/map/ol-coordinates.js
@@ -3,6 +3,7 @@ import PropTypes from 'prop-types';
import { transform } from 'ol/proj';
import Coordinates from './coordinates';
import util from '../../util/util';
+import { reverseGeocode } from '../../modules/geosearch/selectors';
export default class OlCoordinates extends React.Component {
constructor(props) {
@@ -16,22 +17,36 @@ export default class OlCoordinates extends React.Component {
};
this.mouseMove = this.mouseMove.bind(this);
this.mouseOut = this.mouseOut.bind(this);
+ this.mouseClick = this.mouseClick.bind(this);
this.changeFormat = this.changeFormat.bind(this);
this.registerMouseListeners();
}
componentWillUnmount() {
const { mouseEvents } = this.props;
+ mouseEvents.on('click', this.mouseClick);
mouseEvents.off('mousemove', this.mouseMove);
mouseEvents.off('mouseout', this.mouseOut);
}
registerMouseListeners() {
const { mouseEvents } = this.props;
+ mouseEvents.on('click', this.mouseClick);
mouseEvents.on('mousemove', this.mouseMove);
mouseEvents.on('mouseout', this.mouseOut);
}
+ mouseClick() {
+ const { selectCoordinatesToFly, isCoordinateSearchActive } = this.props;
+ const { latitude, longitude } = this.state;
+
+ if (isCoordinateSearchActive) {
+ reverseGeocode([longitude, latitude]).then((results) => {
+ selectCoordinatesToFly([longitude, latitude], results);
+ });
+ }
+ }
+
mouseMove(event, map, crs) {
const pixels = map.getEventPixel(event);
const coord = map.getCoordinateFromPixel(pixels);
@@ -110,4 +125,6 @@ export default class OlCoordinates extends React.Component {
OlCoordinates.propTypes = {
mouseEvents: PropTypes.object.isRequired,
+ isCoordinateSearchActive: PropTypes.bool,
+ selectCoordinatesToFly: PropTypes.func,
};
diff --git a/web/js/containers/coordinates-dialog.js b/web/js/containers/coordinates-dialog.js
new file mode 100644
index 000000000..daa596a53
--- /dev/null
+++ b/web/js/containers/coordinates-dialog.js
@@ -0,0 +1,98 @@
+/* eslint-disable no-restricted-syntax */
+import React from 'react';
+import { connect } from 'react-redux';
+import PropTypes from 'prop-types';
+import {
+ ModalBody, ModalHeader, Nav, NavItem, NavLink,
+} from 'reactstrap';
+// import Scrollbars from '../components/util/scrollbar';
+import VectorMetaTable from '../components/vector-metadata/table';
+
+class CoordinatesDialog extends React.Component {
+ constructor(props) {
+ super(props);
+ this.state = { activeIndex: 0 };
+ this.updateIndex = this.updateIndex.bind(this);
+ }
+
+ updateIndex(activeIndex) {
+ // eslint-disable-next-line react/destructuring-assignment
+ if (activeIndex === this.state.activeIndex) return;
+ this.setState({ activeIndex });
+ }
+
+ render() {
+ const {
+ toggleWithClose, vectorMetaObject, modalHeight, dialogKey,
+ } = this.props;
+ const { activeIndex } = this.state;
+ // const navArray = [];
+ const keyArray = [];
+ let i = 0;
+ console.log(vectorMetaObject);
+ for (const [key, value] of Object.entries(vectorMetaObject)) {
+ const stringLength = 20;
+ const title = value[0].title || key;
+ const { subTitle } = value[0];
+ const titleText = title.length > stringLength ? `${title.substring(0, stringLength)}...` : title;
+ const combinedTitles = subTitle ? `${title} - ${subTitle}` : title;
+ const index = i;
+ keyArray.push(key);
+ // navArray.push(
+ // <NavItem
+ // key={key}
+ // className="vector-meta-nav-item"
+ // active={activeIndex === i}
+ // >
+ // <NavLink onClick={() => this.updateIndex(index)} title={combinedTitles}>
+ // {`${titleText} [${value.length}]`}
+ // </NavLink>
+ // </NavItem>,
+ // );
+ i += 1;
+ }
+ const activeMetaArray = vectorMetaObject[keyArray[activeIndex]];
+ console.log(activeMetaArray);
+ return (
+ <div className="draggable-modal-content">
+ <ModalHeader toggle={toggleWithClose}>
+ {/* TEST TITLE MODAL HEADER */}
+ </ModalHeader>
+
+ <ModalBody>
+ <VectorMetaTable id={dialogKey} metaArray={activeMetaArray} title={keyArray[activeIndex]} />
+ </ModalBody>
+ </div>
+ );
+
+ // return (
+ // <div className="draggable-modal-content">
+ // <ModalHeader toggle={toggleWithClose}>
+ // <Nav tabs id="vector-meta-nav" className="vector-meta-nav">
+ // {navArray}
+ // </Nav>
+ // </ModalHeader>
+
+ // <ModalBody>
+ // <Scrollbars style={{ maxHeight: `${modalHeight - 70}px` }}>
+ // <VectorMetaTable id={dialogKey} metaArray={activeMetaArray} title={keyArray[activeIndex]} />;
+ // </Scrollbars>
+ // </ModalBody>
+ // </div>
+ // );
+ }
+}
+
+function mapStateToProps(state) {
+ return {};
+}
+export default connect(
+ mapStateToProps,
+ null,
+)(CoordinatesDialog);
+CoordinatesDialog.propTypes = {
+ dialogKey: PropTypes.number,
+ modalHeight: PropTypes.number,
+ toggleWithClose: PropTypes.func,
+ vectorMetaObject: PropTypes.object,
+};
diff --git a/web/js/containers/map-interactions/map-interactions.js b/web/js/containers/map-interactions/map-interactions.js
index 93242bf12..bbe54ca85 100644
--- a/web/js/containers/map-interactions/map-interactions.js
+++ b/web/js/containers/map-interactions/map-interactions.js
@@ -4,11 +4,14 @@ import PropTypes from 'prop-types';
import OlCoordinates from '../../components/map/ol-coordinates';
import OlVectorInteractions from './ol-vector-interactions';
import OlMeasureTool from '../../components/map/ol-measure-tool';
+import { selectCoordinatesToFly } from '../../modules/geosearch/actions';
class MapInteractions extends React.PureComponent {
render() {
const {
+ selectCoordinatesToFly,
isDistractionFreeModeActive,
+ isCoordinateSearchActive,
isShowingClick,
mouseEvents,
} = this.props;
@@ -26,6 +29,8 @@ class MapInteractions extends React.PureComponent {
<>
<OlCoordinates
mouseEvents={mouseEvents}
+ selectCoordinatesToFly={selectCoordinatesToFly}
+ isCoordinateSearchActive={isCoordinateSearchActive}
/>
</>
@@ -39,17 +44,29 @@ class MapInteractions extends React.PureComponent {
}
}
function mapStateToProps(state) {
- const { map, ui } = state;
+ const { geosearch, map, ui } = state;
+ const { isCoordinateSearchActive } = geosearch;
return {
isShowingClick: map.isClickable,
isDistractionFreeModeActive: ui.isDistractionFreeModeActive,
+ isCoordinateSearchActive,
};
}
+
+const mapDispatchToProps = (dispatch) => ({
+ selectCoordinatesToFly: (coordinates, reverseGeocodeResults) => {
+ dispatch(selectCoordinatesToFly(coordinates, reverseGeocodeResults));
+ },
+});
+
MapInteractions.propTypes = {
isDistractionFreeModeActive: PropTypes.bool.isRequired,
isShowingClick: PropTypes.bool.isRequired,
mouseEvents: PropTypes.object.isRequired,
+ isCoordinateSearchActive: PropTypes.bool,
+ selectCoordinatesToFly: PropTypes.func,
};
export default connect(
mapStateToProps,
+ mapDispatchToProps,
)(MapInteractions);
diff --git a/web/js/containers/map-interactions/ol-vector-interactions.js b/web/js/containers/map-interactions/ol-vector-interactions.js
index 401952f44..c9c686241 100644
--- a/web/js/containers/map-interactions/ol-vector-interactions.js
+++ b/web/js/containers/map-interactions/ol-vector-interactions.js
@@ -12,6 +12,7 @@ import { transform } from 'ol/proj';
import { isFromActiveCompareRegion } from '../../modules/compare/util';
import { hasNonClickableVectorLayer } from '../../modules/layers/util';
import vectorDialog from '../vector-dialog';
+import coordinatesDialog from '../coordinates-dialog';
import { onMapClickGetVectorFeatures } from '../../modules/vector-styles/util';
import { openCustomContent, onClose } from '../../modules/modal/actions';
import { selectVectorFeatures as selectVectorFeaturesActionCreator } from '../../modules/vector-styles/actions';
@@ -65,34 +66,40 @@ export class VectorInteractions extends React.Component {
const {
lastSelected, openVectorDiaglog, onCloseModal, selectVectorFeatures,
modalState, getDialogObject, measureIsActive, isMobile, activeLayers,
- activateVectorAlert, proj,
+ activateVectorAlert, proj, openCoordinatesDialog,
} = this.props;
if (measureIsActive) return;
const isVectorModalOpen = modalState.id.includes('vector_dialog') && modalState.isOpen;
const pixels = e.pixel;
const clickObj = getDialogObject(pixels, map);
+ console.log(clickObj);
const metaArray = clickObj.metaArray || [];
const selected = clickObj.selected || {};
const offsetLeft = clickObj.offsetLeft || 10;
const offsetTop = clickObj.offsetTop || 100;
+ const isCoordinatesMarker = clickObj.isCoordinatesMarker || false;
const dialogId = isVectorModalOpen ? modalState.id : `vector_dialog${pixels[0]}${pixels[1]}`;
- if (metaArray.length) {
- openVectorDiaglog(dialogId, metaArray, offsetLeft, offsetTop, isMobile);
+ if (isCoordinatesMarker) {
+ openCoordinatesDialog(dialogId, metaArray, offsetLeft, offsetTop, isMobile);
} else {
- const mapRes = map.getView().getResolution();
- const hasNonClickableVectorLayerType = hasNonClickableVectorLayer(activeLayers, mapRes, proj.id);
+ if (metaArray.length) {
+ openVectorDiaglog(dialogId, metaArray, offsetLeft, offsetTop, isMobile);
+ } else {
+ const mapRes = map.getView().getResolution();
+ const hasNonClickableVectorLayerType = hasNonClickableVectorLayer(activeLayers, mapRes, proj.id);
- if (hasNonClickableVectorLayerType) {
- activateVectorAlert();
+ if (hasNonClickableVectorLayerType) {
+ activateVectorAlert();
+ }
+ }
+ if (Object.entries(selected).length || (Object.entries(lastSelected).length && !isVectorModalOpen)) {
+ selectVectorFeatures(selected);
+ } else if (isVectorModalOpen && !Object.entries(selected).length) {
+ onCloseModal();
+ selectVectorFeatures({});
}
- }
- if (Object.entries(selected).length || (Object.entries(lastSelected).length && !isVectorModalOpen)) {
- selectVectorFeatures(selected);
- } else if (isVectorModalOpen && !Object.entries(selected).length) {
- onCloseModal();
- selectVectorFeatures({});
}
}
@@ -187,6 +194,35 @@ function mapStateToProps(state) {
},
}));
},
+ openCoordinatesDialog: (dialogId, metaArray, offsetLeft, offsetTop, isMobile) => {
+ const dialogKey = Date.now();
+ dispatch(openCustomContent(dialogId,
+ {
+ backdrop: false,
+ clickableBehindModal: true,
+ desktopOnly: true,
+ isDraggable: true,
+ wrapClassName: 'vector-modal-wrap',
+ modalClassName: 'vector-modal light',
+ CompletelyCustomModal: coordinatesDialog,
+ isResizable: false,
+ dragHandle: '.modal-header',
+ dialogKey,
+ key: dialogKey,
+ vectorMetaObject: lodashGroupBy(metaArray, 'id'),
+ width: isMobile ? 250 : 445,
+ height: 300,
+ offsetLeft,
+ offsetTop,
+ timeout: 0,
+ isOpen: true,
+ onClose: () => {
+ setTimeout(() => {
+ dispatch(selectVectorFeaturesActionCreator({}));
+ }, 1);
+ },
+ }));
+ },
});
VectorInteractions.propTypes = {
changeCursor: PropTypes.func.isRequired,
@@ -202,6 +238,7 @@ VectorInteractions.propTypes = {
isMobile: PropTypes.bool,
lastSelected: PropTypes.object,
proj: PropTypes.object,
+ openCoordinatesDialog: PropTypes.func,
swipeOffset: PropTypes.number,
activeLayers: PropTypes.array,
activateVectorAlert: PropTypes.func,
diff --git a/web/js/containers/modal.js b/web/js/containers/modal.js
index 23d69d463..1772cf2f2 100644
--- a/web/js/containers/modal.js
+++ b/web/js/containers/modal.js
@@ -122,19 +122,23 @@ class ModalContainer extends Component {
handle={dragHandle}
disabled={!isDraggable}
>
- <Resizable
- className="resize-box"
- resizeHandles={['se']}
- width={width || newProps.width}
- height={height || newProps.height}
- minConstraints={[250, 250]}
- maxConstraints={[495, screenHeight]}
- handleSize={[8, 8]}
- onResize={this.onResize}
- draggableOpts={{ disabled: !isResizable }}
- >
- {children}
- </Resizable>
+ {isResizable
+ ? (
+ <Resizable
+ className="resize-box"
+ resizeHandles={['se']}
+ width={width || newProps.width}
+ height={height || newProps.height}
+ minConstraints={[250, 250]}
+ maxConstraints={[495, screenHeight]}
+ handleSize={[8, 8]}
+ onResize={this.onResize}
+ draggableOpts={{ disabled: !isResizable }}
+ >
+ {children}
+ </Resizable>
+ )
+ : children}
</Draggable>
)}
diff --git a/web/js/location.js b/web/js/location.js
index 34233ee44..c49f1e785 100644
--- a/web/js/location.js
+++ b/web/js/location.js
@@ -25,6 +25,8 @@ import { resetLayers, hasSubDaily } from './modules/layers/selectors';
import { eventsReducerState } from './modules/natural-events/reducers';
import { mapLocationToPaletteState } from './modules/palettes/util';
import { mapLocationToAnimationState } from './modules/animation/util';
+import mapLocationToGeosearchState from './modules/geosearch/util';
+import { areCoordinatesWithinExtent } from './modules/geosearch/selectors';
import mapLocationToSidebarState from './modules/sidebar/util';
import util from './util/util';
import mapLocationToDataState from './modules/data/util';
@@ -58,6 +60,11 @@ export const mapLocationToState = (state, location) => {
state,
config,
);
+ stateFromLocation = mapLocationToGeosearchState(
+ parameters,
+ stateFromLocation,
+ state,
+ );
stateFromLocation = mapLocationToCompareState(
parameters,
stateFromLocation,
@@ -429,6 +436,25 @@ const getParameters = function(config, parameters) {
},
},
},
+ marker: {
+ stateKey: 'geosearch.coordinates',
+ initialState: [],
+ type: 'string',
+ options: {
+ serializeNeedsGlobalState: true,
+ parse: (coordinates) => coordinates,
+ serialize: (coordinates, state) => {
+ const { map } = state;
+ if (map.ui.selected) {
+ const { coordinatesWithinExtent } = areCoordinatesWithinExtent(map, config, coordinates);
+ if (!coordinatesWithinExtent) {
+ return;
+ }
+ }
+ return coordinates;
+ },
+ },
+ },
};
};
diff --git a/web/js/map/ui.js b/web/js/map/ui.js
index b6b0758bb..6648c30df 100644
--- a/web/js/map/ui.js
+++ b/web/js/map/ui.js
@@ -34,6 +34,7 @@ import { mapUtilZoomAction, getActiveLayerGroup } from './util';
import mapCompare from './compare/compare';
import { LOCATION_POP_ACTION } from '../redux-location-state-customs';
import { CHANGE_PROJECTION } from '../modules/projection/constants';
+import { UPDATE_ACTIVE_MARKER } from '../modules/geosearch/constants';
import { SELECT_DATE } from '../modules/date/constants';
import util from '../util/util';
import * as layerConstants from '../modules/layers/constants';
@@ -54,6 +55,7 @@ import { getLeadingExtent } from '../modules/map/util';
import { updateVectorSelection } from '../modules/vector-styles/util';
import { faIconPlusSVGDomEl, faIconMinusSVGDomEl } from './fa-map-icons';
import { hasVectorLayers } from '../modules/layers/util';
+import { addCoordinatesMarker, reverseGeocode } from '../modules/geosearch/selectors';
export default function mapui(models, config, store, ui) {
const id = 'wv-map';
@@ -196,6 +198,19 @@ export default function mapui(models, config, store, ui) {
updateProjection(true);
};
+ // add map coordinate marker
+ const addMapMarker = () => {
+ const state = store.getState();
+ const { geosearch } = state;
+ const { activeMarker, coordinates } = geosearch;
+ if (coordinates && coordinates.length > 0) {
+ reverseGeocode(coordinates).then((results) => {
+ const marker = addCoordinatesMarker(activeMarker, config, { ui: self }, coordinates, results);
+ store.dispatch({ type: UPDATE_ACTIVE_MARKER, value: marker });
+ });
+ }
+ };
+
const flyToNewExtent = function(extent, rotation) {
const coordinateX = extent[0] + (extent[2] - extent[0]) / 2;
const coordinateY = extent[1] + (extent[3] - extent[1]) / 2;
@@ -288,6 +303,7 @@ export default function mapui(models, config, store, ui) {
}
updateExtent();
onResize();
+ addMapMarker();
}
/*
* When page is resised set for mobile or desktop
diff --git a/web/js/modules/combine-reducers.js b/web/js/modules/combine-reducers.js
index 9f2c3ec69..226c2e10a 100644
--- a/web/js/modules/combine-reducers.js
+++ b/web/js/modules/combine-reducers.js
@@ -4,6 +4,7 @@ import { get as lodashGet, assign as lodashAssign } from 'lodash';
import { modalReducer, modalAboutPage } from './modal/reducers';
import feedbackReducer from './feedback/reducers';
import projectionReducer from './projection/reducer';
+import geosearchReducer from './geosearch/reducers';
import { shortLink } from './link/reducers';
import {
requestedEvents,
@@ -105,6 +106,7 @@ const reducers = {
modal: modalReducer,
date: dateReducer,
feedback: feedbackReducer,
+ geosearch: geosearchReducer,
notifications: notificationsReducer,
config: defaultReducer,
models: defaultReducer,
diff --git a/web/js/modules/feedback/reducers.js b/web/js/modules/feedback/reducers.js
index 24f0fba20..5fc419bf8 100644
--- a/web/js/modules/feedback/reducers.js
+++ b/web/js/modules/feedback/reducers.js
@@ -5,7 +5,7 @@ const feedbackState = {
isInitiated: false,
};
-export default function projectionReducer(state = feedbackState, action) {
+export default function feedbackReducer(state = feedbackState, action) {
switch (action.type) {
case INIT_FEEDBACK:
return lodashAssign({}, state, {
diff --git a/web/js/modules/geosearch/actions.js b/web/js/modules/geosearch/actions.js
new file mode 100644
index 000000000..c22d4a876
--- /dev/null
+++ b/web/js/modules/geosearch/actions.js
@@ -0,0 +1,88 @@
+
+import {
+ CLEAR_COORDINATES,
+ SELECT_COORDINATES_TO_FLY,
+ TOGGLE_REVERSE_GEOCODE_ACTIVE,
+ TOGGLE_SHOW_GEOSEARCH,
+} from './constants';
+import {
+ addCoordinatesMarker,
+ animateCoordinates,
+ removeCoordinatesMarker,
+} from './selectors';
+import { getMaxZoomLevelLayerCollection } from '../layers/selectors';
+
+export function toggleShowGeosearch() {
+ return (dispatch, getState) => {
+ const state = getState();
+ const { geosearch } = state;
+ const { isExpanded } = geosearch;
+
+ dispatch({
+ type: TOGGLE_SHOW_GEOSEARCH,
+ value: !isExpanded,
+ });
+ };
+}
+
+export function toggleReverseGeocodeActive(isCoordinateSearchActive) {
+ return {
+ type: TOGGLE_REVERSE_GEOCODE_ACTIVE,
+ value: isCoordinateSearchActive,
+ };
+}
+
+export function selectCoordinatesToFly(coordinates, reverseGeocodeResults) {
+ return (dispatch, getState) => {
+ const state = getState();
+ const {
+ config, geosearch, map, layers, proj,
+ } = state;
+ const { sources } = config;
+ const { active } = layers;
+ const { activeMarker } = geosearch;
+
+ if (reverseGeocodeResults) {
+ const { error } = reverseGeocodeResults;
+ if (error) {
+ console.log('ERROR REVERSE GEOCODING - Typically, the coordinates are not geocoding with data.', error);
+ }
+ }
+
+ const marker = addCoordinatesMarker(activeMarker, config, map, coordinates, reverseGeocodeResults);
+ if (!marker) {
+ console.log('ERROR ADDING MARKER - Coordinates are outside range of current map projection extent.');
+ dispatch({
+ type: SELECT_COORDINATES_TO_FLY,
+ value: false,
+ coordinates,
+ activeMarker: null,
+ });
+ }
+ const zoom = map.ui.selected.getView().getZoom();
+ const activeLayers = active.filter((layer) => layer.projections[proj.id] !== undefined);
+ const maxZoom = getMaxZoomLevelLayerCollection(activeLayers, zoom, proj.id, sources);
+
+ animateCoordinates(map, coordinates, maxZoom);
+
+ dispatch({
+ type: SELECT_COORDINATES_TO_FLY,
+ value: false,
+ coordinates,
+ activeMarker: marker,
+ });
+ };
+}
+
+export function clearCoordinates() {
+ return (dispatch, getState) => {
+ const state = getState();
+ const { map, geosearch } = state;
+ const { activeMarker } = geosearch;
+
+ removeCoordinatesMarker(activeMarker, map);
+ dispatch({
+ type: CLEAR_COORDINATES,
+ });
+ };
+}
diff --git a/web/js/modules/geosearch/constants.js b/web/js/modules/geosearch/constants.js
new file mode 100644
index 000000000..73a82b060
--- /dev/null
+++ b/web/js/modules/geosearch/constants.js
@@ -0,0 +1,5 @@
+export const CLEAR_COORDINATES = 'GEOSEARCH/CLEAR_COORDINATES';
+export const SELECT_COORDINATES_TO_FLY = 'GEOSEARCH/SELECT_COORDINATES_TO_FLY';
+export const TOGGLE_REVERSE_GEOCODE_ACTIVE = 'GEOSEARCH/TOGGLE_REVERSE_GEOCODE_ACTIVE';
+export const TOGGLE_SHOW_GEOSEARCH = 'GEOSEARCH/TOGGLE_SHOW_GEOSEARCH';
+export const UPDATE_ACTIVE_MARKER = 'GEOSEARCH/UPDATE_ACTIVE_MARKER';
diff --git a/web/js/modules/geosearch/reducers.js b/web/js/modules/geosearch/reducers.js
new file mode 100644
index 000000000..d82a03a6c
--- /dev/null
+++ b/web/js/modules/geosearch/reducers.js
@@ -0,0 +1,45 @@
+import { assign as lodashAssign } from 'lodash';
+import {
+ CLEAR_COORDINATES,
+ SELECT_COORDINATES_TO_FLY,
+ TOGGLE_REVERSE_GEOCODE_ACTIVE,
+ TOGGLE_SHOW_GEOSEARCH,
+ UPDATE_ACTIVE_MARKER,
+} from './constants';
+
+const geosearchState = {
+ isCoordinateSearchActive: false,
+ isExpanded: true,
+ coordinates: [],
+ activeMarker: null,
+};
+
+export default function geosearchReducer(state = geosearchState, action) {
+ switch (action.type) {
+ case UPDATE_ACTIVE_MARKER:
+ return lodashAssign({}, state, {
+ activeMarker: action.value,
+ });
+ case TOGGLE_SHOW_GEOSEARCH:
+ return lodashAssign({}, state, {
+ isExpanded: action.value,
+ });
+ case SELECT_COORDINATES_TO_FLY:
+ return lodashAssign({}, state, {
+ isCoordinateSearchActive: action.value,
+ coordinates: action.coordinates,
+ activeMarker: action.activeMarker,
+ });
+ case CLEAR_COORDINATES:
+ return lodashAssign({}, state, {
+ coordinates: [],
+ activeMarker: null,
+ });
+ case TOGGLE_REVERSE_GEOCODE_ACTIVE:
+ return lodashAssign({}, state, {
+ isCoordinateSearchActive: action.value,
+ });
+ default:
+ return state;
+ }
+}
diff --git a/web/js/modules/geosearch/selectors.js b/web/js/modules/geosearch/selectors.js
new file mode 100644
index 000000000..51daf3a23
--- /dev/null
+++ b/web/js/modules/geosearch/selectors.js
@@ -0,0 +1,156 @@
+import OlPoint from 'ol/geom/Point';
+import { Icon, Style } from 'ol/style';
+import OlFeature from 'ol/Feature';
+import OlLayerVector from 'ol/layer/Vector';
+import OlSourceVector from 'ol/source/Vector';
+import * as olProj from 'ol/proj';
+import { containsXY } from 'ol/extent';
+
+export function animateCoordinates(map, coordinates, zoom) {
+ const { ui } = map;
+ const { proj } = ui.selected;
+ let targetCoordinates = coordinates;
+ if (proj !== 'geographic') {
+ targetCoordinates = polarCoordinatesTransform(coordinates, proj);
+ }
+ ui.animate.fly(targetCoordinates, zoom);
+}
+
+function polarCoordinatesTransform(coordinates, proj) {
+ const projObj = {
+ arctic: 'EPSG:3413',
+ antarctic: 'EPSG:3031',
+ };
+ return olProj.transform(coordinates, 'EPSG:4326', projObj[proj]);
+}
+
+export function areCoordinatesWithinExtent(map, config, coordinates) {
+ const { projections } = config;
+ const { selected } = map.ui;
+ const projMaxExtent = projections[selected.proj].maxExtent;
+
+ let coordinatesWithinExtent;
+ let transformedCoordinates;
+ if (selected.proj !== 'geographic') {
+ transformedCoordinates = polarCoordinatesTransform(coordinates, selected.proj);
+ coordinatesWithinExtent = containsXY(projMaxExtent, transformedCoordinates[0], transformedCoordinates[1]);
+ } else {
+ coordinatesWithinExtent = containsXY(projMaxExtent, coordinates[0], coordinates[1]);
+ }
+ return {
+ coordinatesWithinExtent,
+ transformedCoordinates,
+ };
+}
+
+export function addCoordinatesMarker(activeMarker, config, map, coordinates, reverseGeocodeResults) {
+ const { selected } = map.ui;
+
+ removeCoordinatesMarker(activeMarker, map);
+
+ const { coordinatesWithinExtent, transformedCoordinates } = areCoordinatesWithinExtent(map, config, coordinates);
+ if (!coordinatesWithinExtent) {
+ return false;
+ }
+
+ const marker = createPin(coordinates, transformedCoordinates, reverseGeocodeResults, 'testerMarker', true);
+ selected.addLayer(marker);
+ selected.renderSync();
+ return marker;
+}
+
+export function removeCoordinatesMarker(activeMarker, map) {
+ const { selected } = map.ui;
+ if (activeMarker) {
+ activeMarker.setMap(null);
+ selected.removeLayer(activeMarker);
+ }
+}
+
+const createPin = function(coordinates, transformedCoordinates = false, reverseGeocodeResults = {}, id, isSelected, category = { slug: 'test', title: 'cat' }, title) {
+ const overlayEl = document.createElement('div');
+ const icon = document.createElement('i');
+ overlayEl.className = 'marker';
+ if (isSelected) overlayEl.classList.add('marker-selected');
+ icon.className = `event-icon event-icon-${category.slug}`;
+ icon.title = title || category.title;
+ overlayEl.appendChild(icon);
+
+ const [longitude, latitude] = coordinates;
+ const iconFeature = new OlFeature({
+ geometry: new OlPoint(transformedCoordinates || coordinates),
+ reverseGeocodeResults,
+ latitude,
+ longitude,
+ population: 4000,
+ rainfall: 500,
+ });
+
+ const iconStyle = new Style({
+ image: new Icon({
+ anchorOrigin: 'bottom-left',
+ anchorXUnits: 'fraction',
+ anchorYUnits: 'pixels',
+ scale: 0.5,
+ src: 'images/map-pin.png',
+ }),
+ });
+
+ iconFeature.setStyle(iconStyle);
+ iconFeature.setId('coordinates-map-maker');
+ const vectorSource = new OlSourceVector({
+ wrapX: false,
+ features: [iconFeature],
+ });
+
+ const vectorLayer = new OlLayerVector({
+ source: vectorSource,
+ });
+
+ return vectorLayer;
+};
+
+const GEOCODE_OPTIONS = {
+ urlBase: 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/',
+ requestOptions: {
+ method: 'GET',
+ redirect: 'follow',
+ },
+};
+
+export async function suggest(val) {
+ const { requestOptions, urlBase } = GEOCODE_OPTIONS;
+
+ try {
+ const response = await fetch(`${urlBase}suggest?text=${val}&f=json`, requestOptions);
+ const result = await response.text();
+ return JSON.parse(result);
+ } catch (error) {
+ return console.log('error', error);
+ }
+}
+
+export async function processMagicKey(magicKey) {
+ const { requestOptions, urlBase } = GEOCODE_OPTIONS;
+
+ try {
+ const response = await fetch(`${urlBase}findAddressCandidates?f=json&magicKey=${magicKey}=`, requestOptions);
+ const result = await response.text();
+ return JSON.parse(result);
+ } catch (error) {
+ return console.log('error', error);
+ }
+}
+
+export async function reverseGeocode(coordinates) {
+ const { requestOptions, urlBase } = GEOCODE_OPTIONS;
+ console.log(`${urlBase}reverseGeocode?location=${coordinates}&f=json`);
+ try {
+ const response = await fetch(`${urlBase}reverseGeocode?location=${coordinates}&f=json`, requestOptions);
+
+ const result = await response.text();
+ return JSON.parse(result);
+ } catch (error) {
+ return console.log('error', error);
+ }
+}
diff --git a/web/js/modules/geosearch/util.js b/web/js/modules/geosearch/util.js
new file mode 100644
index 000000000..e97ef3ead
--- /dev/null
+++ b/web/js/modules/geosearch/util.js
@@ -0,0 +1,21 @@
+import update from 'immutability-helper';
+
+/**
+ *
+ * @param {*} parameters
+ * @param {*} stateFromLocation
+ */
+export default function mapLocationToGeosearchState(
+ parameters,
+ stateFromLocation,
+) {
+ if (parameters.marker) {
+ stateFromLocation = update(stateFromLocation, {
+ geosearch: {
+ coordinates: { $set: parameters.marker.split(',') },
+ },
+ });
+ }
+
+ return stateFromLocation;
+}
diff --git a/web/js/modules/layers/selectors.js b/web/js/modules/layers/selectors.js
index 23b82070f..571ad7cc1 100644
--- a/web/js/modules/layers/selectors.js
+++ b/web/js/modules/layers/selectors.js
@@ -525,3 +525,18 @@ function getZoomLevel(layer, zoom, proj, sources) {
}
return null;
}
+
+export function getMaxZoomLevelLayerCollection(layers, zoom, proj, sources) {
+ const zoomOffset = proj === 'arctic' || proj === 'antarctic' ? 1 : 0;
+ let maxZoom = zoom;
+
+ lodashEach(layers, (layer) => {
+ const { matrixSet } = layer.projections[proj];
+ if (matrixSet !== undefined && layer.type !== 'vector') {
+ const { source } = layer.projections[proj];
+ const zoomLimit = sources[source].matrixSets[matrixSet].resolutions.length - 1 + zoomOffset;
+ maxZoom = Math.max(maxZoom, zoomLimit);
+ }
+ });
+ return maxZoom;
+}
diff --git a/web/js/modules/vector-styles/util.js b/web/js/modules/vector-styles/util.js
index 3665bd5a2..bc23933b1 100644
--- a/web/js/modules/vector-styles/util.js
+++ b/web/js/modules/vector-styles/util.js
@@ -217,8 +217,73 @@ function getModalOffset(dimensionProps) {
function getModalContentsAtPixel(mapProps, config, compareState) {
const metaArray = [];
const selected = {};
+ let isCoordinatesMarker = false;
const { pixels, map, swipeOffset } = mapProps;
map.forEachFeatureAtPixel(pixels, (feature, layer) => {
+ const featureId = feature.getId();
+ if (featureId === 'coordinates-map-maker') {
+ const featureProperties = feature.getProperties();
+ selected.COORDS = ['COORDS TEST1'];
+
+ const { latitude, longitude, reverseGeocodeResults } = featureProperties;
+ const { address, error } = reverseGeocodeResults;
+
+ let title;
+ if (error) {
+ title = `${latitude}, ${longitude}`;
+ } else if (address) {
+ const { Match_addr } = address;
+ title = Match_addr;
+ }
+
+ const obj = {
+ legend: [
+ // {
+ // DataType: 'string',
+ // Description: 'Name of Nuclear Plant',
+ // Function: 'Identify',
+ // Identifier: 'Plant',
+ // IsLabel: true,
+ // IsOptional: false,
+ // Title: 'Plant Site Name',
+ // },
+ {
+ DataType: 'float',
+ Description: 'Latitude in Decimal Degrees',
+ Function: 'Describe',
+ Identifier: 'Latitude',
+ IsLabel: false,
+ IsOptional: false,
+ Title: 'Latitude',
+ Units: '°',
+ },
+ {
+ DataType: 'float',
+ Description: 'Longitude in Decimal Degrees',
+ Function: 'Describe',
+ Identifier: 'Longitude',
+ IsLabel: false,
+ IsOptional: false,
+ Title: 'Longitude',
+ Units: '°',
+ },
+ ],
+ features: {
+ // Plant: 'TEST FEATURES Plant',
+ Latitude: latitude,
+ Longitude: longitude,
+ },
+ id: 'TEST coords id',
+ title,
+ subTitle: 'TEST SUBTITLE',
+ featureTitle: title,
+
+ };
+ metaArray.push(obj);
+ isCoordinatesMarker = true;
+ return { selected, metaArray, isCoordinatesMarker };
+ }
+
const def = lodashGet(layer, 'wv.def');
if (!def) {
return;
@@ -257,7 +322,8 @@ function getModalContentsAtPixel(mapProps, config, compareState) {
selected[layerId].push(uniqueIdentifier);
}
});
- return { selected, metaArray };
+ console.log(selected, metaArray);
+ return { selected, metaArray, isCoordinatesMarker };
}
/**
* Get organized vector modal contents for clicked
@@ -281,12 +347,13 @@ export function onMapClickGetVectorFeatures(pixels, map, state, swipeOffset) {
};
const mapProps = { pixels, map, swipeOffset };
const { offsetLeft, offsetTop } = getModalOffset(modalOffsetProps);
- const { selected, metaArray } = getModalContentsAtPixel(mapProps, config, compare);
+ const { selected, metaArray, isCoordinatesMarker } = getModalContentsAtPixel(mapProps, config, compare);
return {
selected, // Object containing unique identifiers of selected features
metaArray, // Organized metadata for modal
offsetLeft, // Modal default offsetLeft
offsetTop, // Modal default offsetTop
+ isCoordinatesMarker,
};
}
export function updateVectorSelection(selectionObj, lastSelection, layers, type, state) {
diff --git a/web/js/util/local-storage.js b/web/js/util/local-storage.js
index de6340bfd..e9f8a6b9b 100644
--- a/web/js/util/local-storage.js
+++ b/web/js/util/local-storage.js
@@ -19,6 +19,7 @@ export default {
enabled,
keys: {
RECENT_LAYERS: 'recentLayers',
+ SEARCH_TOKEN: 'searchToken',
DISMISSED_EVENT_VIS_ALERT: 'dismissedEventVisibilityAlert',
DISMISSED_COMPARE_ALERT: 'dismissedCompareAlert',
HIDE_TOUR: 'hideTour',