ask browser to allow location
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
using position.coords.latitude & position.coords.longitude we can get exact position in map
useful when adding google map to website or app, also track geolocation
no any other script or file required.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p><strong>Note:</strong> The geolocation property is not supported in IE8 and earlier versions.</p>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
Useful links
1) to get latitude and longitude - https://www.latlong.net/
2) google map API - https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=myMap