Get user’s Latitude and Longitude in JavaScript – HTML5 Geolocation

In this post, I am going to tell you how to get the latitude and longitude of a user in JavaScript with HTML5 Geolocation.

JavaScript already has navigator geolocation property in HTML5. This property returns a Geolocation object and from the object, we can get user’s latitude and longitude in JavaScript.

Now let’s see it in our example.

Below is the example that will show the latitude and longitude of the user in the console log:


function getLatLon(position) {
  var latitude = position.coords.latitude;
  var longitude = position.coords.longitude;
    console.log("Latitude is "+latitude);
    console.log("Longitude is "+longitude);

In the above code, we have used the Geolocation.getCurrentPosition() method and pass a function inside it. After that, we create the function and write some code inside it.

You can notice that we have passed a parameter in our function which is “position”. It will store the object that contains latitude and longitude coordinates.

Also, read:

We can get the latitude from position.coords.latitude and the longitude from position.coords.longitude which we have did in our code and also store these in variables. Then we pass these variables inside our console log.

Now if we run our code on the browser, we can see it is asking to get the location and if we allow it, we will be able to see the latitude and longitude.

Since the HTML5 Geolocation can compromise the privacy of the user, so it needs to be approved by the user to show the location.

So, we have successfully able to get the latitude and longitude in JavaScript for a user. I hope you enjoyed this post.

One response to “Get user’s Latitude and Longitude in JavaScript – HTML5 Geolocation”


    Thank You For Your Code,
    It is worked and getting logittude and lattitude very well.


Leave a Reply

Your email address will not be published. Required fields are marked *