Skip to content

Instantly share code, notes, and snippets.

@Prn-Ice
Created November 10, 2023 14:26
Show Gist options
  • Save Prn-Ice/3ba90759399cc229622d28b515b28d66 to your computer and use it in GitHub Desktop.
Save Prn-Ice/3ba90759399cc229622d28b515b28d66 to your computer and use it in GitHub Desktop.

Revisions

  1. Prn-Ice created this gist Nov 10, 2023.
    53 changes: 53 additions & 0 deletions location.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    <!DOCTYPE html>
    <html lang="en">

    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get User Location</title>
    </head>

    <body>
    <h1>User Location</h1>
    <p>Latitude: <span id="latitude"></span></p>
    <p>Longitude: <span id="longitude"></span></p>
    <button id="getLocationBtn">Get Location</button>
    <button id="watchLocationBtn">Watch Location</button>

    <script>
    function getLocation() {
    if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
    } else {
    alert("Geolocation is not supported by this browser.");
    }
    }

    function watchLocation() {
    if (navigator.geolocation) {
    // Watch the user's location continuously
    var watchId = navigator.geolocation.watchPosition(showPosition);

    // Optionally, you can clear the watch by calling navigator.geolocation.clearWatch(watchId);

    // Disable the button after fetching the location to prevent multiple requests
    document.getElementById("watchLocationBtn").disabled = true;
    } else {
    alert("Geolocation is not supported by this browser.");
    }
    }

    function showPosition(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
    document.getElementById("latitude").textContent = latitude;
    document.getElementById("longitude").textContent = longitude;
    }


    document.getElementById("getLocationBtn").addEventListener("click", getLocation);
    document.getElementById("watchLocationBtn").addEventListener("click", watchLocation);
    </script>
    </body>

    </html>