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

Use Geolocation API to center map by current location on load in certain cases #378

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
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
30 changes: 30 additions & 0 deletions client/src/pages/Map/Map.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,18 @@ const unsupportedError = (
</Box>
);

// If browser supports geolocation and there is no hash param on page load,
// let's check if we have geo permissions and use that to recenter map if so
let geoPermissionsPromise = Promise.resolve('unsupported');
if (
'geolocation' in navigator &&
!new URLSearchParams(window.location.hash.slice(1)).get('pos')
) {
geoPermissionsPromise = navigator.permissions.query({ name: 'geolocation' });
} else if ('geolocation' in navigator) {
Promise.resolve('denied');
}

function createPopupHTML({ common, scientific }) {
const commonString = common ? `<h4>${common}</h4>` : '';
const scientificString =
Expand Down Expand Up @@ -99,6 +111,24 @@ export default function Map({
}
}, [selectionEnabled]);

useEffect(() => {
const recenterOnLocation = async () => {
const result = await geoPermissionsPromise;
// Will return ['granted', 'prompt', 'denied', 'unsupported']
if (result.state === 'granted') {
navigator.geolocation.getCurrentPosition((position) => {
map.flyTo({
center: [position.coords.longitude, position.coords.latitude],
});
});
}
};

if (map) {
recenterOnLocation();
}
}, [map]);

useEffect(() => {
if (isMapboxSupported && !map && containerRef.current) {
const mapboxMap = new mapboxgl.Map({
Expand Down