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.
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment