Get current location in JavaScript using Geolocation API
Today we’ll show you how to get current geolocation in JavaScript using Geolocation API. In this small article, we will use JavaScript’s Geolocation API to get the latitude and longitude of the visitor’s position.
Let’s create a sample example to get the location using JavaScript. In this example, we will show you the location information in the browser console.
- Random Password Generator using JavaScript
- Check and uncheck all checkboxes using jQuery
- jQuery color picker using bootstrap 3
- How to get query string parameters from URL in JavaScript
Here we will use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator/geolocation" rel="noreferrer noopener" target="_blank">Navigator.geolocation</a>
property to get the Geolocation object. Using this property, we can get the location access of the device to read the latitude and longitude.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
const lat = position.coords.latitude;
const long = position.coords.longitude;
console.log('Latitude: ', lat);
console.log('Longitude: ', long);
}, error => {
console.log('Need access to get location.');
});
}
When executing code in the browser, it will ask permission to allow access to the location.
Output
Let’s use the above code in the sample HTML page and check the logs of the browser console.
index.html
<html>
<head>
<title>Get current Geolocation - Code Premix</title>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
</style>
</head>
<body>
<h3>Get current Geolocation in JavaScript - <a href="https://www.codepremix.com" target="_blank" rel="noopener noreferrer">Code Premix</a></h3>
<b>Turn on Allow apps to access your location.</b>
<script>
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
const lat = position.coords.latitude;
const long = position.coords.longitude;
console.log('Latitude: ', lat);
console.log('Longitude: ', long);
}, error => {
console.log('Need access to get location.');
});
}
</script>
</body>
</html>
Run the above file and check in the output in the browser console.