If you’re building a location-based application like a food delivery app etc, it’s obvious that your app will need to get the user’s current location.

At the end of this tutorial, you will have a simple application built similar to the animation below.

To build that, I will first show you how to get the current user’s location in the form of latitude and longitude coordinates using the HTML5 Geolocation API.

Then, you’re going to learn how to convert the latitude and longitude coordinates into an actual human-readable address using Geocoding API from Google.

Finally, I will show you how to add Autocomplete API, which will let users enter their addresses manually when Geolocation API Locator permission was denied or is not supported.

Infographics

STEP #1: Setting Up The Project

I have a simple project setup that has two files index.html and app.js .

<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="utf-8" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.0/semantic.min.css" /> </head> <body> <!-- Your code here --> </body> <script src="https://maps.googleapis.com/maps/api/js?key=*********&libraries=places"> </script> <script src="app.js"></script> </html>

As you can see, I have linked to semantic-ui which will help me save some time on the UI side.

At the bottom of the page after the <body> tag, add Maps API source link and make sure to add your own API Key in there.

🚀 Start learning Vue JS2 with Google Maps API NOW 🚀

Enroll today with our 30-day money-back guarantee. 🔥 1200+ students already enrolled!

4.85 ⭐️⭐️⭐️⭐️⭐️ (44+ ratings) BEST SELLER A Complete Vue JS & Google Maps API Course Build 3 Location-Based Web Apps Like A Pro! offer ends soon

(function () { // All your code goes here })();

STEP #2: 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.

Some older browsers may not support Geolocation API and you can check the browser compatibility here.

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.

(function () { navigator.geolocation.getCurrentPosition(function (position) { console.log(position.coords.latitude) console.log(position.coords.longitude) }, function (error) { console.log("The Locator was denied. :(") }) })();

When running the code above, the user will be prompted, asking permission to access his/her location.

If the user gives permission, the first callback function will have the position object in which you can find latitude and longitude along with other meta information.

If the user denies sharing his/her location, you can capture it inside the error callback function.

Pretty straight forward and simple! 📍

The other option to get the user’s location would be to use Google GeoLocation API, in case you want to explore it.

Now, I need to create an API Key from Google in order to use Geocoding API which will convert geographic coordinates into a human-readable address.

STEP #3: Obtain the API Key

1. Log in to Google Cloud Platform.

2. Then, go to Select a project ▾ drop-down menu, which will open up a dialog box with your existing projects if any. Choose the one that you want to obtain an API key from.

3. Otherwise, create a new project by clicking the NEW PROJECT button at the top right of the dialog box.

4. Once the project is selected, go to the Navigation Menu button at the top left of the page, choose APIs & Services → Credentials

5. Select Create Credentials → API Key, which will open up a dialog box with your API Key. 🔑

That is it, you have it!

STEP #4: Enable Geocoding API

In your Google Cloud Platform Console, go to APIs & Services → Dashboard → Enable APIs & Services at the top and choose Maps JavaScript API from the API Library.

This will open up the Map JavaScript API page and Enable it.

Then, scroll down to More Solutions to explore and choose Geocoding API → Enable it.

👇Like what you’re reading? Check out my full course below 👇

Vue.js + Google Maps API for Beginners

STEP #5: AJAX HTTP Request To Geocoding API

Geocoding API will convert an actual human-readable address to geographic coordinates.

However, what I want is Reverse Geocoding which is the process of converting geographic coordinates into an actual human-readable address.

Here is the base URL for it:

https://maps.googleapis.com/maps/api/geocode/json?latlng="latitude,longitude"&key=************************

It has two query parameters:

latlng : This is where you will be passing latitude and longitude geographic coordinates dynamically separated by a comma. For Example 46.278971,-79.44265039999999

: This is where you will be passing latitude and longitude geographic coordinates dynamically separated by a comma. For Example 46.278971,-79.44265039999999 key: The API key that you have obtained from the previous section.

Inside getCurrentPosition() method, create getUserAddressBy() function by passing position.coords.latitude and position.coords.longitude as arguments.

(function () { navigator.geolocation.getCurrentPosition(function (position) { getUserAddressBy(position.coords.latitude, position.coords.longitude) }, function (error) { console.log("The Locator was denied :(") }) function getUserAddressBy(lat, long) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { var address = JSON.parse(this.responseText) console.log(address.results[0].formatted_address) } }; xhttp.open("GET", "https://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+long+"&key=***", true); xhttp.send(); } })();

Define getUserAddressBy(lat, long) function and make an AJAX call to Geolocation API inside it.

As you see in the URL, I have passed the two parameters lat and long separated by a comma. I also replaced the value of the key query parameter with the API key.

Get the response inside the onreadystatechange() callback function and then convert it into a JSON object.

Some browsers do not allow getting a user’s location, so you will have to move the project into a secured HTTPS connection.

STEP #6: Show User Address To The Input Field

... <body> <section class="container"> <div class="ui icon big input" id="location-input-section"> <input type="text" placeholder="Enter Your Address" id="autocomplete" /> <i aria-hidden="true" class="dot circle outline link icon" id="location-button"></i> </div> </section> </body> ...

To make the input section element centered horizontally and vertically, add the CSS rule for container inside the <head> tags.

<head> ... <style> .container { min-height: 100vh; width: 100%; display: flex; justify-content: center; align-items: center; text-align: center; } </style> </head>

Rather than asking the user’s permission on page load, show the notification when a user clicks the icon on the right side of the input field and show the actual address on it.

Get a DOM reference to the locator-button which is on the right side of the input field.

Attach a click event listener to it with a callback function named locatorButtonPressed inside the init() function.

Move getCurrentPosition() method inside the callback function.

To add and remove the spinner on the right side of the input field, I will be toggling a semantic UI class called loading on the locator-input-section.

Get a DOM reference to it at the top and add the loading class as soon as the location-button is pressed and remove the loading class inside the onreadystatechange() function.

(function () { var locatorSection = document.getElementById("locator-input-section") function init() { var locatorButton = document.getElementById("locator-button"); locatorButton.addEventListener("click", locatorButtonPressed) } function locatorButtonPressed() { locatorSection.classList.add("loading") navigator.geolocation.getCurrentPosition(function (position) { getUserAddressBy(position.coords.latitude, position.coords.longitude) }, function (error) { locatorSection.classList.remove("loading") alert("The Locator was denied :( Please add your address manually") }) } function getUserAddressBy(lat, long) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { var address = JSON.parse(this.responseText) setAddressToInputField(address.results[0].formatted_address) } }; xhttp.open("GET", "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + long + "&key=****", true); xhttp.send(); } function setAddressToInputField(address) { var input = document.getElementById("autocomplete"); input.value = address locatorSection.classList.remove("loading") } init() })();

Invoke setAddressToInputField() by passing the actual address from the AJAX response.

Inside the declaration of setAddressToInputField( ), get a DOM reference to the input field #autocomplete and set the address to it and hide the spinner.

👇Like what you’re reading? Check out my full course below 👇

Vue.js + Google Maps API for Beginners

STEP #7: Enter Address Manually Via AutoComplete API

There are some cases, where the Geolocation API fails to get the location. For example, when a user does not want to share his/her location or the browser is not compatible with the Geolocation API.

In that case, it would be handy to let users get their addresses using AutoComplete API.

Let’s see how to do that.

1. Move the input DOM reference outside of setAddressToInputField() as I will be using it in multiple places.

var input = document.getElementById("autocomplete");

2. Add the following magic line which will enable autocomplete function to the input filed that it is passed into.

var autocomplete = new google.maps.places.Autocomplete(input);

As you can see, I am getting addresses but it’s all over the place. You can easily restrict it to a specific city or country by passing the appropriate coordinates.

To do that, create a LatLngBounds object by passing your city’s geographic coordinates and create a javascript object called options with it.

var defaultBounds = new google.maps.LatLngBounds( new google.maps.LatLng(45.4215296, -75.6971931), ); var options = { bounds: defaultBounds }; var autocomplete = new google.maps.places.Autocomplete(input, options);

Nice 🙂 There you have it! You can find source code here!

What type of application are you working on leveraging Google Maps API? I am looking forward to hearing from you in the comments section below.