Open In App

How to implement Geolocation in HTML5 ?

Geolocation in HTML5 allows web applications to access a user’s geographical location. This can be incredibly useful for services like mapping, local recommendations, and more.

Approach

Example:






<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
          "width=device-width, initial-scale=1.0">
    <title>Geolocation in HTML5</title>
</head>
  
<body>
    <h1>GeeksforGeeks Geolocation</h1>
  
    <script>
        
        // Check if the browser supports geolocation
        if ("geolocation" in navigator) {
  
            // Get the user's current position
            navigator.geolocation.getCurrentPosition(
                function (position) {
                    let latitude = position.coords.latitude;
                    let longitude = position.coords.longitude;
  
                    document.body.innerHTML += 
                       "<p>Latitude: " + latitude + "</p>";
                    document.body.innerHTML +=
                       "<p>Longitude: " + longitude + "</p>";
                },
                function (error) {
                    console.error("Error getting location: " + error.message);
                }
            );
        } else {
            alert("Geolocation is not supported by your browser");
        }
    </script>
  
</body>
  
</html>

Output:




Article Tags :