Get current Geolocation using JavaScript
Today we’ll show you how to get current geolocation using JavaScript. 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 geolocation using JavaScript. In this example, we will show you the location information in the browser console.
Example to get current geolocation
Here we will use the Navigator.geolocation
property to get the Geolocation object. Using this property, we can get the location access of the device to read the latitude and longitude.
1 2 3 4 5 6 7 8 9 10 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <!DOCTYPE html> <html> <head> <title>Get current Geolocation - Clue Mediator</title> <style> body { font-family: Arial, Helvetica, sans-serif; } </style> </head> <body> <h3>Get current Geolocation using JavaScript - <a href="https://www.cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Mediator</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 browser.
That’s it for today.
Thank you for reading. Happy Coding..!!