How do I get an address latitude-longitude using HTML5 Geolocation or Google API?

The HTML5 Geolocation API provides a way to access the user's geographic location, including latitude and longitude coordinates. This requires JavaScript to interact with the browser's geolocation services and can be enhanced with Google's Geocoding API for reverse geocoding (converting coordinates to addresses).

HTML5 Geolocation Syntax

Following is the basic syntax for accessing geolocation −

navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);

Parameters

  • successCallback − Function called when location is successfully retrieved

  • errorCallback − Function called when an error occurs (optional)

  • options − Configuration object for timeout, accuracy, and caching (optional)

Getting Latitude and Longitude with HTML5 Geolocation

Example − Basic Geolocation

Following example demonstrates how to get the user's current latitude and longitude −

<!DOCTYPE html>
<html>
<head>
   <title>HTML5 Geolocation Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Get Your Location</h2>
   <button onclick="getLocation()">Get My Location</button>
   <p id="demo"></p>
   
   <script>
      function getLocation() {
         if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(successFunc, errorFunc);
         } else {
            alert('Geolocation is not supported by this browser.');
         }
      }
      
      function successFunc(position) {
         var latitude = position.coords.latitude;
         var longitude = position.coords.longitude;
         var accuracy = position.coords.accuracy;
         
         document.getElementById("demo").innerHTML = 
            "<strong>Location Found:</strong><br>" +
            "Latitude: " + latitude + "<br>" +
            "Longitude: " + longitude + "<br>" +
            "Accuracy: " + accuracy + " meters";
      }
      
      function errorFunc(error) {
         var errorMessage = "";
         switch(error.code) {
            case error.PERMISSION_DENIED:
               errorMessage = "User denied the request for Geolocation.";
               break;
            case error.POSITION_UNAVAILABLE:
               errorMessage = "Location information is unavailable.";
               break;
            case error.TIMEOUT:
               errorMessage = "The request to get user location timed out.";
               break;
            default:
               errorMessage = "An unknown error occurred.";
               break;
         }
         document.getElementById("demo").innerHTML = "<strong>Error:</strong> " + errorMessage;
      }
   </script>
</body>
</html>

The output displays the user's coordinates when location permission is granted −

Location Found:
Latitude: 40.7128
Longitude: -74.0060
Accuracy: 20 meters

Using Google Geocoding API for Address Conversion

The Google Geocoding API can convert latitude and longitude coordinates into human-readable addresses. This process is called reverse geocoding.

Example − Geolocation with Google Geocoding

Following example gets the user's location and converts it to an address using Google's API −

<!DOCTYPE html>
<html>
<head>
   <title>Geolocation with Address</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Get Location and Address</h2>
   <button onclick="getLocationWithAddress()">Get Location & Address</button>
   <div id="result"></div>
   
   <script>
      function getLocationWithAddress() {
         if (navigator.geolocation) {
            document.getElementById("result").innerHTML = "Getting location...";
            navigator.geolocation.getCurrentPosition(showPosition, showError);
         } else {
            document.getElementById("result").innerHTML = "Geolocation is not supported.";
         }
      }
      
      function showPosition(position) {
         var lat = position.coords.latitude;
         var lon = position.coords.longitude;
         
         // Display coordinates first
         document.getElementById("result").innerHTML = 
            "<strong>Coordinates:</strong><br>" +
            "Latitude: " + lat + "<br>" +
            "Longitude: " + lon + "<br><br>" +
            "Getting address...";
         
         // Get address using Google Geocoding API
         getAddress(lat, lon);
      }
      
      function getAddress(lat, lon) {
         // Note: Replace 'YOUR_API_KEY' with actual Google API key
         var apiKey = 'YOUR_API_KEY';
         var geocodeUrl = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lon}&key=${apiKey}`;
         
         fetch(geocodeUrl)
            .then(response => response.json())
            .then(data => {
               if (data.status === 'OK' && data.results.length > 0) {
                  var address = data.results[0].formatted_address;
                  document.getElementById("result").innerHTML += 
                     "<br><strong>Address:</strong><br>" + address;
               } else {
                  document.getElementById("result").innerHTML += 
                     "<br><strong>Address:</strong> Could not determine address";
               }
            })
            .catch(error => {
               document.getElementById("result").innerHTML += 
                  "<br><strong>Error:</strong> " + error.message;
            });
      }
      
      function showError(error) {
         var errorMsg = "";
         switch(error.code) {
            case error.PERMISSION_DENIED:
               errorMsg = "User denied geolocation request.";
               break;
            case error.POSITION_UNAVAILABLE:
               errorMsg = "Location information unavailable.";
               break;
            case error.TIMEOUT:
               errorMsg = "Location request timed out.";
               break;
            default:
               errorMsg = "Unknown error occurred.";
               break;
         }
         document.getElementById("result").innerHTML = "<strong>Error:</strong> " + errorMsg;
      }
   </script>
</body>
</html>

Note: To use the Google Geocoding API, you need to obtain an API key from the Google Cloud Console and replace YOUR_API_KEY with your actual key.

Enhanced Geolocation with Options

The geolocation API accepts an options parameter to control accuracy, timeout, and caching behavior.

Example − Geolocation with Custom Options

<!DOCTYPE html>
<html>
<head>
   <title>Enhanced Geolocation</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>High Accuracy Location</h2>
   <button onclick="getPreciseLocation()">Get Precise Location</button>
   <div id="location-info"></div>
   
   <script>
      function getPreciseLocation() {
         var options = {
            enableHighAccuracy: true,  // Use GPS if available
            timeout: 10000,           // Wait up to 10 seconds
            maximumAge: 300000        // Accept cached location up to 5 minutes old
         };
         
         if (navigator.geolocation) {
            document.getElementById("location-info").innerHTML = "Acquiring high-accuracy location...";
            navigator.geolocation.getCurrentPosition(displayLocation, handleError, options);
         } else {
            document.getElementById("location-info").innerHTML = "Geolocation not supported.";
         }
      }
      
      function displayLocation(position) {
         var coords = position.coords;
         var timestamp = new Date(position.timestamp);
         
         document.getElementById("location-info").innerHTML = 
            "<h3>Location Details:</h3>" +
            "<strong>Latitude:</strong> " + coords.latitude + "<br>" +
            "<strong>Longitude:</strong> " + coords.longitude + "<br>" +
            "<strong>Accuracy:</strong> " + coords.accuracy + " meters<br>" +
            "<strong>Altitude:</strong> " + (coords.altitude || "N/A") + "<br>" +
            "<strong>Speed:</strong> " + (coords.speed || "N/A") + "<br>" +
            "<strong>Timestamp:</strong> " + timestamp.toLocaleString();
      }
      
      function handleError(error) {
         document.getElementById("location-info").innerHTML = 
            "<strong>Error:</strong> " + error.message;
      }
   </script>
</body>
</html>

The enhanced version provides additional location properties and uses high-accuracy mode for better precision.

Comparison of Methods

Method Accuracy API Key Required Address Support
HTML5 Geolocation Moderate to High No No (coordinates only)
Google Geocoding API High Yes Yes (full addresses)
Combined Approach High Yes (for addresses) Yes

Browser Compatibility

HTML5 Geolocation is supported in all modern browsers including Chrome, Firefox, Safari, Edge, and mobile browsers. However, it requires HTTPS for security on most browsers, and users must grant permission for location access.

Conclusion

HTML5 Geolocation provides an easy way to get latitude and longitude coordinates using JavaScript. For converting coordinates to readable addresses, combine it with Google's Geocoding API. Always handle errors gracefully and respect user privacy by requesting location permissions appropriately.

Updated on: 2026-03-16T21:38:53+05:30

551 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements