How to use HTML5 Geolocation Latitude/Longitude API?

HTML5 Geolocation API lets you share your location with your favorite websites. A JavaScript can capture your latitude and longitude and can be sent to backend web server and do fancy location-aware things like finding local businesses or showing your location on a map.

The geolocation APIs work with a new property of the global navigator object ie. Geolocation object.


You can try to run the following code to find the current location using the Geolocation API, with Latitude and Longitude coordinates

Live Demo

      <script type="text/javascript">
         function showLocation(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            alert("Latitude : " + latitude + " Longitude: " + longitude);
         function errorHandler(err) {
            if(err.code == 1) {
               alert("Error: Access is denied!");
            } else if( err.code == 2) {
               alert("Error: Position is unavailable!");
         function getLocation(){
               // timeout at 60000 milliseconds (60 seconds)
               var options = {timeout:60000};
               (showLocation, errorHandler, options);
            } else{
               alert("Sorry, browser does not support geolocation!");
         <input type="button" onclick="getLocation();" value="Get Location"/>

Updated on: 18-May-2020


Kickstart Your Career

Get certified by completing the course

Get Started