User in specific Area
by scurrilus
JavaScript
// Use Geolocation from Browser
// Coordinates of the center of Berlin
const berlinLatitude = 52.52;
const berlinLongitude = 13.405;// Radius of the circular area (in kilometers)
const areaRadius = 15; // Adjust this according to the desired range// Function to calculate the distance between two points using Haversine formula
if ("geolocation" in navigator) {
// Get the current position
navigator.geolocation.getCurrentPosition(function(position) {
// Get the latitude and longitude from the position object
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
// Do something with the latitude and longitude
console.log("Latitude: " + latitude + ", Longitude: " + longitude);
// User Location
const userLatitude = latitude; // User's latitude
const userLongitude = longitude; // User's longitude
if (isInArea(userLatitude, userLongitude)) {
const message = `User is within the specified area (Berlin). userLatitude: ${userLatitude}, userLongitude: ${userLongitude}, berlinLatitude: ${berlinLatitude}, berlinLongitude: ${berlinLongitude}, areaRadius: ${areaRadius} Km`
console.log(message);
alert(message)
} else {
const message = `User is outside the specified area. userLatitude: ${userLatitude}, userLongitude: ${userLongitude}, berlinLatitude: ${berlinLatitude}, berlinLongitude: ${berlinLongitude}, areaRadius: ${areaRadius} Km`
console.log(message);
alert(message)
}
}, function(error) {
// Handle any errors that occur when trying to get the user's location
switch(error.code) {
case error.PERMISSION_DENIED:
console.log("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
console.log("Location information is unavailable.");
break;
case error.TIMEOUT:
console.log("The request to get user location timed out.");
break;
...