Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Setting to choose coordinate display format #526

Merged
merged 23 commits into from
Apr 19, 2021
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
2736f57
feat: Add coordinate system page to settings with ability to change b…
luandro Mar 16, 2021
cf4be4f
fix: Add latlon to formatCoords switch
luandro Mar 17, 2021
81953d0
feat: Add information on GpsModal based on selected coordinate system
luandro Mar 17, 2021
330c882
feat: Show coordinates on observation screens based on selected system
luandro Mar 17, 2021
32fbe0a
fix: Add value check before setting AsyncStorage
luandro Mar 17, 2021
2c07212
fix: Have Coordinate System before About Mapeo on configuration menu
luandro Mar 24, 2021
f853030
fix: Remove Decimal Degrees which is same as Lat Long
luandro Mar 24, 2021
873a6b5
fix: Round decimal degrees to 6 decimal places
luandro Mar 24, 2021
48e815b
chore: Cleanup and add better formating for DMS
luandro Mar 24, 2021
930346b
fix: Add 3 decimal degrees to DMS coordinates
luandro Mar 24, 2021
70b3d1c
fix: Pass lat/lon explicitly within an object on formatting functions
luandro Mar 26, 2021
31c127a
fix: Use Decimal Degrees naming instead of lat/lon
luandro Mar 26, 2021
72fa39e
chore: Extract messages and add DD to naming in config menu
luandro Mar 26, 2021
e4ee80d
chore: Add settings context
luandro Apr 1, 2021
4caa862
chore: Update screens and components to use settings context
luandro Apr 1, 2021
d4499e8
fixes & cleanup
gmaclennan Apr 16, 2021
a41fddf
remove unused message
gmaclennan Apr 16, 2021
9e8eeaa
Update language to coordinate format
gmaclennan Apr 16, 2021
4b15d25
Use Number.toFixed() for rounding coordinates
gmaclennan Apr 16, 2021
ecc7245
Merge branch 'develop' into custom-coord-system
gmaclennan Apr 16, 2021
46fe030
Fix flow type error
gmaclennan Apr 16, 2021
fa8a738
Add comma to DMS formatting
gmaclennan Apr 16, 2021
7e02d19
Format lat/long DD according to Nat Geo style guide
gmaclennan Apr 16, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,22 @@
"description": "Title for category chooser screen",
"message": "Choose what is happening"
},
"screens.CoordinateSystem.dd": {
"description": "Decimal Degrees coordinate system",
"message": "Decimal Degrees (DD)"
},
"screens.CoordinateSystem.dms": {
"description": "Degrees/Minutes/Seconds coordinate system",
"message": "Degrees/Minutes/Seconds (DMS)"
},
"screens.CoordinateSystem.title": {
"description": "Title coordinate system screen",
"message": "Coordinate System"
},
"screens.CoordinateSystem.utm": {
"description": "Universal Transverse Mercator coordinate system",
"message": "Universal Transverse Mercator (UTM)"
},
"screens.GpsModal.details": {
"description": "Section title for details about current position",
"message": "Details"
Expand All @@ -70,6 +86,18 @@
"description": "Section title for time of last GPS update",
"message": "Last update"
},
"screens.GpsModal.locationDD": {
"description": "Section title for DD coordinates",
"message": "Coordinates Decimal Degrees"
},
"screens.GpsModal.locationDMS": {
"description": "Section title for DMS coordinates",
"message": "Coordinates DMS"
},
"screens.GpsModal.locationLatLon": {
"description": "Section title for latitude and longitude coordinates",
"message": "Coordinates Latitude and Longitude"
},
"screens.GpsModal.locationSensors": {
"description": "Heading for section about location sensor status",
"message": "Sensor Status"
Expand Down Expand Up @@ -296,6 +324,14 @@
"description": "Title of error dialog when there is an error importing a config file",
"message": "Import Error"
},
"screens.Settings.coordinateSystem": {
"description": "Settings for coordinate systems",
"message": "Coordinate System"
},
"screens.Settings.coordinateSystemDesc": {
"description": "Description of the 'Coordinate System' page",
"message": "DD, UTM, DMS"
},
"screens.Settings.currentConfig": {
"description": "Label for name & version of current configuration",
"message": "Current Configuration"
Expand Down
3 changes: 3 additions & 0 deletions src/frontend/AppStack.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import CustomHeaderLeft from "./sharedComponents/CustomHeaderLeft";
import ProjectConfig from "./screens/Settings/ProjectConfig";
import AboutMapeo from "./screens/Settings/AboutMapeo";
import LanguageSettings from "./screens/Settings/LanguageSettings";
import CoordinateSystem from "./screens/Settings/CoordinateSystem";
import HomeHeader from "./sharedComponents/HomeHeader";

const HomeTabs = createBottomTabNavigator(
Expand Down Expand Up @@ -68,6 +69,8 @@ const AppStack = createStackNavigator(
// $FlowFixMe
LanguageSettings,
// $FlowFixMe
CoordinateSystem,
// $FlowFixMe
PhotosModal: PhotosModal,
// $FlowFixMe
CategoryChooser: CategoryChooser,
Expand Down
5 changes: 4 additions & 1 deletion src/frontend/context/AppProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as React from "react";
import { LocationProvider } from "./LocationContext";
import { ObservationsProvider } from "./ObservationsContext";
import { ConfigProvider } from "./ConfigContext";
import { SettingsProvider } from "./SettingsContext";
import { DraftObservationProvider } from "./DraftObservationContext";

// This is a convenience wrapper for providing all App contexts to the tree,
Expand All @@ -12,7 +13,9 @@ const AppProvider = ({ children }: { children: React.Node }) => (
<LocationProvider>
<ObservationsProvider>
<ConfigProvider>
<DraftObservationProvider>{children}</DraftObservationProvider>
<SettingsProvider>
<DraftObservationProvider>{children}</DraftObservationProvider>
</SettingsProvider>
</ConfigProvider>
</ObservationsProvider>
</LocationProvider>
Expand Down
84 changes: 84 additions & 0 deletions src/frontend/context/SettingsContext.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// @flow
import * as React from "react";
import AsyncStorage from "@react-native-community/async-storage";

const STORE_KEY = "@MapeoSettings@36";

export type SettingsContextType = {
coordinateSystem?: string,
};

const initialState = {
coordinateSystem: "utm",
};

const defaultContext = [initialState, () => {}];
const SettingsContext = React.createContext(defaultContext);

function reducer(state: State, action: Action): State {
switch (action.type) {
case "set": {
return action.value;
}
case "set_coordinate_system": {
try {
return { ...state, coordinateSystem: action.value };
} catch {
return state;
}
}
default:
return state;
}
}

const getData = async dispatch => {
try {
// AsyncStorage.clear()
const state = await AsyncStorage.getItem(STORE_KEY);
if (state) {
const parsedState = JSON.parse(state);
dispatch({ type: "set", value: parsedState });
return parsedState;
} else return initialState;
} catch (e) {
console.log("Failed to fetch the data from storage");
return initialState;
}
};

const saveData = async value => {
try {
const stringified = JSON.stringify(value);
await AsyncStorage.setItem(STORE_KEY, stringified);
return value;
} catch (e) {
console.log("Failed to save the data to the storage");
}
};

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is already a usePersistedState hook, so best use that rather than have two different implementations of this.

export const SettingsProvider = ({ children }: { children: React.Node }) => {
const didMountRef = React.useRef(false);
const [state, dispatch] = React.useReducer(reducer, defaultContext[0]);
const contextValue = React.useMemo(() => [state, dispatch], [
state,
dispatch,
]);
React.useEffect(() => {
if (didMountRef.current) {
saveData(contextValue[0]);
} else {
didMountRef.current = true;
getData(dispatch);
}
}, [contextValue]);
return (
<SettingsContext.Provider
value={{ settings: contextValue[0], dispatch: contextValue[1] }}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This creates a new object on every render

>
{children}
</SettingsContext.Provider>
);
};

export default SettingsContext;
65 changes: 56 additions & 9 deletions src/frontend/lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,15 +121,30 @@ export function getLastPhotoAttachment(
return filterPhotosFromAttachments(attachments).pop();
}

export function formatCoords({
lon,
lat,
format = "utm",
}: {
lon: number,
lat: number,
format?: "utm",
}): string {
// Coordinates conversions
function toDegreesMinutesAndSeconds(coordinate) {
const absolute = Math.abs(coordinate);
const degrees = Math.floor(absolute);
const minutesNotTruncated = (absolute - degrees) * 60;
const minutes = Math.floor(minutesNotTruncated);
const seconds = (minutesNotTruncated - minutes) * 60;
const decimals = 3;
const formattedSeconds = Number(
Math.round(seconds + "e" + decimals) + "e-" + decimals
);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not seconds.toFixed(3)?

return `${degrees}° ${minutes}' ${formattedSeconds}"`;
}

function convertToDMS({ lat, lon }) {
const latitude = toDegreesMinutesAndSeconds(lat);
const latitudeCardinal = lat >= 0 ? "N" : "S";

const longitude = toDegreesMinutesAndSeconds(lon);
const longitudeCardinal = lon >= 0 ? "E" : "W";
return `${latitude} ${latitudeCardinal} ${longitude} ${longitudeCardinal}`;
}

function convertToUTM({ lat, lon }) {
try {
let { easting, northing, zoneNum, zoneLetter } = fromLatLon(lat, lon);
easting = leftPad(easting.toFixed(), 6, "0");
Expand All @@ -143,6 +158,38 @@ export function formatCoords({
}
}

function formatDD({ lat, lon }) {
const decimals = 6;
const formattedLat = Number(
Math.round(lat + "e" + decimals) + "e-" + decimals
);
const formattedLon = Number(
Math.round(lon + "e" + decimals) + "e-" + decimals
);
return `lat ${formattedLat} lon ${formattedLon}`;
}

export function formatCoords({
lon,
lat,
format = "utm",
}: {
lon: number,
lat: number,
format?: "utm" | "dd" | "dms",
}): string {
switch (format) {
case "dd":
return formatDD({ lat, lon });
case "utm":
return convertToUTM({ lat, lon });
case "dms":
return convertToDMS({ lat, lon });
default:
return convertToUTM({ lat, lon });
}
}

export function getProp(tags: any, fieldKey: Key, defaultValue: any) {
// TODO: support deeply nested tags.
const shallowKey = Array.isArray(fieldKey) ? fieldKey[0] : fieldKey;
Expand Down
37 changes: 34 additions & 3 deletions src/frontend/screens/GpsModal.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import Text from "../sharedComponents/Text";
import { defineMessages, FormattedMessage, useIntl } from "react-intl";

import LocationContext from "../context/LocationContext";
import SettingsContext from "../context/SettingsContext";

import { FormattedCoords } from "../sharedComponents/FormattedData";
import DateDistance from "../sharedComponents/DateDistance";
import HeaderTitle from "../sharedComponents/HeaderTitle";
Expand All @@ -27,6 +29,21 @@ const m = defineMessages({
defaultMessage: "Coordinates UTM",
description: "Section title for UTM coordinates",
},
locationLatLon: {
id: "screens.GpsModal.locationLatLon",
defaultMessage: "Coordinates Latitude and Longitude",
description: "Section title for latitude and longitude coordinates",
},
locationDMS: {
id: "screens.GpsModal.locationDMS",
defaultMessage: "Coordinates DMS",
description: "Section title for DMS coordinates",
},
locationDD: {
id: "screens.GpsModal.locationDD",
defaultMessage: "Coordinates Decimal Degrees",
description: "Section title for DD coordinates",
},
details: {
id: "screens.GpsModal.details",
defaultMessage: "Details",
Expand Down Expand Up @@ -62,7 +79,22 @@ type Props = {

const GpsModal = ({ navigation }: Props) => {
const location = React.useContext(LocationContext);
const {
settings: { coordinateSystem },
} = React.useContext(SettingsContext);
const { formatMessage: t } = useIntl();
const coordinateMessage = () => {
switch (coordinateSystem) {
case "dd":
return <FormattedMessage {...m.locationDD} />;
case "utm":
return <FormattedMessage {...m.locationUTM} />;
case "dms":
return <FormattedMessage {...m.locationDMS} />;
default:
return <FormattedMessage {...m.locationUTM} />;
}
};

return (
<ScrollView style={styles.container} testID="gpsScreenScrollView">
Expand All @@ -76,13 +108,12 @@ const GpsModal = ({ navigation }: Props) => {
/>
{location.position && (
<>
<Text style={styles.sectionTitle}>
<FormattedMessage {...m.locationUTM} />
</Text>
<Text style={styles.sectionTitle}>{coordinateMessage()}</Text>
<Text style={styles.rowValue}>
<FormattedCoords
lon={location.position.coords.longitude}
lat={location.position.coords.latitude}
format={coordinateSystem}
/>
</Text>
<Text style={styles.sectionTitle}>
Expand Down
7 changes: 6 additions & 1 deletion src/frontend/screens/Observation/ObservationShare.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
import { getProp } from "../../lib/utils";
import type { PresetWithFields } from "../../context/ConfigContext";
import type { Observation } from "../../context/ObservationsContext";
import SettingsContext from "../../context/SettingsContext";

const m = defineMessages({
alertSubject: {
Expand Down Expand Up @@ -52,6 +53,10 @@ export const ShareSubject = ({ observation, preset }: ShareMessageProps) => {

export const ShareMessage = ({ observation, preset }: ShareMessageProps) => {
const { formatMessage: t } = useIntl();
const {
settings: { coordinateSystem },
} = React.useContext(SettingsContext);

const { value } = observation;
const { lon, lat } = value;

Expand Down Expand Up @@ -81,7 +86,7 @@ export const ShareMessage = ({ observation, preset }: ShareMessageProps) => {
<FormattedObservationDate observation={observation} variant="long" />
<br />
{lon != null && lat != null ? (
<FormattedCoords lat={lat} lon={lon} />
<FormattedCoords format={coordinateSystem} lat={lat} lon={lon} />
) : null}
</p>
{value.tags.notes ? <p>{value.tags.notes}</p> : null}
Expand Down
10 changes: 9 additions & 1 deletion src/frontend/screens/Observation/ObservationView.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
} from "../../lib/styles";
import { TouchableOpacity } from "../../sharedComponents/Touchables";
import type { PresetWithFields } from "../../context/ConfigContext";
import SettingsContext from "../../context/SettingsContext";
import type { Observation } from "../../context/ObservationsContext";
import useMapStyle from "../../hooks/useMapStyle";
import useDeviceId from "../../hooks/useDeviceId";
Expand Down Expand Up @@ -125,6 +126,9 @@ const ObservationView = ({
onPressDelete,
}: ODVProps) => {
const intl = useIntl();
const {
settings: { coordinateSystem },
} = React.useContext(SettingsContext);
const { formatMessage: t } = intl;
const deviceId = useDeviceId();
const isMine = deviceId === observation.value.deviceId;
Expand Down Expand Up @@ -173,7 +177,11 @@ const ObservationView = ({
<View style={styles.coords}>
<View style={styles.coordsPointer} />
<Text style={styles.positionText}>
<FormattedCoords lon={lon} lat={lat} />
<FormattedCoords
format={coordinateSystem}
lon={lon}
lat={lat}
/>
</Text>
</View>
<InsetMapView lat={lat} lon={lon} />
Expand Down
Loading