Accessing location in browser

I want to implement a location dependent web application, is there any way of getting access to the users location in the browser?
2 answers

Use the following javascript snippet to access the Users location.

var x = document.getElementById("pos"); function getLocation() {
if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation not enabled.";
} }

function processPosition(position) {
x.innerHTML = "Lat: " +
position.coords.latitude + "<br>Long: " +
position.coords.longitude;
}

By navigator.geolocation the user will be asked for permission to share the location. navigator.geolocation.getCurrentPosition(showPosition) retrieves the location and passes it to the callback function showposition. In the position.coords object lat and long can be accessed, displayed or sent to a server via REST.

Comments

I had the same problem that I was looking for the current longitude and latitude when developing an application. This one is a viable solution. I would in addition also suggest to take a look at https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_geolocation and https://www.w3schools.com/html/html5_geolocation.asp if someone faces this problem as well and likes an interactive tutorial.

Cordula Thekla ... - Mon, 11/25/2019 - 22:40 :::