How to Get user Current Location from Google Map API using JavaScript?

Getting user current location is essential for many web applications, as it enables personalized experiences and find the products near by the user location. For example, an e-commerce website can display products relevant to the user’s location or provide shipping estimates based on their address.

With JavaScript, developers can use the built-in navigator.geolocation method to retrieve user location data. However, this method has limitations, and there are other ways to get user locations that offer additional features and benefits.

How to get location name from latitude and longitude in JavaScript?

In this tutorial, we will learn, How to get user current location using google maps API with JavaScript, including navigator.geolocationIP geolocation, and other methods. By the end, you will have a solid understanding of the options available and which is best for your needs.

And I have create a project to detect my location with search user location with pincode, area name and city name using google maps API. Project name like, blinkit or many other project web applications project made for same concepts.

Project Directory

 // Get-location-from-google-map-api/
     |__ index.html
     |__ app.js

See also

  1. How to get World map with latitude and longitude
  2. How to get the latitude and longitude in JavaScript?
  3. Get Geolocation from IP address in PHP
  4. How to get Geolocation using PHP-cURL from IP Address

Setting Up the Project

In this project we will create a popup to detect user location & also user search the location with pincode, city name etc. to show products based on location to delivered on estimated time.
How to Get user Current Location from Google Map API using JavaScript

Create HTML File with Bootstrap Modal for Design

In have created a file name index.html. In this html file we will create a bootstrap modal for location detect or a autocomplete search bar using with google map API. We have need to pass a google maps API key.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>How to Get user Current Location from Google Map API using JavaScript?</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<style>
    .separator-text{
        border: 1px solid #d1d3e0;
        padding: 10px;
        border-radius: 50px;
        margin: 10px 12px;
        font-size: 12px;
        font-weight: 500;
    }
    .pac-container {
        z-index: 1051 !important;
    }
    #autocomplete{
        width: 244px;
    }
    #collapse_Navbar, #setLocation{
        margin-left: 50px;
        color: #fff;
    }
</style>

<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
    <a class="navbar-brand" href="#"><b><span class="text-success">Webs</span><span class="text-primary">Codex</span></b></a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapse_Navbar">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="collapse_Navbar">
        <ul class="navbar-nav mr-sm-2">
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" data-toggle="modal" data-target="#locationModal">
                   <span id="setLocation">Select Location</span>
                </a>
            </li>
        </ul>
    </div>
    <form class="form-inline">
       <input class="form-control mr-sm-2" type="text" placeholder="Search your Product">
       <button class="btn btn-info" type="submit">Search</button>
    </form>
</nav>

<div class="modal fade" id="locationModal">
    <div class="modal-dialog modal-md">
        <div class="modal-content">
            <!-- Modal Header -->
            <div class="modal-header">
                <h6 class="modal-title">Welcome to <span class="text-success">WebCodex</span></h6>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <!-- Modal body -->
            <div class="modal-body">
                <form class="form-inline" novalidate="novalidate">
                    <p class="text-dark-50">Please provide your delivery location to see Products</p>
                    <div class="form-group">
                        <button type="button" class="btn btn-success" id="locationBtn">Detect my location</button>
                    </div>
                    <span class="separator-text">
                        <span>OR</span>
                    </span>
                    <div class="form-group">
                        <input type="text" class="form-control" id="autocomplete" placeholder="Search delivery location">
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=YOUR_API_KEY&libraries=places"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>

Get Latitude & Longitude Using Geolocation API

Using the HTML5 Browser Geolocation API, your app will be able to obtain a user’s location in the form of latitude and longitude coordinates upon being granted the permission.

To get the coordinates, all you have to do is to invoke getCurrentPosition() method on the geolocation object. This method will take a few arguments. In this case, I have two callback functions as arguments.

app.js

$(window).on('load', function() {
    $('#locationModal').modal({backdrop: 'static', keyboard: false}, 'show');
});

// GET ID FOR SET USER LOCATION VALUE
var setLocation = document.querySelector("#setLocation"); 

$(document).ready(function () {
    var searchInput = document.getElementById('autocomplete');
    var autocomplete;

    autocomplete = new google.maps.places.Autocomplete((searchInput), {
        types: ['geocode']
    });

    google.maps.event.addListener(autocomplete, 'place_changed', function () {
        var nearPlace = autocomplete.getPlace();
        var latitude  = nearPlace.geometry.location.lat();
        var longitude = nearPlace.geometry.location.lng();
        const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=YOUR_API_KEY`;
        if (url) {
            sendLocation(url);
        }
    });
});

function successLocation(position){
    var latitude  = position.coords.latitude;
    var longitude = position.coords.longitude;
    const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=YOUR_API_KEY`;
    if (url) {
        sendLocation(url);
    }
}

function failLocation(){
    console.log("Unable to retrieve your location");
}

const button = document.getElementById('locationBtn');

button.addEventListener("click", async() => {
    navigator.geolocation.getCurrentPosition(successLocation, failLocation);
});

function sendLocation(url){
    fetch(url)
        .then(response => response.json())
        .then(data => {
        if(data.status == 'OK'){
            const results = data.results;
            let addressArr = [];

            results.forEach((currentElement, index) =>{
                addressArr[index] = currentElement.formatted_address;
            });

            if (addressArr != null) {
                setLocation.textContent = addressArr[0];
                $('#locationModal').modal('hide');
            }
        }else{
            return false;
        }
    }).catch(status => {
        console.log('Request failed.Returned status of', status);
    });
}

How to get current location using Google Map JavaScript API?

Get the user’s location in the form of Latitude and Longitude using getCurrentPoistion() method, which is a part of the HTML5 Geolocation JavaScript API. 5. Inside the success callback function, invoke initMap() with Latitude and Longitude values as arguments.

How to get current user location using JavaScript?

To get a user’s location using JavaScript, you can use the built-in ‘navigator. geolocation’ object, which provides access to the device’s location. Another way is to call IP Geolocation API which returns the user’s location with accuracy up to the city level.

How to get latitude and longitude from google maps?

One of the most common ways to get a user’s latitude and longitude with JavaScript is by using the built-in google maps API. This API provides access to the user’s current location via their device’s GPS or other location sensors. It is supported by most modern web browsers and can be accessed using JavaScript. Full code in below for more understanding.

$(document).ready(function () {
    var searchInput = document.getElementById('autocomplete');
    var autocomplete;
    autocomplete = new google.maps.places.Autocomplete((searchInput), {
        types: ['geocode']
    });
    google.maps.event.addListener(autocomplete, 'place_changed', function () {
        var nearPlace = autocomplete.getPlace();
        var latitude  = nearPlace.geometry.location.lat();
        var longitude = nearPlace.geometry.location.lng();
        const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=YOUR_API_KEY`;
    });
});

You can always support by sharing on social media or recommending my blog to your friends and colleagues.  If you have any suggestions or problems about this tutorial, please comment on the  form below.😊

Leave a Reply

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