Skip to content

Interactive interface for browsing global, full-resolution satellite imagery

add input alert icon and alert component for no suggested places from search

Ed Platod31015898e77
diff --git a/e2e/features/geosearch/geosearch-test.js b/e2e/features/geosearch/geosearch-test.js
index c9b0c4bf9..5138bd080 100644
--- a/e2e/features/geosearch/geosearch-test.js
+++ b/e2e/features/geosearch/geosearch-test.js
@@ -1,8 +1,8 @@
const reuseables = require('../../reuseables/skip-tour.js');
const localSelectors = require('../../reuseables/selectors.js');
-// encoded id; originally coordinates-map-marker_38.89037,-77.03196
-const testMarkerEncodedID = '.coordinates-map-marker_38__2E__89037__2C__-77__2E__03196';
+// encoded id; originally coordinates-map-marker_38.8904,-77.032
+const testMarkerEncodedID = '.coordinates-map-marker_38__2E__8904__2C__-77__2E__032';
const testMarkerNoDetailsEncodedID = '.coordinates-map-marker_5__2C__-51__2E__5';
const TIME_LIMIT = 10000;
@@ -13,6 +13,9 @@ const {
tooltipCoordinatesContainer,
tooltipCoordinatesTitle,
tooltipCoordinates,
+ tooltipCoordinatesMinimizeButton,
+ tooltipCoordinatesCloseButton,
+ coordinatesMapMarker,
} = localSelectors;
module.exports = {
@@ -40,7 +43,7 @@ module.exports = {
c.expect.element(geosearchComponent).to.be.present;
},
'Coordinates dialog for permalink marker is visible by default on page load': (c) => {
- c.url(`${c.globals.url}?v=-176.3167432493038,-16.70650759975561,-16.988618249303812,108.30938074294103&marker=-77.03196,38.89037`);
+ c.url(`${c.globals.url}?v=-176.3167432493038,-16.70650759975561,-16.988618249303812,108.30938074294103&marker=-77.032,38.8904`);
c.waitForElementVisible(tooltipCoordinatesContainer, TIME_LIMIT);
c.expect.element(testMarkerEncodedID).to.be.present;
},
@@ -49,7 +52,7 @@ module.exports = {
c.assert.containsText(tooltipCoordinates, '38.8904°, -77.0320°');
},
'Clicking minimize tooltip hides the coordinates dialog': (c) => {
- c.click('.minimize-coordinates-tooltip');
+ c.click(tooltipCoordinatesMinimizeButton);
c.pause(500);
c.expect.element(tooltipCoordinatesContainer).to.not.be.present;
},
@@ -60,6 +63,17 @@ module.exports = {
c.assert.containsText(tooltipCoordinatesTitle, '5.0000°, -51.5000°');
c.assert.containsText(tooltipCoordinates, '5.0000°, -51.5000°');
},
+ 'Clicking close tooltip removes the marker and coordinates dialog': (c) => {
+ c.click(tooltipCoordinatesCloseButton);
+ c.pause(500);
+ c.expect.element(coordinatesMapMarker).to.not.be.present;
+ c.assert.not.urlContains('marker');
+ },
+ 'Invalid marker query string parameter prevents state update': (c) => {
+ c.url(`${c.globals.url}?marker=-51.5,invalidtext`);
+ c.expect.element(coordinatesMapMarker).to.not.be.present;
+ c.assert.not.urlContains('marker');
+ },
after(c) {
c.end();
},
diff --git a/e2e/reuseables/selectors.js b/e2e/reuseables/selectors.js
index c2a0f8605..13692b85b 100644
--- a/e2e/reuseables/selectors.js
+++ b/e2e/reuseables/selectors.js
@@ -131,4 +131,7 @@ module.exports = {
tooltipCoordinatesContainer: '.tooltip-coordinates-container',
tooltipCoordinatesTitle: '.tooltip-coordinates-title',
tooltipCoordinates: '.tooltip-coordinates',
+ tooltipCoordinatesMinimizeButton: '.minimize-coordinates-tooltip',
+ tooltipCoordinatesCloseButton: '.close-coordinates-tooltip',
+ coordinatesMapMarker: '.coordinates-map-marker',
};
diff --git a/web/css/geosearch.css b/web/css/geosearch.css
index aa6529e02..6c29c1e37 100644
--- a/web/css/geosearch.css
+++ b/web/css/geosearch.css
@@ -13,6 +13,13 @@
}
}
+.geosearch-autocomplete,
+.geosearch-autocomplete:focus {
+ background: none;
+ color: #fff;
+ box-shadow: none;
+}
+
.geosearch-results-menu {
position: absolute;
width: 85%;
@@ -28,7 +35,7 @@
}
/* Autocomplete Input Submit Button */
-.geosearch-submit-input-group-addon {
+.geosearch-input-group-addon {
height: 38px;
position: absolute;
top: 0;
@@ -40,6 +47,7 @@
background: none;
border: none;
color: #999;
+ margin-right: 2px;
border-left: 2px solid rgba(51, 51, 51, 0.65);
border-radius: 0;
box-sizing: border-box;
@@ -55,6 +63,9 @@
top: 13px;
}
}
+ &.submit-group {
+ right: 31px;
+ }
& .geosearch-search-clear-button {
cursor: pointer;
color: #fff;
@@ -89,7 +100,7 @@
}
/* Geosearch Component Coordinate Buttons */
-.geosearch-coordinate-button-addpoint {
+.geosearch-add-coordinate-button {
border-radius: 0;
border-top-right-radius: 5px;
border-bottom-right-radius: 5px;
@@ -143,13 +154,6 @@
}
/* Additional Styling */
-.dark-input,
-.dark-input:focus {
- background: none;
- color: #fff;
- box-shadow: none;
-}
-
.geosearch-input-alert-icon {
right: 120px;
}
@@ -187,11 +191,14 @@
line-height: 16px;
font-size: 16px;
}
- .geosearch-submit-input-group-addon {
+ .geosearch-input-group-addon {
margin-right: 6px;
background: none;
& .geosearch-search-submit-button {
border-left: none;
}
+ & .geosearch-search-clear-button {
+ background: #3b3b3b;
+ }
}
}
diff --git a/web/js/components/geosearch/coordinates-dialog.js b/web/js/components/geosearch/coordinates-dialog.js
index ca9129f4f..7643f527f 100644
--- a/web/js/components/geosearch/coordinates-dialog.js
+++ b/web/js/components/geosearch/coordinates-dialog.js
@@ -55,7 +55,7 @@ class CoordinatesDialog extends Component {
const tooltipVisibilityCondition = !isMobile && showTooltips;
return (
<>
- <span id={closeButtonId} className="close-tooltip close-coordinates-tooltip">
+ <span id={closeButtonId} className={`close-tooltip ${closeButtonId}`}>
{tooltipVisibilityCondition
&& (
<UncontrolledTooltip
@@ -69,7 +69,7 @@ class CoordinatesDialog extends Component {
)}
<FontAwesomeIcon onClick={this.clearCoordinates} icon="times" fixedWidth />
</span>
- <span id={minimizeButtonId} className="minimize-tooltip minimize-coordinates-tooltip">
+ <span id={minimizeButtonId} className={`minimize-tooltip ${minimizeButtonId}`}>
{tooltipVisibilityCondition
&& (
<UncontrolledTooltip
@@ -102,7 +102,7 @@ class CoordinatesDialog extends Component {
>
<div
id={buttonId}
- className="copy-coordinates-to-clipboard-button"
+ className={buttonId}
>
{!isMobile && (
<UncontrolledTooltip placement="bottom" trigger="hover" target={buttonId}>
@@ -122,7 +122,6 @@ class CoordinatesDialog extends Component {
const {
tooltipToggleTime,
} = this.state;
-
const {
coordinates,
title,
diff --git a/web/js/components/geosearch/copy-tooltip.js b/web/js/components/geosearch/copy-tooltip.js
index dca137b95..6367ef8f5 100644
--- a/web/js/components/geosearch/copy-tooltip.js
+++ b/web/js/components/geosearch/copy-tooltip.js
@@ -1,9 +1,7 @@
/* eslint-disable react/destructuring-assignment */
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
-import {
- Tooltip,
-} from 'reactstrap';
+import { Tooltip } from 'reactstrap';
/*
* @class CopyClipboardTooltip
diff --git a/web/js/components/geosearch/geosearch-input.js b/web/js/components/geosearch/geosearch-input.js
index 2c833b56a..af6de2a9e 100644
--- a/web/js/components/geosearch/geosearch-input.js
+++ b/web/js/components/geosearch/geosearch-input.js
@@ -49,7 +49,6 @@ class SearchBox extends Component {
if (entered) {
e.preventDefault();
e.stopPropagation();
-
if (coordinatesPending.length > 0) {
onCoordinateInputSelect();
}
@@ -89,7 +88,6 @@ class SearchBox extends Component {
} = this.props;
const buttonId = 'geosearch-search-submit-button';
const labelText = 'Submit and navigate to location';
- const rightPositioning = '31px';
const buttonStyle = inputValue
? { background: isMobile ? '#d54e21' : 'none', color: isMobile ? '#fff' : '#d54e21', cursor: 'pointer' }
: {};
@@ -97,18 +95,15 @@ class SearchBox extends Component {
return (
<InputGroupAddon
- className="geosearch-submit-input-group-addon"
+ className="geosearch-input-group-addon submit-group"
addonType="prepend"
- style={{
- right: rightPositioning,
- }}
>
<Button
id={buttonId}
style={buttonStyle}
disabled={!inputValue}
onClick={this.handleSubmitClick}
- className="geosearch-search-submit-button"
+ className={buttonId}
>
{tooltipVisibilityCondition && (
<UncontrolledTooltip
@@ -129,15 +124,15 @@ class SearchBox extends Component {
// render alert icon
renderAlertIcon = () => {
const {
- showExtentAlert,
+ activeAlert,
} = this.props;
return (
- showExtentAlert && (
+ activeAlert && (
<InputGroupAddon
- className="geosearch-submit-input-group-addon geosearch-input-alert-icon"
+ className="geosearch-input-group-addon geosearch-input-alert-icon"
addonType="append"
- title="The entered location is outside of the current map extent."
+ title="The entered location is not avaialable."
>
<FontAwesomeIcon icon="exclamation-triangle" size="1x" />
</InputGroupAddon>
@@ -157,13 +152,13 @@ class SearchBox extends Component {
return (
inputValue && (
<InputGroupAddon
- className="geosearch-submit-input-group-addon geosearch-input-clear-container"
+ className="geosearch-input-group-addon geosearch-input-clear-container"
addonType="append"
>
<Button
id={buttonId}
onClick={clearInput}
- className="geosearch-search-clear-button"
+ className={buttonId}
>
{tooltipVisibilityCondition && (
<UncontrolledTooltip
@@ -187,12 +182,12 @@ class SearchBox extends Component {
const {
inputValue,
isMobile,
- showExtentAlert,
+ activeAlert,
} = this.props;
// handle mobile/desktop input padding with/without alert
const paddingRightStyle = inputValue
- ? showExtentAlert
+ ? activeAlert
? isMobile ? '68px' : '84px'
: isMobile ? '42px' : '60px'
: '0';
@@ -223,7 +218,7 @@ class SearchBox extends Component {
<Autocomplete
ref={(el) => { this.geosearchInput = el; }}
inputProps={{
- className: 'form-control geosearch-autocomplete dark-input',
+ className: 'form-control geosearch-autocomplete',
id: 'geosearch-autocomplete',
placeholder: placeHolderText,
}}
@@ -245,6 +240,7 @@ class SearchBox extends Component {
}
SearchBox.propTypes = {
+ activeAlert: PropTypes.bool,
clearInput: PropTypes.func,
coordinatesPending: PropTypes.array,
geosearchMobileModalOpen: PropTypes.bool,
@@ -254,7 +250,6 @@ SearchBox.propTypes = {
onChange: PropTypes.func,
onCoordinateInputSelect: PropTypes.func,
onSelect: PropTypes.func,
- showExtentAlert: PropTypes.bool,
suggestions: PropTypes.array,
};
diff --git a/web/js/components/geosearch/geosearch-modal.js b/web/js/components/geosearch/geosearch-modal.js
index 803a053c0..6e9992c16 100644
--- a/web/js/components/geosearch/geosearch-modal.js
+++ b/web/js/components/geosearch/geosearch-modal.js
@@ -1,5 +1,6 @@
import PropTypes from 'prop-types';
import React, { Component } from 'react';
+import { connect } from 'react-redux';
import {
Button, InputGroup, InputGroupAddon, UncontrolledTooltip,
} from 'reactstrap';
@@ -11,35 +12,63 @@ import googleTagManager from 'googleTagManager';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import SearchBox from './geosearch-input';
import Alert from '../util/alert';
-import isValidCoordinates from './util';
+import { getCoordinateFixedPrecision, isValidCoordinates } from './util';
+import {
+ clearSuggestions,
+ selectCoordinatesToFly,
+ toggleShowGeosearch,
+ toggleReverseGeocodeActive,
+ setSuggestion,
+ getSuggestions,
+} from '../../modules/geosearch/actions';
+import {
+ areCoordinatesWithinExtent,
+} from '../../modules/geosearch/util';
+import {
+ processMagicKey,
+ reverseGeocode,
+} from '../../modules/geosearch/util-api';
class GeosearchModal extends Component {
constructor(props) {
super(props);
this.state = {
isTouchDevice: false,
+ showInputAlert: false,
showExtentAlert: false,
showReverseGeocodeAlert: false,
+ showNoSuggestionsAlert: false,
};
- this.throttlegetSuggestions = lodashThrottle(this.getSuggestions, 400, { leading: true, trailing: true });
+ this.throttleGetSuggestions = lodashThrottle(this.getSuggestions, 400, { leading: true, trailing: true });
}
componentDidUpdate(prevProps) {
- const { coordinates, isCoordinateSearchActive } = this.props;
- const { showExtentAlert, showReverseGeocodeAlert } = this.state;
+ const {
+ coordinates, inputValue, isCoordinateSearchActive, suggestions,
+ } = this.props;
+ const {
+ showExtentAlert, showInputAlert, showReverseGeocodeAlert, showNoSuggestionsAlert,
+ } = this.state;
if ((showReverseGeocodeAlert || showExtentAlert) && coordinates.length > 0) {
const [prevLong, prevLat] = prevProps.coordinates;
const [long, lat] = coordinates;
if (prevLong !== long || prevLat !== lat) {
- this.dismissReverseGeocodeAlert();
- this.setExtentAlert(false);
+ this.clearAlerts();
}
}
// clear geocode click instruction alert if search no longer active
if (!isCoordinateSearchActive && prevProps.isCoordinateSearchActive) {
this.dismissReverseGeocodeAlert();
}
+ // handle add/remove no suggestion alert based on inputValue and suggestions
+ if (inputValue && suggestions.length === 0 && prevProps.suggestions.length > 0) {
+ this.setNoSuggestionsAlert(true);
+ this.setInputAlertIcon(true);
+ } else if ((showNoSuggestionsAlert || showInputAlert) && (!inputValue || suggestions.length > 0)) {
+ this.setNoSuggestionsAlert(false);
+ this.setInputAlertIcon(false);
+ }
}
// suggest place with text input to get place suggestions
@@ -54,6 +83,22 @@ class GeosearchModal extends Component {
// set extent message error alert
setExtentAlert = (shouldShow) => this.setState({ showExtentAlert: shouldShow });
+ // set no suggested places message error alert
+ setNoSuggestionsAlert = (shouldShow) => this.setState({ showNoSuggestionsAlert: shouldShow });
+
+ // set input alert icon
+ setInputAlertIcon = (shouldShow) => this.setState({ showInputAlert: shouldShow });
+
+ // clear all alerts
+ clearAlerts = () => {
+ this.setState({
+ showInputAlert: false,
+ showExtentAlert: false,
+ showNoSuggestionsAlert: false,
+ showReverseGeocodeAlert: false,
+ });
+ }
+
// handle submitting search after inputing coordinates
onCoordinateInputSelect = () => {
const {
@@ -69,12 +114,13 @@ class GeosearchModal extends Component {
const coordinatesWithinExtent = isCoordinatePairWithinExtent(coordinatesPending);
if (coordinatesWithinExtent === false) {
this.setExtentAlert(true);
+ this.setInputAlertIcon(true);
} else {
const [longitude, latitude] = coordinatesPending;
reverseGeocode([longitude, latitude]).then((results) => {
selectCoordinatesToFly([longitude, latitude], results);
});
- this.setExtentAlert(false);
+ this.clearAlerts();
updateValue('');
clearSuggestions();
updatePendingCoordinates([]);
@@ -106,12 +152,13 @@ class GeosearchModal extends Component {
const addressAttributes = { address: attributes };
const { x, y } = location;
- const parsedX = parseFloat(x.toPrecision(9));
- const parsedY = parseFloat(y.toPrecision(9));
+ const parsedX = getCoordinateFixedPrecision(x);
+ const parsedY = getCoordinateFixedPrecision(y);
const coordinatesWithinExtent = isCoordinatePairWithinExtent([parsedX, parsedY]);
if (coordinatesWithinExtent === false) {
this.setExtentAlert(true);
+ this.setInputAlertIcon(true);
} else {
selectCoordinatesToFly([parsedX, parsedY], addressAttributes);
}
@@ -132,18 +179,18 @@ class GeosearchModal extends Component {
// check for coordinate value
const coordinatesInputValue = isValidCoordinates(value);
if (coordinatesInputValue) {
- this.throttlegetSuggestions.cancel();
+ this.throttleGetSuggestions.cancel();
const { latitude, longitude } = coordinatesInputValue;
- this.setExtentAlert(false);
+ this.clearAlerts();
clearSuggestions();
updatePendingCoordinates([longitude, latitude]);
} else if (!value) {
// clear on empty input
- this.throttlegetSuggestions.cancel();
+ this.throttleGetSuggestions.cancel();
clearSuggestions();
} else {
// provide suggestions to populate search result menu item(s)
- this.throttlegetSuggestions(value);
+ this.throttleGetSuggestions(value);
}
}
@@ -155,10 +202,7 @@ class GeosearchModal extends Component {
} = this.props;
updateValue('');
clearSuggestions();
- this.setState({
- showReverseGeocodeAlert: false,
- showExtentAlert: false,
- });
+ this.clearAlerts();
}
// initiate instruction alert and activate store level toggleReverseGeocodeActive
@@ -171,6 +215,8 @@ class GeosearchModal extends Component {
isTouchDevice,
showReverseGeocodeAlert: true,
showExtentAlert: false,
+ showNoSuggestionsAlert: false,
+ showInputAlert: false,
});
updateValue('');
googleTagManager.pushEvent({
@@ -226,13 +272,32 @@ class GeosearchModal extends Component {
id="geosearch-select-coordinates-extent-alert"
isOpen
title="Selected Coordinates Outside Current Map Projection"
- timeout={15000}
+ timeout={12000}
message={message}
onDismiss={() => this.setExtentAlert(false)}
/>
);
}
+ // render alert message to indicate no suggestions for input value
+ renderNoSuggestionsAlert = () => {
+ const {
+ showNoSuggestionsAlert,
+ } = this.state;
+ const message = 'No suggested places available. Check your text or try a different place.';
+
+ return showNoSuggestionsAlert && (
+ <Alert
+ id="geosearch-no-suggestions-available-alert"
+ isOpen
+ title="No suggested places are available"
+ timeout={12000}
+ message={message}
+ onDismiss={() => this.setNoSuggestionsAlert(false)}
+ />
+ );
+ }
+
// render geosearch component minimize button (not visible in mobile)
renderMinimizeButton = () => {
const { toggleShowGeosearch } = this.props;
@@ -242,11 +307,11 @@ class GeosearchModal extends Component {
<InputGroupAddon addonType="prepend">
<Button
id={buttonId}
- className="geosearch-search-minimize-button"
+ className={buttonId}
onClick={toggleShowGeosearch}
>
{this.renderTooltip(buttonId, labelText)}
- <div className="geosearch-search-minimize-button-chevron" />
+ <div className={`${buttonId}-chevron`} />
</Button>
</InputGroupAddon>
);
@@ -254,18 +319,18 @@ class GeosearchModal extends Component {
// render add coordinate marker button for reverse geocode
renderAddCoordinateButton = () => {
- const addCoordinateButtonId = 'geosearch-coordinate-button-addpoint';
- const addCoordinateLabelText = 'Add marker on map';
+ const buttonId = 'geosearch-add-coordinate-button';
+ const labelText = 'Add marker on map';
return (
<InputGroupAddon addonType="append">
<Button
- id={addCoordinateButtonId}
+ id={buttonId}
onTouchEnd={this.initReverseGeocode}
onMouseDown={this.initReverseGeocode}
- className="geosearch-coordinate-button-addpoint"
+ className={buttonId}
>
- {this.renderTooltip(addCoordinateButtonId, addCoordinateLabelText)}
+ {this.renderTooltip(buttonId, labelText)}
<FontAwesomeIcon icon="map-marker-alt" size="1x" />
</Button>
</InputGroupAddon>
@@ -274,7 +339,6 @@ class GeosearchModal extends Component {
render() {
const {
- coordinates,
geosearchMobileModalOpen,
isExpanded,
isMobile,
@@ -283,13 +347,14 @@ class GeosearchModal extends Component {
suggestions,
} = this.props;
const {
- showExtentAlert,
+ showInputAlert,
} = this.state;
return (
<>
{/* Alerts */}
{this.renderReverseGeocodeAlert()}
+ {this.renderNoSuggestionsAlert()}
{this.renderExtentAlert()}
<div className="geosearch-component">
<InputGroup className="geosearch-search-input-group">
@@ -297,7 +362,6 @@ class GeosearchModal extends Component {
{!isMobile && this.renderMinimizeButton()}
<SearchBox
clearInput={this.clearInput}
- coordinates={coordinates}
coordinatesPending={coordinatesPending}
geosearchMobileModalOpen={geosearchMobileModalOpen}
inputValue={inputValue}
@@ -306,7 +370,7 @@ class GeosearchModal extends Component {
onChange={this.onChange}
onCoordinateInputSelect={this.onCoordinateInputSelect}
onSelect={this.onSelect}
- showExtentAlert={showExtentAlert}
+ activeAlert={showInputAlert}
suggestions={suggestions}
/>
{/* Add coordinate marker button */}
@@ -318,11 +382,61 @@ class GeosearchModal extends Component {
}
}
+const mapStateToProps = (state) => {
+ const {
+ browser,
+ config,
+ map,
+ modal,
+ geosearch,
+ } = state;
+ const {
+ coordinates, isCoordinateSearchActive, isExpanded, suggestions,
+ } = geosearch;
+ const isMobile = browser.lessThan.medium;
+ const geosearchMobileModalOpen = modal.isOpen && modal.id === 'TOOLBAR_GEOSEARCH_MOBILE';
+ // Collapse when image download, GIF, measure tool, or distraction free mode is active
+
+ return {
+ coordinates,
+ geosearchMobileModalOpen,
+ isCoordinatePairWithinExtent: (targetCoordinates) => areCoordinatesWithinExtent(map, config, targetCoordinates),
+ isCoordinateSearchActive,
+ isExpanded,
+ isMobile,
+ processMagicKey: (magicKey) => processMagicKey(magicKey, config),
+ reverseGeocode: (coords) => reverseGeocode(coords, config),
+ suggestions,
+ };
+};
+
+const mapDispatchToProps = (dispatch) => ({
+ selectCoordinatesToFly: (coordinates, addressAttributes) => {
+ dispatch(selectCoordinatesToFly(coordinates, addressAttributes));
+ },
+ toggleReverseGeocodeActive: (isActive) => {
+ dispatch(toggleReverseGeocodeActive(isActive));
+ },
+ toggleShowGeosearch: () => {
+ dispatch(toggleShowGeosearch());
+ },
+ getSuggestions: (val) => {
+ dispatch(getSuggestions(val));
+ },
+ clearSuggestions: () => {
+ dispatch(clearSuggestions());
+ },
+ setSuggestion: (suggestion) => {
+ dispatch(setSuggestion(suggestion));
+ },
+});
+
GeosearchModal.propTypes = {
clearSuggestions: PropTypes.func,
coordinates: PropTypes.array,
coordinatesPending: PropTypes.array,
geosearchMobileModalOpen: PropTypes.bool,
+ getSuggestions: PropTypes.func,
inputValue: PropTypes.string,
isCoordinatePairWithinExtent: PropTypes.func,
isCoordinateSearchActive: PropTypes.bool,
@@ -333,11 +447,13 @@ GeosearchModal.propTypes = {
selectCoordinatesToFly: PropTypes.func,
setSuggestion: PropTypes.func,
suggestions: PropTypes.array,
- getSuggestions: PropTypes.func,
toggleReverseGeocodeActive: PropTypes.func,
toggleShowGeosearch: PropTypes.func,
updatePendingCoordinates: PropTypes.func,
updateValue: PropTypes.func,
};
-export default GeosearchModal;
+export default connect(
+ mapStateToProps,
+ mapDispatchToProps,
+)(GeosearchModal);
diff --git a/web/js/components/geosearch/geosearch.js b/web/js/components/geosearch/geosearch.js
index c5aec2d78..ed3ee9069 100644
--- a/web/js/components/geosearch/geosearch.js
+++ b/web/js/components/geosearch/geosearch.js
@@ -1,25 +1,9 @@
-import React from 'react';
+import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import GeosearchModal from './geosearch-modal';
-import {
- clearCoordinates,
- clearSuggestions,
- selectCoordinatesToFly,
- toggleShowGeosearch,
- toggleReverseGeocodeActive,
- setSuggestion,
- getSuggestions,
-} from '../../modules/geosearch/actions';
-import {
- areCoordinatesWithinExtent,
-} from '../../modules/geosearch/selectors';
-import {
- processMagicKey,
- reverseGeocode,
-} from '../../modules/geosearch/util';
-class Geosearch extends React.Component {
+class Geosearch extends Component {
constructor(props) {
super(props);
this.state = {
@@ -41,23 +25,7 @@ class Geosearch extends React.Component {
// update array of pending coordinates
updatePendingCoordinates = (coordinatesPending) => this.setState({ coordinatesPending });
- renderSearchComponent = (isMobile) => {
- const {
- clearCoordinates,
- coordinates,
- geosearchMobileModalOpen,
- getSuggestions,
- isCoordinatePairWithinExtent,
- isCoordinateSearchActive,
- isExpanded,
- processMagicKey,
- reverseGeocode,
- selectCoordinatesToFly,
- setSuggestion,
- suggestions,
- toggleReverseGeocodeActive,
- toggleShowGeosearch,
- } = this.props;
+ renderSearchComponent = () => {
const {
coordinatesPending,
inputValue,
@@ -65,23 +33,8 @@ class Geosearch extends React.Component {
return (
<GeosearchModal
- clearCoordinates={clearCoordinates}
- coordinates={coordinates}
coordinatesPending={coordinatesPending}
- geosearchMobileModalOpen={geosearchMobileModalOpen}
- getSuggestions={getSuggestions}
inputValue={inputValue}
- isCoordinatePairWithinExtent={isCoordinatePairWithinExtent}
- isCoordinateSearchActive={isCoordinateSearchActive}
- isExpanded={isExpanded}
- isMobile={isMobile}
- processMagicKey={processMagicKey}
- reverseGeocode={reverseGeocode}
- selectCoordinatesToFly={selectCoordinatesToFly}
- setSuggestion={setSuggestion}
- suggestions={suggestions}
- toggleReverseGeocodeActive={toggleReverseGeocodeActive}
- toggleShowGeosearch={toggleShowGeosearch}
updatePendingCoordinates={this.updatePendingCoordinates}
updateValue={this.updateValue}
/>
@@ -99,12 +52,10 @@ class Geosearch extends React.Component {
return null;
}
- const shouldShowComponent = isExpanded && !shouldCollapseFromOtherUI;
+ const shouldShowComponent = isMobile || (isExpanded && !shouldCollapseFromOtherUI);
return (
<>
- {isMobile
- ? this.renderSearchComponent(true)
- : shouldShowComponent && this.renderSearchComponent(false)}
+ {shouldShowComponent && this.renderSearchComponent()}
</>
);
}
@@ -114,7 +65,6 @@ const mapStateToProps = (state) => {
const {
browser,
config,
- map,
modal,
measure,
animation,
@@ -126,75 +76,30 @@ const mapStateToProps = (state) => {
const { isActive } = measure;
const { gifActive } = animation;
const {
- coordinates, isCoordinateSearchActive, isExpanded, suggestions,
+ isExpanded,
} = geosearch;
const { isDistractionFreeModeActive } = ui;
const isMobile = browser.lessThan.medium;
const snapshotModalOpen = modal.isOpen && modal.id === 'TOOLBAR_SNAPSHOT';
- const geosearchMobileModalOpen = modal.isOpen && modal.id === 'TOOLBAR_GEOSEARCH_MOBILE';
// Collapse when image download, GIF, measure tool, or distraction free mode is active
const shouldCollapseFromOtherUI = snapshotModalOpen || isActive || gifActive || isDistractionFreeModeActive;
return {
- coordinates,
- geosearchMobileModalOpen,
- isCoordinatePairWithinExtent: (targetCoordinates) => areCoordinatesWithinExtent(map, config, targetCoordinates),
- isCoordinateSearchActive,
isExpanded,
isFeatureEnabled,
isMobile,
- processMagicKey: (magicKey) => processMagicKey(magicKey, config),
- reverseGeocode: (coords) => reverseGeocode(coords, config),
shouldCollapseFromOtherUI,
- suggestions,
};
};
-const mapDispatchToProps = (dispatch) => ({
- clearCoordinates: () => {
- dispatch(clearCoordinates());
- },
- selectCoordinatesToFly: (coordinates, addressAttributes) => {
- dispatch(selectCoordinatesToFly(coordinates, addressAttributes));
- },
- toggleReverseGeocodeActive: (isActive) => {
- dispatch(toggleReverseGeocodeActive(isActive));
- },
- toggleShowGeosearch: () => {
- dispatch(toggleShowGeosearch());
- },
- getSuggestions: (val) => {
- dispatch(getSuggestions(val));
- },
- clearSuggestions: () => {
- dispatch(clearSuggestions());
- },
- setSuggestion: (suggestion) => {
- dispatch(setSuggestion(suggestion));
- },
-});
-
Geosearch.propTypes = {
- clearCoordinates: PropTypes.func,
- coordinates: PropTypes.array,
- geosearchMobileModalOpen: PropTypes.bool,
- getSuggestions: PropTypes.func,
- isCoordinatePairWithinExtent: PropTypes.func,
- isCoordinateSearchActive: PropTypes.bool,
isExpanded: PropTypes.bool,
isFeatureEnabled: PropTypes.bool,
isMobile: PropTypes.bool,
- processMagicKey: PropTypes.func,
- reverseGeocode: PropTypes.func,
- selectCoordinatesToFly: PropTypes.func,
- setSuggestion: PropTypes.func,
shouldCollapseFromOtherUI: PropTypes.bool,
- suggestions: PropTypes.array,
- toggleReverseGeocodeActive: PropTypes.func,
toggleShowGeosearch: PropTypes.func,
};
export default connect(
mapStateToProps,
- mapDispatchToProps,
)(Geosearch);
diff --git a/web/js/components/geosearch/ol-coordinates-marker-util.js b/web/js/components/geosearch/ol-coordinates-marker-util.js
index abd0488de..5754e417e 100644
--- a/web/js/components/geosearch/ol-coordinates-marker-util.js
+++ b/web/js/components/geosearch/ol-coordinates-marker-util.js
@@ -1,49 +1,10 @@
-/* eslint-disable no-restricted-syntax */
-/* eslint-disable no-nested-ternary */
import Overlay from 'ol/Overlay';
import React from 'react';
import ReactDOM from 'react-dom';
import CoordinatesDialog from './coordinates-dialog';
import { coordinatesCRSTransform } from '../../modules/projection/util';
import util from '../../util/util';
-
-/**
- * Get parsed precision coordinate number
- * @param {String} coordinate
- * @returns {Number} parsed coordinate with modified precision
- */
-const getCoordinateDisplayPrecision = (coordinate) => {
- const coordinateNumber = Number(coordinate);
- const coordinatePrecision = Math.abs(coordinateNumber) > 100
- ? 7
- : coordinateNumber < 0
- ? 7
- : 6;
-
- return parseFloat(coordinateNumber.toPrecision(coordinatePrecision));
-};
-
-/**
- * getFormattedCoordinates
- *
- * @param {String} latitude
- * @param {String} longitude
- *
- * @returns {Array} formattedCoordinates
- */
-const getFormattedCoordinates = (latitude, longitude) => {
- const parsedLatitude = getCoordinateDisplayPrecision(latitude);
- const parsedLongitude = getCoordinateDisplayPrecision(longitude);
-
- // format coordinates based on localStorage preference
- const format = util.getCoordinateFormat();
- const coordinates = util.formatCoordinate(
- [parsedLongitude, parsedLatitude],
- format,
- );
- const formattedCoordinates = coordinates.split(',');
- return formattedCoordinates;
-};
+import { getFormattedCoordinates } from './util';
/**
* getCoordinatesDialogTitle
@@ -87,10 +48,12 @@ const getCoordinatesDialogTitle = (address, error, formattedLatitude, formattedL
* @param {Array} coordinates
* @param {Object} coordinatesMetadata
* @param {Boolean} isMobile
+ * @param {Function} clearCoordinates
+ * @param {Function} toggleDialogVisible
*
* @returns {Void}
*/
-export const renderCoordinatesTooltip = (map, config, coordinates, coordinatesMetadata, isMobile, clearCoordinates) => {
+export const renderCoordinatesTooltip = (map, config, coordinates, coordinatesMetadata, isMobile, clearCoordinates, toggleDialogVisible) => {
const { projections } = config;
const { proj } = map;
const { crs } = projections[proj];
@@ -117,11 +80,13 @@ export const renderCoordinatesTooltip = (map, config, coordinates, coordinatesMe
// add tooltip overlay to map and position based on marker coordinates
map.addOverlay(tooltipOverlay);
+ toggleDialogVisible(true);
tooltipOverlay.setPosition(coordinatesPosition);
// helper function to remove/hide tooltip overlay
const removeCoordinatesDialog = () => {
map.removeOverlay(tooltipOverlay);
+ toggleDialogVisible(false);
};
ReactDOM.render((
@@ -166,15 +131,18 @@ export const getCoordinatesMetadata = (geocodeProperties) => {
* @param {Object} map
* @param {Object} config
* @param {Boolean} isMobile
+ * @param {Function} clearCoordinates
+ * @param {Function} toggleDialogVisible
*
* @returns {Void}
*/
-export const getCoordinatesDialogAtMapPixel = (pixels, map, config, isMobile, clearCoordinates) => {
+export const getCoordinatesDialogAtMapPixel = (pixels, map, config, isMobile, clearCoordinates, toggleDialogVisible) => {
// check for existing coordinate marker tooltip overlay and prevent multiple renders
const mapOverlays = map.getOverlays().getArray();
+ const mapMarkerId = 'coordinates-map-marker';
const coordinatesTooltipOverlay = mapOverlays.filter((overlay) => {
const { id } = overlay;
- return id && id.includes('coordinates-map-marker');
+ return id && id.includes(mapMarkerId);
});
if (coordinatesTooltipOverlay.length > 0) {
return;
@@ -182,7 +150,7 @@ export const getCoordinatesDialogAtMapPixel = (pixels, map, config, isMobile, cl
map.forEachFeatureAtPixel(pixels, (feature) => {
const featureId = feature.getId();
- if (featureId === 'coordinates-map-marker') {
+ if (featureId === mapMarkerId) {
const featureProperties = feature.getProperties();
const { latitude, longitude } = featureProperties;
@@ -190,7 +158,7 @@ export const getCoordinatesDialogAtMapPixel = (pixels, map, config, isMobile, cl
const coordinatesMetadata = getCoordinatesMetadata(featureProperties);
// create tooltip overlay React DOM element
- renderCoordinatesTooltip(map, config, [latitude, longitude], coordinatesMetadata, isMobile, clearCoordinates);
+ renderCoordinatesTooltip(map, config, [latitude, longitude], coordinatesMetadata, isMobile, clearCoordinates, toggleDialogVisible);
}
});
};
diff --git a/web/js/components/geosearch/ol-coordinates-marker.js b/web/js/components/geosearch/ol-coordinates-marker.js
index 091021d9f..336498165 100644
--- a/web/js/components/geosearch/ol-coordinates-marker.js
+++ b/web/js/components/geosearch/ol-coordinates-marker.js
@@ -9,9 +9,12 @@ import { transform } from 'ol/proj';
import Alert from '../util/alert';
import { changeCursor as changeCursorActionCreator } from '../../modules/map/actions';
import { getCoordinatesDialogAtMapPixel } from './ol-coordinates-marker-util';
-import { clearCoordinates, selectCoordinatesToFly, toggleReverseGeocodeActive } from '../../modules/geosearch/actions';
-import { areCoordinatesWithinExtent } from '../../modules/geosearch/selectors';
-import { reverseGeocode } from '../../modules/geosearch/util';
+import {
+ clearCoordinates, selectCoordinatesToFly, toggleDialogVisible, toggleReverseGeocodeActive,
+} from '../../modules/geosearch/actions';
+import { areCoordinatesWithinExtent } from '../../modules/geosearch/util';
+import { reverseGeocode } from '../../modules/geosearch/util-api';
+import { getCoordinateFixedPrecision } from './util';
export class CoordinatesMarker extends Component {
constructor(props) {
@@ -71,7 +74,9 @@ export class CoordinatesMarker extends Component {
} else if (!hasFeatures && isShowingClick) {
changeCursor(false);
}
- this.setState({ latitude: lat, longitude: lon });
+ const latFormat = getCoordinateFixedPrecision(lat);
+ const lonFormat = getCoordinateFixedPrecision(lon);
+ this.setState({ latitude: latFormat, longitude: lonFormat });
}
rightClick(e) {
@@ -127,8 +132,9 @@ export class CoordinatesMarker extends Component {
config,
clearCoordinates,
isMobile,
+ toggleDialogVisible,
} = this.props;
- getCoordinatesDialogAtMapPixel(pixels, olMap, config, isMobile, clearCoordinates);
+ getCoordinatesDialogAtMapPixel(pixels, olMap, config, isMobile, clearCoordinates, toggleDialogVisible);
}
// render geosearch extent alert for selecting points outside of the current map extent
@@ -189,6 +195,9 @@ const mapDispatchToProps = (dispatch) => ({
clearCoordinates: () => {
dispatch(clearCoordinates());
},
+ toggleDialogVisible: (isVisible) => {
+ dispatch(toggleDialogVisible(isVisible));
+ },
});
CoordinatesMarker.propTypes = {
changeCursor: PropTypes.func.isRequired,
@@ -200,6 +209,7 @@ CoordinatesMarker.propTypes = {
measureIsActive: PropTypes.bool.isRequired,
mouseEvents: PropTypes.object.isRequired,
selectCoordinatesToFly: PropTypes.func.isRequired,
+ toggleDialogVisible: PropTypes.func.isRequired,
toggleReverseGeocodeActive: PropTypes.func.isRequired,
};
export default connect(
diff --git a/web/js/components/geosearch/util.js b/web/js/components/geosearch/util.js
index 99459ad29..b933d06ce 100644
--- a/web/js/components/geosearch/util.js
+++ b/web/js/components/geosearch/util.js
@@ -1,7 +1,12 @@
import CoordinateParser from 'coordinate-parser';
+import util from '../../util/util';
-// check for valid coordinates using https://www.npmjs.com/package/coordinate-parser
-export default function isValidCoordinates(position) {
+/**
+ * check for valid coordinates using https://www.npmjs.com/package/coordinate-parser
+ * @param {String} position
+ * @returns {Bool}
+ */
+export function isValidCoordinates(position) {
try {
const isValid = new CoordinateParser(position);
return isValid;
@@ -9,3 +14,32 @@ export default function isValidCoordinates(position) {
return false;
}
}
+
+/**
+ * Get fixed precision coordinate number
+ * @param {String} coordinate
+ * @returns {Number} parsed coordinate with fixed precision
+ */
+export const getCoordinateFixedPrecision = (coordinate) => Number(coordinate.toFixed(4));
+
+/**
+ * getFormattedCoordinates
+ *
+ * @param {String} latitude
+ * @param {String} longitude
+ *
+ * @returns {Array} formattedCoordinates
+ */
+export const getFormattedCoordinates = (latitude, longitude) => {
+ const parsedLatitude = getCoordinateFixedPrecision(latitude);
+ const parsedLongitude = getCoordinateFixedPrecision(longitude);
+
+ // format coordinates based on localStorage preference
+ const format = util.getCoordinateFormat();
+ const coordinates = util.formatCoordinate(
+ [parsedLongitude, parsedLatitude],
+ format,
+ );
+ const formattedCoordinates = coordinates.split(',');
+ return formattedCoordinates;
+};
diff --git a/web/js/containers/image-download.js b/web/js/containers/image-download.js
index 5105a71f6..fd27fbc28 100644
--- a/web/js/containers/image-download.js
+++ b/web/js/containers/image-download.js
@@ -16,7 +16,7 @@ import {
hasSubDaily as hasSubDailySelector,
getLayers,
} from '../modules/layers/selectors';
-import { removeCoordinatesOverlayFromAllProjections } from '../modules/geosearch/selectors';
+import { removeCoordinatesOverlayFromAllProjections } from '../modules/geosearch/util';
import {
resolutionsGeo,
resolutionsPolar,
diff --git a/web/js/containers/toolbar.js b/web/js/containers/toolbar.js
index 210590f2d..63032a355 100644
--- a/web/js/containers/toolbar.js
+++ b/web/js/containers/toolbar.js
@@ -77,7 +77,7 @@ const CUSTOM_MODAL_PROPS = {
backdrop: false,
bodyComponent: Geosearch,
clickableBehindModal: true,
- headerText: 'Search for places or enter coordinates',
+ headerText: 'Search for places',
mobileOnly: true,
modalClassName: 'toolbar-geosearch-modal toolbar-modal toolbar-medium-modal',
type: 'toolbar',
diff --git a/web/js/location.js b/web/js/location.js
index 933344852..616c75d09 100644
--- a/web/js/location.js
+++ b/web/js/location.js
@@ -25,8 +25,7 @@ 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 { areCoordinatesWithinExtent, mapLocationToGeosearchState } from './modules/geosearch/util';
import mapLocationToSidebarState from './modules/sidebar/util';
import util from './util/util';
import mapLocationToDataState from './modules/data/util';
diff --git a/web/js/map/ui.js b/web/js/map/ui.js
index 0cee4b945..79a257ef1 100644
--- a/web/js/map/ui.js
+++ b/web/js/map/ui.js
@@ -34,7 +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 { CLEAR_COORDINATES, UPDATE_ACTIVE_MARKER } from '../modules/geosearch/constants';
+import { CLEAR_MARKER, SET_MARKER, TOGGLE_DIALOG_VISIBLE } from '../modules/geosearch/constants';
import { SELECT_DATE } from '../modules/date/constants';
import util from '../util/util';
import * as layerConstants from '../modules/layers/constants';
@@ -55,8 +55,8 @@ 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, removeCoordinatesMarker } from '../modules/geosearch/selectors';
-import { reverseGeocode } from '../modules/geosearch/util';
+import { addCoordinatesMarker, removeCoordinatesMarker } from '../modules/geosearch/util';
+import { reverseGeocode } from '../modules/geosearch/util-api';
import { getCoordinatesMetadata, renderCoordinatesTooltip } from '../components/geosearch/ol-coordinates-marker-util';
export default function mapui(models, config, store, ui) {
@@ -233,9 +233,10 @@ export default function mapui(models, config, store, ui) {
*/
const addMarkerAndUpdateStore = (activeMarker, coordinates, results) => {
const state = store.getState();
- const { browser } = state;
+ const { browser, geosearch } = state;
const isMobile = browser.lessThan.medium;
const marker = addCoordinatesMarker(activeMarker, config, { ui: self }, coordinates, results);
+ const { isCoordinatesDialogOpen } = geosearch;
// prevent marker if outside of extent
if (!marker) {
@@ -248,13 +249,28 @@ export default function mapui(models, config, store, ui) {
const coordinatesMetadata = getCoordinatesMetadata(geocodeProperties);
// handle clearing cooridnates using created marker
- const clearCoordinates = () => {
+ const clearMarker = () => {
removeCoordinatesMarker(marker, { ui: self });
- store.dispatch({ type: CLEAR_COORDINATES });
+ store.dispatch({ type: CLEAR_MARKER });
+ };
+ // handle toggling dialog visibility to retain preference between proj changes
+ const toggleDialogVisible = (isVisible) => {
+ store.dispatch({ type: TOGGLE_DIALOG_VISIBLE, value: isVisible });
};
- renderCoordinatesTooltip(self.selected, config, [latitude, longitude], coordinatesMetadata, isMobile, clearCoordinates);
- store.dispatch({ type: UPDATE_ACTIVE_MARKER, value: marker, reverseGeocodeResults: results });
+ // only render dialog if new marker or not previously minimized
+ const isDialogOpen = !activeMarker || (activeMarker && isCoordinatesDialogOpen);
+ if (isDialogOpen) {
+ renderCoordinatesTooltip(self.selected, config, [latitude, longitude], coordinatesMetadata, isMobile, clearMarker, toggleDialogVisible);
+ }
+
+ store.dispatch({
+ type: SET_MARKER,
+ coordinates,
+ value: marker,
+ reverseGeocodeResults: results,
+ isCoordinatesDialogOpen: isDialogOpen,
+ });
};
const flyToNewExtent = function(extent, rotation) {
diff --git a/web/js/modules/geosearch/actions.js b/web/js/modules/geosearch/actions.js
index 9f6842e56..b391da6fe 100644
--- a/web/js/modules/geosearch/actions.js
+++ b/web/js/modules/geosearch/actions.js
@@ -1,24 +1,33 @@
-
import {
- CLEAR_COORDINATES,
+ CLEAR_MARKER,
CLEAR_SUGGESTIONS,
- SELECT_COORDINATES_TO_FLY,
+ SET_MARKER,
SET_SUGGESTION,
- TOGGLE_REVERSE_GEOCODE_ACTIVE,
+ TOGGLE_DIALOG_VISIBLE,
+ TOGGLE_REVERSE_GEOCODE,
TOGGLE_SHOW_GEOSEARCH,
} from './constants';
+import { requestAction } from '../core/actions';
import {
addCoordinatesMarker,
animateCoordinates,
removeCoordinatesMarker,
-} from './selectors';
-import { getMaxZoomLevelLayerCollection } from '../layers/selectors';
-import {
- GEOSEARCH_REQUEST_OPTIONS,
setLocalStorageCollapseState,
} from './util';
-import { getCoordinatesMetadata, renderCoordinatesTooltip } from '../../components/geosearch/ol-coordinates-marker-util';
-import { requestAction } from '../core/actions';
+import {
+ GEOSEARCH_REQUEST_OPTIONS,
+} from './util-api';
+import {
+ getCoordinatesMetadata,
+ renderCoordinatesTooltip,
+} from '../../components/geosearch/ol-coordinates-marker-util';
+import { getMaxZoomLevelLayerCollection } from '../layers/selectors';
+
+const {
+ REQUEST_OPTIONS,
+ GEOCODE_SUGGEST_CATEGORIES,
+ CONSTANT_REQUEST_PARAMETERS,
+} = GEOSEARCH_REQUEST_OPTIONS;
// toggle show geosearch component
export function toggleShowGeosearch() {
@@ -41,7 +50,7 @@ export function toggleShowGeosearch() {
// toggle reverse geocode - if active, next click on map will add marker and get coordinates
export function toggleReverseGeocodeActive(isCoordinateSearchActive) {
return {
- type: TOGGLE_REVERSE_GEOCODE_ACTIVE,
+ type: TOGGLE_REVERSE_GEOCODE,
value: isCoordinateSearchActive,
};
}
@@ -61,18 +70,17 @@ export function selectCoordinatesToFly(coordinates, reverseGeocodeResults) {
if (reverseGeocodeResults) {
const { error } = reverseGeocodeResults;
if (error) {
- console.log(`ERROR REVERSE GEOCODING - ${error.message} ${error.details}`);
+ console.warn(`REVERSE GEOCODING WARNING - ${error.message} ${error.details}`);
}
}
const marker = addCoordinatesMarker(activeMarker, config, map, coordinates, reverseGeocodeResults);
if (!marker) {
- console.log('ERROR ADDING MARKER - Coordinates are outside range of current map projection extent.');
return dispatch({
- type: SELECT_COORDINATES_TO_FLY,
- value: false,
+ type: SET_MARKER,
+ value: null,
coordinates: [],
- activeMarker: null,
+ isCoordinatesDialogOpen: false,
});
}
@@ -90,20 +98,26 @@ export function selectCoordinatesToFly(coordinates, reverseGeocodeResults) {
reverseGeocodeResults,
};
const coordinatesMetadata = getCoordinatesMetadata(geocodeProperties);
- const clearMarkerAndCoordinates = () => {
+ const clearMarker = () => {
removeCoordinatesMarker(marker, map);
dispatch({
- type: CLEAR_COORDINATES,
+ type: CLEAR_MARKER,
});
};
- renderCoordinatesTooltip(map.ui.selected, config, [latitude, longitude], coordinatesMetadata, isMobile, clearMarkerAndCoordinates);
+ const toggleDialog = (isVisible) => {
+ dispatch({
+ type: TOGGLE_DIALOG_VISIBLE,
+ value: isVisible,
+ });
+ };
+ renderCoordinatesTooltip(map.ui.selected, config, [latitude, longitude], coordinatesMetadata, isMobile, clearMarker, toggleDialog);
dispatch({
- type: SELECT_COORDINATES_TO_FLY,
- value: false,
+ type: SET_MARKER,
reverseGeocodeResults,
coordinates,
- activeMarker: marker,
+ value: marker,
+ isCoordinatesDialogOpen: true,
});
};
}
@@ -119,19 +133,32 @@ export function clearCoordinates() {
removeCoordinatesMarker(activeMarker, map);
}
dispatch({
- type: CLEAR_COORDINATES,
+ type: CLEAR_MARKER,
});
};
}
+// clear place suggestions
+export function toggleDialogVisible(isVisible) {
+ return (dispatch) => {
+ dispatch({
+ type: TOGGLE_DIALOG_VISIBLE,
+ value: isVisible,
+ });
+ };
+}
+
+// clear place suggestions
export function clearSuggestions() {
return (dispatch) => {
dispatch({
type: CLEAR_SUGGESTIONS,
+ value: [],
});
};
}
+// set place suggestion
export function setSuggestion(suggestion) {
return (dispatch) => {
dispatch({
@@ -141,12 +168,7 @@ export function setSuggestion(suggestion) {
};
}
-const {
- REQUEST_OPTIONS,
- GEOCODE_SUGGEST_CATEGORIES,
- CONSTANT_REQUEST_PARAMETERS,
-} = GEOSEARCH_REQUEST_OPTIONS;
-
+// get place suggestions using ArcGIS suggest API
export function getSuggestions(val) {
return (dispatch, getState) => {
const { config } = getState();
diff --git a/web/js/modules/geosearch/actions.test.js b/web/js/modules/geosearch/actions.test.js
index 04303657a..dc4859d33 100644
--- a/web/js/modules/geosearch/actions.test.js
+++ b/web/js/modules/geosearch/actions.test.js
@@ -1,12 +1,18 @@
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import {
+ clearSuggestions,
+ toggleDialogVisible,
toggleShowGeosearch,
toggleReverseGeocodeActive,
+ setSuggestion,
} from './actions';
import {
- TOGGLE_REVERSE_GEOCODE_ACTIVE,
+ TOGGLE_REVERSE_GEOCODE,
+ TOGGLE_DIALOG_VISIBLE,
TOGGLE_SHOW_GEOSEARCH,
+ CLEAR_SUGGESTIONS,
+ SET_SUGGESTION,
} from './constants';
const middlewares = [thunk];
@@ -14,6 +20,11 @@ const mockStore = configureMockStore(middlewares);
// test variables
const isExpanded = true;
+const suggestion = [{
+ isCollection: false,
+ magicKey: 'test1234=',
+ text: 'New York, NY, USA',
+}];
describe('Geosearch actions', () => {
test(`toggleShowGeosearch action returns ${TOGGLE_SHOW_GEOSEARCH} as type and ${
@@ -30,12 +41,52 @@ describe('Geosearch actions', () => {
store.dispatch(toggleShowGeosearch());
expect(store.getActions()[0]).toEqual(expectedAction);
});
- test(`toggleReverseGeocodeActive action returns ${TOGGLE_REVERSE_GEOCODE_ACTIVE} as type and ${
+ test(`toggleReverseGeocodeActive action returns ${TOGGLE_REVERSE_GEOCODE} as type and ${
true} as value`, () => {
const expectedAction = {
- type: TOGGLE_REVERSE_GEOCODE_ACTIVE,
+ type: TOGGLE_REVERSE_GEOCODE,
value: true,
};
expect(toggleReverseGeocodeActive(true)).toEqual(expectedAction);
});
+ test(`toggleDialogVisible action returns ${TOGGLE_DIALOG_VISIBLE} as type and ${
+ true} as value`, () => {
+ const expectedAction = {
+ type: TOGGLE_DIALOG_VISIBLE,
+ value: true,
+ };
+ const store = mockStore({
+ geosearch: {
+ isCoordinatesDialogOpen: false,
+ },
+ });
+ store.dispatch(toggleDialogVisible(true));
+ expect(store.getActions()[0]).toEqual(expectedAction);
+ });
+ test(`setSuggestion action returns ${SET_SUGGESTION} as type and ${suggestion} as value`, () => {
+ const expectedAction = {
+ type: SET_SUGGESTION,
+ value: suggestion,
+ };
+ const store = mockStore({
+ geosearch: {
+ suggestions: [],
+ },
+ });
+ store.dispatch(setSuggestion(suggestion));
+ expect(store.getActions()[0]).toEqual(expectedAction);
+ });
+ test(`clearSuggestions action returns ${CLEAR_SUGGESTIONS} as type and ${[]} as value`, () => {
+ const expectedAction = {
+ type: CLEAR_SUGGESTIONS,
+ value: [],
+ };
+ const store = mockStore({
+ geosearch: {
+ suggestions: [{}, {}],
+ },
+ });
+ store.dispatch(clearSuggestions());
+ expect(store.getActions()[0]).toEqual(expectedAction);
+ });
});
diff --git a/web/js/modules/geosearch/constants.js b/web/js/modules/geosearch/constants.js
index d46c16dff..abd68857c 100644
--- a/web/js/modules/geosearch/constants.js
+++ b/web/js/modules/geosearch/constants.js
@@ -1,9 +1,9 @@
-export const CLEAR_COORDINATES = 'GEOSEARCH/CLEAR_COORDINATES';
+export const CLEAR_MARKER = 'GEOSEARCH/CLEAR_MARKER';
export const CLEAR_SUGGESTIONS = 'GEOSEARCH/CLEAR_SUGGESTIONS';
export const REQUEST_SUGGEST_PLACE_FAILURE = 'GEOSEARCH/REQUEST_SUGGEST_PLACE_FAILURE';
export const REQUEST_SUGGEST_PLACE_SUCCESS = 'GEOSEARCH/REQUEST_SUGGEST_PLACE_SUCCESS';
-export const SELECT_COORDINATES_TO_FLY = 'GEOSEARCH/SELECT_COORDINATES_TO_FLY';
+export const SET_MARKER = 'GEOSEARCH/SET_MARKER';
export const SET_SUGGESTION = 'GEOSEARCH/SET_SUGGESTION';
-export const TOGGLE_REVERSE_GEOCODE_ACTIVE = 'GEOSEARCH/TOGGLE_REVERSE_GEOCODE_ACTIVE';
+export const TOGGLE_DIALOG_VISIBLE = 'GEOSEARCH/TOGGLE_DIALOG_VISIBLE';
+export const TOGGLE_REVERSE_GEOCODE = 'GEOSEARCH/TOGGLE_REVERSE_GEOCODE';
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
index 87418ce6b..8c85e9388 100644
--- a/web/js/modules/geosearch/reducers.js
+++ b/web/js/modules/geosearch/reducers.js
@@ -1,13 +1,13 @@
import {
- CLEAR_COORDINATES,
+ CLEAR_MARKER,
CLEAR_SUGGESTIONS,
REQUEST_SUGGEST_PLACE_FAILURE,
REQUEST_SUGGEST_PLACE_SUCCESS,
- SELECT_COORDINATES_TO_FLY,
+ SET_MARKER,
SET_SUGGESTION,
- TOGGLE_REVERSE_GEOCODE_ACTIVE,
+ TOGGLE_DIALOG_VISIBLE,
+ TOGGLE_REVERSE_GEOCODE,
TOGGLE_SHOW_GEOSEARCH,
- UPDATE_ACTIVE_MARKER,
} from './constants';
import { getLocalStorageCollapseState } from './util';
@@ -16,6 +16,7 @@ export const geosearchState = {
activeMarker: null,
coordinates: [],
isCoordinateSearchActive: false,
+ isCoordinatesDialogOpen: false,
isExpanded: !localStorageCollapseState,
reverseGeocodeResults: null,
suggestions: [],
@@ -23,41 +24,37 @@ export const geosearchState = {
export function geosearchReducer(state = geosearchState, action) {
switch (action.type) {
- case UPDATE_ACTIVE_MARKER:
+ case TOGGLE_DIALOG_VISIBLE:
return {
...state,
- activeMarker: action.value,
- reverseGeocodeResults: action.reverseGeocodeResults,
+ isCoordinatesDialogOpen: action.value,
};
case TOGGLE_SHOW_GEOSEARCH:
return {
...state,
isExpanded: action.value,
};
- case SELECT_COORDINATES_TO_FLY:
+ case TOGGLE_REVERSE_GEOCODE:
return {
...state,
isCoordinateSearchActive: action.value,
+ };
+ case SET_MARKER:
+ return {
+ ...state,
+ activeMarker: action.value,
coordinates: action.coordinates,
- activeMarker: action.activeMarker,
+ isCoordinateSearchActive: false,
reverseGeocodeResults: action.reverseGeocodeResults,
+ isCoordinatesDialogOpen: action.isCoordinatesDialogOpen,
};
- case CLEAR_COORDINATES:
+ case CLEAR_MARKER:
return {
...state,
- coordinates: [],
activeMarker: null,
+ coordinates: [],
reverseGeocodeResults: null,
- };
- case TOGGLE_REVERSE_GEOCODE_ACTIVE:
- return {
- ...state,
- isCoordinateSearchActive: action.value,
- };
- case CLEAR_SUGGESTIONS:
- return {
- ...state,
- suggestions: [],
+ isCoordinatesDialogOpen: false,
};
case SET_SUGGESTION:
return {
@@ -74,6 +71,11 @@ export function geosearchReducer(state = geosearchState, action) {
...state,
suggestions: [],
};
+ case CLEAR_SUGGESTIONS:
+ return {
+ ...state,
+ suggestions: action.value,
+ };
default:
return state;
}
diff --git a/web/js/modules/geosearch/reducers.test.js b/web/js/modules/geosearch/reducers.test.js
index c4171c0ab..cd7bbec47 100644
--- a/web/js/modules/geosearch/reducers.test.js
+++ b/web/js/modules/geosearch/reducers.test.js
@@ -3,11 +3,13 @@ import {
geosearchState,
} from './reducers';
import {
- CLEAR_COORDINATES,
- SELECT_COORDINATES_TO_FLY,
- TOGGLE_REVERSE_GEOCODE_ACTIVE,
+ CLEAR_MARKER,
+ CLEAR_SUGGESTIONS,
+ SET_MARKER,
+ SET_SUGGESTION,
+ TOGGLE_DIALOG_VISIBLE,
+ TOGGLE_REVERSE_GEOCODE,
TOGGLE_SHOW_GEOSEARCH,
- UPDATE_ACTIVE_MARKER,
} from './constants';
// test variables
@@ -15,99 +17,137 @@ const reverseGeocodeResults = {
address: {},
location: {},
};
+const suggestion = [{
+ isCollection: false,
+ magicKey: 'test1234=',
+ text: 'New York, NY, USA',
+}];
+const coordinates = [72, 40];
describe('geosearchReducer', () => {
- test(' should return the initial state', () => {
+ test('geosearchReducer should return the initial state', () => {
expect(geosearchReducer(undefined, {})).toEqual(
geosearchState,
);
});
test(
- `${CLEAR_COORDINATES
- } resets cooridnates, activeMarker, and geocode results`
+ `${TOGGLE_SHOW_GEOSEARCH
+ } shows geosearch isExpanded and `
+ 'should return new state',
() => {
expect(
geosearchReducer(geosearchState, {
- type: CLEAR_COORDINATES,
+ type: TOGGLE_SHOW_GEOSEARCH,
+ value: true,
}),
).toEqual({
...geosearchState,
- coordinates: [],
- activeMarker: null,
- reverseGeocodeResults: null,
+ isExpanded: true,
});
},
);
test(
- `${TOGGLE_SHOW_GEOSEARCH
- } shows geosearch isExpanded and `
+ `${TOGGLE_REVERSE_GEOCODE
+ } toggles isCoordinateSearchActive to true and `
+ 'should return new state',
() => {
expect(
geosearchReducer(geosearchState, {
- type: TOGGLE_SHOW_GEOSEARCH,
+ type: TOGGLE_REVERSE_GEOCODE,
value: true,
}),
).toEqual({
...geosearchState,
- isExpanded: true,
+ isCoordinateSearchActive: true,
});
},
);
test(
- `${TOGGLE_REVERSE_GEOCODE_ACTIVE
- } toggles isCoordinateSearchActive to true and `
+ `${TOGGLE_DIALOG_VISIBLE
+ } sets coordinate dialog visiblity and `
+ 'should return new state',
() => {
expect(
geosearchReducer(geosearchState, {
- type: TOGGLE_REVERSE_GEOCODE_ACTIVE,
+ type: TOGGLE_DIALOG_VISIBLE,
value: true,
}),
).toEqual({
...geosearchState,
- isCoordinateSearchActive: true,
+ isCoordinatesDialogOpen: true,
});
},
);
test(
- `${UPDATE_ACTIVE_MARKER
- } updates action value and reverseGeocodeResults objects and `
- + 'should return new state',
+ `${SET_MARKER
+ } updates activeMarker, coordinates, reverseGeocodeResults `
+ + 'and sets isCoordinateSearchActive to false and should return new state',
() => {
expect(
geosearchReducer(geosearchState, {
- type: UPDATE_ACTIVE_MARKER,
+ type: SET_MARKER,
value: {},
+ coordinates,
reverseGeocodeResults,
+ isCoordinatesDialogOpen: true,
}),
).toEqual({
...geosearchState,
+ isCoordinateSearchActive: false,
+ coordinates,
activeMarker: {},
reverseGeocodeResults,
+ isCoordinatesDialogOpen: true,
});
},
);
test(
- `${SELECT_COORDINATES_TO_FLY
- } updates activeMarker, coordinates, and reverseGeocodeResults `
- + 'and sets isCoordinateSearchActive to false and should return new state',
+ `${CLEAR_MARKER
+ } resets cooridnates, activeMarker, and geocode results`
+ + 'should return new state',
() => {
expect(
geosearchReducer(geosearchState, {
- type: SELECT_COORDINATES_TO_FLY,
- value: false,
- coordinates: [],
- activeMarker: {},
- reverseGeocodeResults,
+ type: CLEAR_MARKER,
}),
).toEqual({
...geosearchState,
- isCoordinateSearchActive: false,
coordinates: [],
- activeMarker: {},
- reverseGeocodeResults,
+ activeMarker: null,
+ reverseGeocodeResults: null,
+ isCoordinatesDialogOpen: false,
+ });
+ },
+ );
+ test(
+ `${SET_SUGGESTION
+ } updates suggestions with value and `
+ + 'should return new state',
+ () => {
+ expect(
+ geosearchReducer(geosearchState, {
+ type: SET_SUGGESTION,
+ value: suggestion,
+ }),
+ ).toEqual({
+ ...geosearchState,
+ suggestions: suggestion,
+ });
+ },
+ );
+ test(
+ `${CLEAR_SUGGESTIONS
+ } updates suggestions with clear value and `
+ + 'should return new state',
+ () => {
+ expect(
+ geosearchReducer(geosearchState, {
+ type: CLEAR_SUGGESTIONS,
+ value: [],
+ }),
+ ).toEqual({
+ ...geosearchState,
+ suggestions: [],
});
},
);
diff --git a/web/js/modules/geosearch/selectors.js b/web/js/modules/geosearch/selectors.js
deleted file mode 100644
index d25c978d5..000000000
--- a/web/js/modules/geosearch/selectors.js
+++ /dev/null
@@ -1,130 +0,0 @@
-import OlPoint from 'ol/geom/Point';
-import OlFeature from 'ol/Feature';
-import OlLayerVector from 'ol/layer/Vector';
-import OlSourceVector from 'ol/source/Vector';
-import {
- Style as OlStyle,
- Icon as OlIcon,
-} from 'ol/style';
-import { containsXY } from 'ol/extent';
-import { coordinatesCRSTransform } from '../projection/util';
-
-// animate coordinates marker
-export function animateCoordinates(map, config, coordinates, zoom) {
- const { projections } = config;
- const { selected } = map.ui;
- const { proj } = selected;
- const { crs } = projections[proj];
-
- let [x, y] = coordinates;
- if (proj !== 'geographic') {
- [x, y] = coordinatesCRSTransform(coordinates, 'EPSG:4326', crs);
- }
- map.ui.animate.fly([x, y], zoom);
-}
-
-// check if coordinates are within selected map extent
-export function areCoordinatesWithinExtent(map, config, coordinates) {
- const { projections } = config;
- const { selected } = map.ui;
- const { proj } = selected;
- const { maxExtent, crs } = projections[proj];
-
- let [x, y] = coordinates;
- if (proj !== 'geographic') {
- const transformedXY = coordinatesCRSTransform(coordinates, 'EPSG:4326', crs);
- [x, y] = transformedXY;
- }
- const coordinatesWithinExtent = containsXY(maxExtent, x, y);
- return coordinatesWithinExtent;
-}
-
-// add coordinates marker
-export function addCoordinatesMarker(activeMarker, config, map, coordinates, reverseGeocodeResults) {
- const { projections } = config;
- const { selected } = map.ui;
- const { proj } = selected;
- const { crs } = projections[proj];
-
- // remove any markers
- removeCoordinatesMarker(activeMarker, map);
-
- // only add marker within current map extent
- const coordinatesWithinExtent = areCoordinatesWithinExtent(map, config, coordinates);
- if (!coordinatesWithinExtent) {
- return false;
- }
-
- // transform coordinates if not CRS EPSG:4326
- let transformedCoordinates = false;
- if (proj !== 'geographic') {
- transformedCoordinates = coordinatesCRSTransform(coordinates, 'EPSG:4326', crs);
- }
-
- // create Ol vector layer map pin
- const marker = createPin(coordinates, transformedCoordinates, reverseGeocodeResults);
- selected.addLayer(marker);
- selected.renderSync();
- return marker;
-}
-
-// remove coordinates tooltip from all projections
-export function removeCoordinatesOverlayFromAllProjections(proj) {
- const mapProjections = Object.keys(proj);
- mapProjections.forEach((mapProjection) => {
- const mapOverlays = proj[mapProjection].getOverlays().getArray();
- const coordinatesTooltipOverlay = mapOverlays.filter((overlay) => {
- const { id } = overlay;
- return id && id.includes('coordinates-map-marker');
- });
- if (coordinatesTooltipOverlay.length > 0) {
- proj[mapProjection].removeOverlay(coordinatesTooltipOverlay[0]);
- }
- });
-}
-
-// remove coordinates marker
-export function removeCoordinatesMarker(activeMarker, map) {
- const { selected, proj } = map.ui;
- // remove marker
- if (activeMarker) {
- activeMarker.setMap(null);
- selected.removeLayer(activeMarker);
- }
- // remove tooltip from all projections
- removeCoordinatesOverlayFromAllProjections(proj);
-}
-
-// create Ol vector layer map pin
-const createPin = function(coordinates, transformedCoordinates = false, reverseGeocodeResults = {}) {
- const [longitude, latitude] = coordinates;
- const iconFeature = new OlFeature({
- geometry: new OlPoint(transformedCoordinates || coordinates),
- reverseGeocodeResults,
- latitude,
- longitude,
- });
-
- const iconStyle = new OlStyle({
- image: new OlIcon({
- anchorOrigin: 'bottom-left',
- anchorXUnits: 'fraction',
- anchorYUnits: 'pixels',
- scale: 0.5,
- src: 'images/map-pin.png',
- }),
- });
-
- iconFeature.setStyle(iconStyle);
- iconFeature.setId('coordinates-map-marker');
-
- const vectorSource = new OlSourceVector({
- wrapX: false,
- features: [iconFeature],
- });
- const vectorLayer = new OlLayerVector({
- source: vectorSource,
- });
-
- return vectorLayer;
-};
diff --git a/web/js/modules/geosearch/util-api.js b/web/js/modules/geosearch/util-api.js
new file mode 100644
index 000000000..0721c5292
--- /dev/null
+++ b/web/js/modules/geosearch/util-api.js
@@ -0,0 +1,57 @@
+// ArcGIS World Geocoding Service API Request Options
+export const GEOSEARCH_REQUEST_OPTIONS = {
+ REQUEST_OPTIONS: {
+ method: 'GET',
+ redirect: 'follow',
+ },
+ // https://developers.arcgis.com/rest/geocode/api-reference/geocoding-category-filtering.htm
+ // necessary to filter to remove fast food type suggestions, but still include relavant Places of Interest
+ GEOCODE_SUGGEST_CATEGORIES: [
+ 'Address',
+ 'Street Address',
+ 'Populated Place',
+ 'Education',
+ 'Land Features',
+ 'Water Features',
+ 'Museum',
+ 'Tourist Attraction',
+ 'Scientific Research',
+ 'Government Office',
+ 'Business Facility',
+ 'Primary Postal',
+ 'Airport',
+ ],
+ // language code EN (English) and required f request format parameters
+ CONSTANT_REQUEST_PARAMETERS: '&langCode=en&f=json',
+};
+
+const {
+ REQUEST_OPTIONS,
+ CONSTANT_REQUEST_PARAMETERS,
+} = GEOSEARCH_REQUEST_OPTIONS;
+
+export async function processMagicKey(magicKey, config) {
+ const { features: { geocodeSearch: { url: requestUrl } } } = config;
+ const request = `${requestUrl}findAddressCandidates?outFields=*${CONSTANT_REQUEST_PARAMETERS}&magicKey=${magicKey}=`;
+
+ try {
+ const response = await fetch(request, REQUEST_OPTIONS);
+ const result = await response.text();
+ return JSON.parse(result);
+ } catch (error) {
+ return console.log('error', error);
+ }
+}
+
+export async function reverseGeocode(coordinates, config) {
+ const { features: { geocodeSearch: { url: requestUrl } } } = config;
+ const request = `${requestUrl}reverseGeocode?location=${coordinates}${CONSTANT_REQUEST_PARAMETERS}`;
+
+ try {
+ const response = await fetch(request, REQUEST_OPTIONS);
+ 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
index a640ea24f..1ac99c716 100644
--- a/web/js/modules/geosearch/util.js
+++ b/web/js/modules/geosearch/util.js
@@ -1,66 +1,139 @@
import update from 'immutability-helper';
+import lodashIsNaN from 'lodash/isNaN';
+import OlPoint from 'ol/geom/Point';
+import OlFeature from 'ol/Feature';
+import OlLayerVector from 'ol/layer/Vector';
+import OlSourceVector from 'ol/source/Vector';
+import {
+ Style as OlStyle,
+ Icon as OlIcon,
+} from 'ol/style';
+import { containsXY } from 'ol/extent';
+import { coordinatesCRSTransform } from '../projection/util';
import safeLocalStorage from '../../util/local-storage';
const { GEOSEARCH_COLLAPSED } = safeLocalStorage.keys;
-// ArcGIS World Geocoding Service API Request Options
-export const GEOSEARCH_REQUEST_OPTIONS = {
- REQUEST_OPTIONS: {
- method: 'GET',
- redirect: 'follow',
- },
- // https://developers.arcgis.com/rest/geocode/api-reference/geocoding-category-filtering.htm
- // necessary to filter to remove fast food type suggestions, but still include relavant Places of Interest
- GEOCODE_SUGGEST_CATEGORIES: [
- 'Address',
- 'Street Address',
- 'Populated Place',
- 'Education',
- 'Land Features',
- 'Water Features',
- 'Museum',
- 'Tourist Attraction',
- 'Scientific Research',
- 'Government Office',
- 'Business Facility',
- 'Primary Postal',
- 'Airport',
- ],
- // language code EN (English) and required f request format parameters
- CONSTANT_REQUEST_PARAMETERS: '&langCode=en&f=json',
-};
+// animate coordinates marker
+export function animateCoordinates(map, config, coordinates, zoom) {
+ const { projections } = config;
+ const { selected } = map.ui;
+ const { proj } = selected;
+ const { crs } = projections[proj];
-const {
- REQUEST_OPTIONS,
- CONSTANT_REQUEST_PARAMETERS,
-} = GEOSEARCH_REQUEST_OPTIONS;
-
-export async function processMagicKey(magicKey, config) {
- const { features: { geocodeSearch: { url: requestUrl } } } = config;
- const request = `${requestUrl}findAddressCandidates?outFields=*${CONSTANT_REQUEST_PARAMETERS}&magicKey=${magicKey}=`;
-
- try {
- const response = await fetch(request, REQUEST_OPTIONS);
- const result = await response.text();
- return JSON.parse(result);
- } catch (error) {
- return console.log('error', error);
+ let [x, y] = coordinates;
+ if (proj !== 'geographic') {
+ [x, y] = coordinatesCRSTransform(coordinates, 'EPSG:4326', crs);
}
+ map.ui.animate.fly([x, y], zoom);
+}
+
+// check if coordinates are within selected map extent
+export function areCoordinatesWithinExtent(map, config, coordinates) {
+ const { projections } = config;
+ const { selected } = map.ui;
+ const { proj } = selected;
+ const { maxExtent, crs } = projections[proj];
+
+ let [x, y] = coordinates;
+ if (proj !== 'geographic') {
+ const transformedXY = coordinatesCRSTransform(coordinates, 'EPSG:4326', crs);
+ [x, y] = transformedXY;
+ }
+ const coordinatesWithinExtent = containsXY(maxExtent, x, y);
+ return coordinatesWithinExtent;
+}
+
+// add coordinates marker
+export function addCoordinatesMarker(activeMarker, config, map, coordinates, reverseGeocodeResults) {
+ const { projections } = config;
+ const { selected } = map.ui;
+ const { proj } = selected;
+ const { crs } = projections[proj];
+
+ // remove any markers
+ removeCoordinatesMarker(activeMarker, map);
+
+ // only add marker within current map extent
+ const coordinatesWithinExtent = areCoordinatesWithinExtent(map, config, coordinates);
+ if (!coordinatesWithinExtent) {
+ return false;
+ }
+
+ // transform coordinates if not CRS EPSG:4326
+ let transformedCoordinates = false;
+ if (proj !== 'geographic') {
+ transformedCoordinates = coordinatesCRSTransform(coordinates, 'EPSG:4326', crs);
+ }
+
+ // create Ol vector layer map pin
+ const marker = createPin(coordinates, transformedCoordinates, reverseGeocodeResults);
+ selected.addLayer(marker);
+ selected.renderSync();
+ return marker;
}
-export async function reverseGeocode(coordinates, config) {
- const { features: { geocodeSearch: { url: requestUrl } } } = config;
- const request = `${requestUrl}reverseGeocode?location=${coordinates}${CONSTANT_REQUEST_PARAMETERS}`;
+// remove coordinates tooltip from all projections
+export function removeCoordinatesOverlayFromAllProjections(proj) {
+ const mapProjections = Object.keys(proj);
+ mapProjections.forEach((mapProjection) => {
+ const mapOverlays = proj[mapProjection].getOverlays().getArray();
+ const coordinatesTooltipOverlay = mapOverlays.filter((overlay) => {
+ const { id } = overlay;
+ return id && id.includes('coordinates-map-marker');
+ });
+ if (coordinatesTooltipOverlay.length > 0) {
+ proj[mapProjection].removeOverlay(coordinatesTooltipOverlay[0]);
+ }
+ });
+}
- try {
- const response = await fetch(request, REQUEST_OPTIONS);
- const result = await response.text();
- return JSON.parse(result);
- } catch (error) {
- return console.log('error', error);
+// remove coordinates marker
+export function removeCoordinatesMarker(activeMarker, map) {
+ const { selected, proj } = map.ui;
+ // remove marker
+ if (activeMarker) {
+ activeMarker.setMap(null);
+ selected.removeLayer(activeMarker);
}
+ // remove tooltip from all projections
+ removeCoordinatesOverlayFromAllProjections(proj);
}
+// create Ol vector layer map pin
+const createPin = function(coordinates, transformedCoordinates = false, reverseGeocodeResults = {}) {
+ const [longitude, latitude] = coordinates;
+ const iconFeature = new OlFeature({
+ geometry: new OlPoint(transformedCoordinates || coordinates),
+ reverseGeocodeResults,
+ latitude,
+ longitude,
+ });
+
+ const iconStyle = new OlStyle({
+ image: new OlIcon({
+ anchorOrigin: 'bottom-left',
+ anchorXUnits: 'fraction',
+ anchorYUnits: 'pixels',
+ scale: 0.5,
+ src: 'images/map-pin.png',
+ }),
+ });
+
+ iconFeature.setStyle(iconStyle);
+ iconFeature.setId('coordinates-map-marker');
+
+ const vectorSource = new OlSourceVector({
+ wrapX: false,
+ features: [iconFeature],
+ });
+ const vectorLayer = new OlLayerVector({
+ source: vectorSource,
+ });
+
+ return vectorLayer;
+};
+
/**
*
* @param {*} parameters
@@ -72,8 +145,13 @@ export function mapLocationToGeosearchState(
state,
) {
const { marker } = parameters;
- const coordinates = marker
- ? marker.split(',').map((coord) => Number(coord))
+ const validCoordinates = marker
+ ? marker.split(',')
+ .map((coord) => Number(coord))
+ .filter((coord) => !lodashIsNaN(parseFloat(coord)))
+ : [];
+ const coordinates = validCoordinates.length === 2
+ ? validCoordinates
: [];
const isMobile = state.browser.lessThan.medium;
diff --git a/web/js/modules/image-download/util.test.js b/web/js/modules/image-download/util.test.js
index 4e4a35701..e6a40dbfe 100644
--- a/web/js/modules/image-download/util.test.js
+++ b/web/js/modules/image-download/util.test.js
@@ -214,7 +214,7 @@ test('Download URL', () => {
height: 300,
};
const dateTime = new Date('2019-06-24T19:04:00Z');
- const geosearchCoordinates = [-19.16086, 2.71169];
+ const geosearchCoordinates = [-19.1609, 2.7117];
const dlURL = getDownloadUrl(url, proj, mockLayerDefs, lonlats, dimensions, dateTime, false, false, geosearchCoordinates);
const expectedURL = 'http://localhost:3002/api/v1/snapshot'
+ '?REQUEST=GetSnapshot'
@@ -225,6 +225,6 @@ test('Download URL', () => {
+ '&WRAP=day'
+ '&FORMAT=image/jpeg'
+ '&WIDTH=300&HEIGHT=300'
- + '&MARKER=-19.16086,2.71169';
+ + '&MARKER=-19.1609,2.7117';
expect(dlURL.includes(expectedURL)).toBe(true);
});