Get user location from browser using JavaScript | Solutions By ShriekDj

Shrikant DhayjeShrikant Dhayje
3 min read

So today i am gonna share you some code and details about how to ask the customer there own location and submit in a form using Geolocation API of Web Browser Using JavaScript.

But Before Copying and Pasting the Code Be Aware this feature only work on https protocol not http, but weirdly able to run on localhost.

1. Create an HTML Boilerplate

The HTML Boilerplate Given below.

<!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>Geolocation Form</title>
</head>
<body>
    Hello World
</body>
</html>

2. Create and Form in the body

We will get user location in latitude and longitude format like given below.

<form action="submit_location" method="post">
    <input type="number" name="lat" id="latitude" required>
    <input type="number" name="long" id="longitude" required>

    <label for="user_data">Add User Data</label><br>
    <input type="text" id="user_data" name="user_data" required>

    <button type="submit" value="submit">Submit The Data</button>
</form>

3. Make Latitude and Longitude hidden.

For many times user don't want to see or don't need at all to see the latitude and longitude in front of them. for that case. change the form as follows.

<form action="submit_location" method="post">
    <input type="hidden" name="latitude" id="lat" required>
    <input type="hidden" name="longitude" id="long" required>

    <label for="user_data">Add User Data</label><br>
    <input type="text" id="user_data" name="user_data" required>

    <button type="submit" value="submit">Submit The Data</button>
</form>

3. Create JavaScript Function to Ask Customer for there location and register it.

Given Below Code Contains 3 Types of logic to run as per client interaction.

function myFunction() {
    // this will be called when my function is needed
    console.log('location captured');
}

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, removeForm);
        if ((lat.getAttribute('value') == null) || (long.getAttribute('value') == null)) {

            // code to run if cs disagrees to share the location
            // x.innerHTML = "Form Can't be uploaded Until you provide your current location";
        }

    } else {

        // if client browser does not supports geolocation at all
        // x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    // code to run if cs agrees to share the location
    // x.innerHTML = "Now You Can Submit the Form";
    lat.setAttribute('value', position.coords.latitude);
    long.setAttribute('value', position.coords.longitude);
}

4. Lastly Run the all script function on full page load.

Given Below is code is used when we want to run a function when the page is loaded.

We can directly write function but in some browsers it does not work so we have to run the function in below manner.

window.addEventListener('DOMContentLoaded', (event) => {
    console.log('DOM fully loaded and parsed');
    getLocation();
});

5. Complete HTML Code Given Below.

<!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>Geolocation Form</title>
</head>

<body>
    <form action="submit_location" method="post">
        <input type="hidden" name="latitude" id="lat" required>
        <input type="hidden" name="longitude" id="long" required>

        <label for="user_data">Add User Data</label><br>
        <input type="text" id="user_data" name="user_data" required>

        <button type="submit" value="submit">Submit The Data</button>

        <script>
            function myFunction() {
                // this will be called when my function is needed
                console.log('location captured');
            }

            function getLocation() {
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(showPosition, myFunction);
                    if ((lat.getAttribute('value') == null) || (long.getAttribute('value') == null)) {

                        // code to run if cs disagrees to share the location
                        // x.innerHTML = "Form Can't be uploaded Until you provide your current location";
                    }

                } else {

                    // if client browser does not supports geolocation at all
                    // x.innerHTML = "Geolocation is not supported by this browser.";
                }
            }

            function showPosition(position) {
                // code to run if cs agrees to share the location
                // x.innerHTML = "Now You Can Submit the Form";
                lat.setAttribute('value', position.coords.latitude);
                long.setAttribute('value', position.coords.longitude);
            }

            window.addEventListener('DOMContentLoaded', (event) => {
                console.log('DOM fully loaded and parsed');
                getLocation();
            });
        </script>
    </form>
</body>

</html>

6. Screenshots of How The Form and location notification Looks on Firefox

Location Asked Screenshot

location asked screenshot

Location Captured Screenshot

location captured screenshot

0
Subscribe to my newsletter

Read articles from Shrikant Dhayje directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shrikant Dhayje
Shrikant Dhayje

I'm a software developer from India. :india: I live in Shrirampur City, Maharastra :india: I'm currently learning Back-end Web Developing via Python Programming Language.