Get User Current Location Using HTML5 Geolocation API JavaScript
Tags: javascript, programming, html
Published: 2021-06-21 13:58:06

{% youtube CgGHqI7P0yU %}

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](https://softauthor.com/wp-content/uploads/2019/09/get-a-users-location-with-javascript-geoloacation-geocoding.gif)

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](https://developer.mozilla.org/en-US/docs/Web/API/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](https://developers.google.com/maps/documentation/geocoding/start?utm_source=google&utm_medium=cpc&utm_campaign=FY18-Q2-global-demandgen-paidsearchonnetworkhouseads-cs-maps_contactsal_saf&utm_content=text-ad-none-none-DEV_c-CRE_315916117661-ADGP_Hybrid%20%7C%20AW%20SEM%20%7C%20SKWS%20~%20Geocoding%20API-KWID_43700039136946174-kwd-301485311002-userloc_9001132&utm_term=KW_geocoding%20api-ST_geocoding%20api&gclid=CjwKCAjwtuLrBRAlEiwAPVcZBml4y3UmIPwTUmSL8UGW4koHaRz8WsAniJTJIOizAhgvmINLn5M59BoCvRIQAvD_BwE) from Google.

Finally, I will show you how to add [Autocomplete API](https://developers.google.com/maps/documentation/places/web-service/autocomplete), which will let users enter their addresses manually when Geolocation API Locator permission was denied or is not supported.

###Infographics

![alt text](https://softauthor.com/wp-content/uploads/2019/09/Get-A-Users-Location-with-Javascript.jpg)

- [Setting Up The Project](https://softauthor.com/get-user-current-location-html5-geolocation-api-javascript/#setting-up-the-project)
- [Get Latitude & Longitude Using Geolocation API](https://softauthor.com/get-user-current-location-html5-geolocation-api-javascript/#get-latitude-longitude-using-geolocation-api)
- [Obtain the API Key](https://softauthor.com/get-user-current-location-html5-geolocation-api-javascript/#obtain-the-google-maps-api-Key)
- [Enable Geocoding API](https://softauthor.com/get-user-current-location-html5-geolocation-api-javascript/#enable-geocoding-api)
- [AJAX HTTP Request To Geocoding API](https://softauthor.com/get-user-current-location-html5-geolocation-api-javascript/#ajax-http-request-to-geocoding-api)
- [Show User Address To The Input Field](https://softauthor.com/get-user-current-location-html5-geolocation-api-javascript/#show-user-address-to-the-input-field)
- [Enter Address Manually Via AutoComplete API](https://softauthor.com/get-user-current-location-html5-geolocation-api-javascript/#enter-address-manually-via-places-autocomplete-api)

###STEP #1: Setting Up The Project

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

```HTML
<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](https://semantic-ui.com) 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.

```JavaScript
(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](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API#browser_compatibility).*

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.

```JavaScript
(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.

![alt text](https://softauthor.com/wp-content/uploads/2019/09/html5-geolocation-api-notification-message.png)

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](https://developers.google.com/maps/documentation/geolocation/overview), 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

{% youtube ASiEw-eakWM %}

- Log in to [Google Cloud Platform](https://accounts.google.com/signin/v2/identifier?service=cloudconsole&passive=1209600&osid=1&continue=https%3A%2F%2Fconsole.cloud.google.com%2Fgoogle%2Fmaps-apis%2Foverview&followup=https%3A%2F%2Fconsole.cloud.google.com%2Fgoogle%2Fmaps-apis%2Foverview&flowName=GlifWebSignIn&flowEntry=ServiceLogin).

![alt text](https://softauthor.com/wp-content/uploads/2019/08/google-cloud-platform-console.png)

- 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](https://softauthor.com/wp-content/uploads/2019/08/select-a-project-google-places-api.png)

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

![alt text](https://softauthor.com/wp-content/uploads/2019/08/create-a-new-project-google-cloud-platform.png)

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

![alt text](https://softauthor.com/wp-content/uploads/2019/08/apiservices-credentials.png)

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

![alt text](https://softauthor.com/wp-content/uploads/2019/08/enable-maps-javascript-api.png)

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

![alt text](https://softauthor.com/wp-content/uploads/2019/09/google-enable-geocoding-api.png)

###STEP #5: AJAX HTTP Request To Geocoding API

[Geocoding API](https://developers.google.com/maps/documentation/geocoding/start?utm_source=google&utm_medium=cpc&utm_campaign=FY18-Q2-global-demandgen-paidsearchonnetworkhouseads-cs-maps_contactsal_saf&utm_content=text-ad-none-none-DEV_c-CRE_315916117661-ADGP_Hybrid%20%7C%20AW%20SEM%20%7C%20SKWS%20~%20Geocoding%20API-KWID_43700039136946174-aud-581578347266%3Akwd-301485311002-userloc_1002367&utm_term=KW_geocoding%20api-ST_geocoding%20api&gclid=EAIaIQobChMI1vGgmKLG5AIVEhgMCh2e7wf9EAAYASAAEgImSPD_BwE) will convert an actual human-readable address to geographic coordinates.

However, what I want is [Reverse Geocoding](https://developers.google.com/maps/documentation/geocoding/start?utm_source=google&utm_medium=cpc&utm_campaign=FY18-Q2-global-demandgen-paidsearchonnetworkhouseads-cs-maps_contactsal_saf&utm_content=text-ad-none-none-DEV_c-CRE_315916117661-ADGP_Hybrid%20%7C%20AW%20SEM%20%7C%20SKWS%20~%20Geocoding%20API-KWID_43700039136946174-aud-581578347266%3Akwd-301485311002-userloc_1002367&utm_term=KW_geocoding%20api-ST_geocoding%20api&gclid=EAIaIQobChMI1vGgmKLG5AIVEhgMCh2e7wf9EAAYASAAEgImSPD_BwE) which is the process of converting geographic coordinates into an actual human-readable address.

[Continue Reading...](https://softauthor.com/get-user-current-location-html5-geolocation-api-javascript/#enter-address-manually-via-places-autocomplete-api)