How To Get Current User’s Location

How To Get Current User's Location
How To Get Current User’s Location

This simple tutorial on How To Get Current User’s Location based on the Latitude and Longitude coordinates. But in order not to compromise privacy, the user permission is required to access its information.

One of the most important features available in HTML5 webs browser is Geolocation API. The Geolocation is considered the most accurate for devices with GPS.

Let’s Start adding a code.

First, Create an HTML file and add the following code. This code will allow the user to click a Button to Get Current User’s Location.

<!DOCTYPE html>
<html>
<body>

<H1>Click to Find my Location.</H1>


<button onclick="findLocation()">Find my Location</button>


<div id="result"></div>






</body>
</html>

Next, Add a Javascript code before closing the body tag. This code will simply check the geolocation available. Then using the getCurrentPositon() Method, it will get the current user location of a user.

<script>
var x = document.getElementById("result");

function findLocation() {
    if (navigator.geolocation) { //check geolocation available 

    	//getting the user current location using getCurrentPosition() method
        navigator.geolocation.getCurrentPosition(DisplayPosition);
    } else { 
        x.innerHTML = "Your browser doesent Geolocation.";
    }
}
//function used to display the current coordinates
function DisplayPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;
}
</script>

 

Finally, Execute the given codes in your browser.

Here’s the full source code used in this application.

<!DOCTYPE html>
<html>
<body>

<H1>Click to Find my Location.</H1>


<button onclick="findLocation()">Find my Location</button>


<div id="result"></div>

<script>
var x = document.getElementById("result");

function findLocation() {
    if (navigator.geolocation) { //check geolocation available 

    	//getting the user current location using getCurrentPosition() method
        navigator.geolocation.getCurrentPosition(DisplayPosition);
    } else { 
        x.innerHTML = "Your browser doesent Geolocation.";
    }
}
//function used to display the current coordinates
function DisplayPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;
}
</script>

</body>
</html>

 

If you have any questions or suggestion please feel free to contact me on our contact page.

The recommended article from the author.

Leave a Comment