To get the current location (latitude and longitude) of the user in JavaScript, you can use the Geolocation
API. This API is supported by most modern browsers and enables web applications to access the user’s location information, with the user’s permission.
Here is an example of how to use the Geolocation
API to get the current location of the user:
navigator.geolocation.getCurrentPosition(success, error);
function success(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
console.log(`Your current position is:`);
console.log(`Latitude : ${latitude}`);
console.log(`Longitude: ${longitude}`);
}
function error(error) {
console.error(`Error: ${error.message}`);
}
This code calls the getCurrentPosition()
method of the geolocation
object, and passes two callback functions as arguments: success
and error
. If the location information is successfully obtained, the success
function will be called with a position
object that contains the latitude and longitude of the user’s current location. If an error occurs, the error
function will be called with an error
object that contains information about the error.
Note that the getCurrentPosition()
method may prompt the user for permission to access their location information. The user must grant this permission for the getCurrentPosition()
method to succeed.