How to get User Location using JavaScript

How to get User Location using JavaScript
August 02, 2021

If you are building an eCommerce app or delivery app you will need to get user location to get their address. JavaScript provides us feature to get user location using GeoLocation API.

For privacy purposes, it asks the user permission to allow the browser to access the location.

navigator.geolocation is accessed via navigator.geolocation will cause user browsers to ask for permission. If they accept, then the browser will use the best available functionality on the device to access this information(for Example GPS)

We can access user location using 2 ways:

  1. Geolocation.getCurrentPosition() : To get user current location
  2. Geolocation.watchPosition(): Registers a handler function that will be called automatically each time the position of the device changes, returning the updated location. For example, when the delivery boy delivers the food we can get his real-time location.

Here we are using getCurrentPosition() to get user location

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Get User Location</title>
</head><body><div><h1>Current Position</h1></div><div><h2>Latitude: <span id="latitude"></span></h2></div><div><h2>Longitude: <span id="longitude"></span></h2></div><div><h2>Range: <span id="range"></span> meters.</h2></div></body><script>const options = {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
        };

        function success(pos) {
            const coords = pos.coords;

            document.querySelector("#latitude").innerHTML = coords.latitude;
            document.querySelector("#longitude").innerHTML = coords.longitude;
            document.querySelector("#range").innerHTML = coords.accuracy;
        }

        function error(err) {
            console.warn(`ERROR(${err.code}): ${err.message}`);
        }

        navigator.geolocation.getCurrentPosition(success, error, options);

    </script>
</html>

In the above example, we have used getCurrentPosition, It takes 3 parameters

  1. Success: It's a callback function and mandatory parameter. When the function gets executed successfully this function gets called.
  2. Error: It's an optional parameter of a callback function, when any error occurs then this function gets called.
  3. Options: This is also an optional parameter that provides options for the retrieval of the position data.

To get the user's current address and location info for a better user experience Google Maps API is a good option.


Resources for You

ChatGPT Guide For Software Developers

Learn to use ChatGPT to stay ahead of competition

Front-End Developer Interview Kit

Today, Start preparing to get your dream job!

JavaScript Developer Kit

Start your JavaScript journey today!

Master JavaScript by Solving Daily Challenges

Challenge Yourself Daily: Advance Your JavaScript Skills and Career

View Challenges

Newsletter for Developers!

Join our newsletter to get important Web Development and Technology Updates