Using the Geolocation API
The Geolocation API for JavaScript provides a mechanism for us to obtain the location of a user. Using the Geolocation API, we can obtain the coordinates of a device that the browser is running on.
The Geolocation API is accessed through a navigator.geolocation
object. When we make a call to the navigator.geolocation
object, the user's browser asks the user for permission to access their location. If they accept, the browser uses the device's positioning hardware, such as the Global Positioning System (GPS) on a smart phone, to determine its location.
Before we attempt to use the navigator.geolocation
object, we should verify that it is supported by the browser. The following code tests for the presence of geolocation support on the browser:
if (navigator.geolocation) { Â Â Â Â var position = await getPositionAsync();Â Â } else { Â Â Â Â throw Error("Geolocation is not supported."); }...