For Location we will use geolocation api Its super simple In this code we used navigator.geolocation.getCurrentPosition to know the users location Save and run the html code It will show the latitude and longitude. Which indicates the exact location in the world map.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
let userslatitude;
let userslongitude;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
userslatitude = position.coords.latitude;
userslongitude = position.coords.longitude;
alert('latitude: ' + userslatitude + ', longitude: ' + userslongitude);
});
}
</script>
</body>
</html>
In the next example we add button to add more control when calling the geolocation API
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>GPS</h1>
<button onclick="showLocation()">Show Location</button>
<p id="locationParagraph"></p>
<script>
let userslatitude;
let userslongitude;
function showLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
userslatitude = position.coords.latitude;
userslongitude = position.coords.longitude;
document.getElementById('locationParagraph').innerText = 'Latitude: ' + userslatitude + ', Longitude: ' + userslongitude;
});
} else {
alert('Geolocation is not supported by your browser');
}
}
</script>
</body>
</html>
You can also test this code
GPS
If you click on show location. It will show the latitude and longitude. With this information we can get the exact location.
Knowing the location just a number, that is not enough. We need to know the place name or the visualization with map. There is a wonderful free option for this. OpenStreetMap. In the next example we will specifically show the location name.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<button onclick="getLocation()">Get Location</button>
<p id="locationName"></p>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getAddress);
} else {
alert('Geolocation is not supported by your browser');
}
}
function getAddress(position) {
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
let apiUrl = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}&zoom=18&addressdetails=1`;
fetch(apiUrl)
.then(response => response.json())
.then(data => {
let locationName = data.display_name;
document.getElementById('locationName').innerText = 'Location: ' + locationName;
})
.catch(error => {
console.log('Error:', error);
});
}
</script>
</body>
</html>
Run the html code locally or here is demonstration with the Get location button That will show the location name from the latitude and longitude.
Location is great. But users will feel more comfortable if we can visualize this in map In the next example we will use leaflet library and OpenStreetMap api to show the location in the map.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<style>
#map {
height: 400px;
width:400px;
}
button {
padding: 10px 20px;
border: 2px solid #333;
background-color: transparent;
color: #333;
font-size: 16px;
text-transform: uppercase;
cursor: pointer;
transition: all 0.3s ease;
outline: none;
}
button:hover {
background-color: #333;
color: #fff;
}
</style>
</head>
<body>
<button onclick="getLocation()">Get Location</button>
<p id="locationName"></p>
<div id="map"></div>
<script>
let map;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getAddress);
} else {
alert('Geolocation is not supported by your browser');
}
}
function getAddress(position) {
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
let apiUrl = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}&zoom=18&addressdetails=1`;
fetch(apiUrl)
.then(response => response.json())
.then(data => {
let locationName = data.display_name;
document.getElementById('locationName').innerText = 'Location: ' + locationName;
displayMap(latitude, longitude);
})
.catch(error => {
console.log('Error:', error);
});
}
function displayMap(latitude, longitude) {
var mapElement = document.getElementById('map');
var map;
map = L.map('map', {
minZoom: 1,
}).setView([latitude, longitude], 14);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
var url = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}`;
fetch(url)
.then(response => response.json())
.then(data => {
let locationText = data.display_name;
L.circle([latitude, longitude], {
color: 'red',
fillOpacity: 0.2,
radius: 3000
}).addTo(map);
L.marker([latitude, longitude])
.addTo(map)
.bindPopup(locationText)
.openPopup();
var bounds = L.latLngBounds([[latitude, longitude]]);
map.fitBounds(bounds);
})
.catch(error => {
console.error('Error fetching data:', error);
});
}
</script>
</body>
</html>
Customize the code on your needs. I first applied the GPS feature in my video calling project. I hope it will be helpful for you too. One thing to consider . Sometimes the map shows inaccurate result. Also Open street Map has standard rate limit. (The standard limit is 1 request per second)
You can get the example code from github for practice github
For performance and visual and location information accuracy you may use google maps Embed api.