DEV Community

loading...
Cover image for Get User Current Location Using HTML5 Geolocation API ← JavaScript

Get User Current Location Using HTML5 Geolocation API ← JavaScript

Raja Tamil
Hi I am Raja Tamil • Best Selling Instructor at Udemy • Featured Author @ Medium.com • Founder of SoftAuthor.com (20K visitors/month)
・5 min read

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.

alt text

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

alt text

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>
Enter fullscreen mode Exit fullscreen mode

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.

(function () {
// All your code goes here
})();
Enter fullscreen mode Exit fullscreen mode

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. :(")
    })
})();
Enter fullscreen mode Exit fullscreen mode

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.

alt text

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

IMAGE ALT TEXT HERE

alt text

  • 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.

alt text

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

alt text

  • Once the project is selected, go to the Navigation Menu button at the top left of the page, choose APIs & ServicesCredentials

alt text

  • Select Create CredentialsAPI 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 & ServicesDashboardEnable 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.

alt text

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

alt text

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.

Continue Reading...

Discussion (0)