Native web browser behaviour asks you to use an outdated approach to get user geolocation data using callbacks. Since we have the ability to use Promises
and an asynchronous functions, we'll show you an example how to request user's geolocation from a browser using the async/await
functionality.
Note that asynchronous functions from ES7 may introduce performance and/or cross platform runtime compatibility issues, so make sure to do your research.
Let's have a look first how to request user's geolocation:
const getLocation = (showPosition, handleError) => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, handleError);
} else {
// Handle browser support error
}
}
Of course, this code is good enough to work, and if you don't care about callbacks usage. But when you prefer to write more synchronous code, you would need async/await
syntax to handle it.
Let's declare a getCurrentPosition
function, that will return us a Promise
with coordinates. Resolving this promise we will get the coordinates, that came to the callback function earlier.
// utils.js
export function getCurrentPosition(options = {}) {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject, options);
});
}
After creating that reusable function, we can use it as a helper function in different places of our application. To load coordinates from browser we have to implement async
function now:
import { getCurrentPosition } from "utils";
const fetchCoordinates = async () => {
try {
const { coords } = await getCurrentPosition();
cosnt { latitude, longitude } = coords;
// Handle coordinates
} catch (error) {
// Handle error
console.error(error);
}
};
Well done! We just created a synchronous function to get coordinates from browser instead of processing data inside callbacks.
ResourcesClick to expand/shrink