Vue.js + Google Maps API: Getting User Location
Tags: vue, programming
Published: 2021-05-17 12:17:15

{% youtube CgGHqI7P0yU %}

Getting user location is one of the important steps when building an app that relies on street addresses such as a food delivery app for example.

In this article, I am going to quickly cover how to get user location using HTML5 Geolocation and Google’s Geocoding API in the vue.js project.

I assume that you already know [how to get up and running with vue.js project](https://softauthor.com/getting-started-with-vue-js/).

{% youtube 3A57dcz8A8E %}

The folder structure should be like this:

![alt text](https://softauthor.com/wp-content/uploads/2020/01/vue.js-folder-structure.png)

Create a vue component called UserLocation.vue inside the component folder as well as define a route object inside the router/index.js file.

{% youtube lZKZwDcNaUw %}

Inside UserLocation.vue component add the following code.

```HTML
<template>
   <section class="ui two column centered grid">
      <div class="column">
         <form class="ui segment large form">
            <div class="field">
               <div class="ui right icon input large">
                  <input
                     type="text"
                     placeholder="Enter your address"
                     v-model="address"
                     ref="autocomplete"
                     />
                  <i class="dot circle link icon" @click="locatorButtonPressed"></i>
               </div>
            </div>
         </form>
      </div>
   </section>
</template>
```

And the view would look like this.

![alt text](https://softauthor.com/wp-content/uploads/2020/01/Screen-Shot-2020-01-05-at-9.32.47-PM.png)

As you can see, there is an input field with a button on the right, along with a few elements building a grid-based layout using [semantic ui css framework](https://semantic-ui.com/).

I have already added a [semantic ui CDN link](https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css) inside the index.html file.

Also, the input filed has a v-model directive with a property value called address and the side button has a click event callback function called locatorButtonPressed.

Let’s define them.

```JavaScript
<script>
   export default {
     data() {
       return {
         address: "",
       };
     },
     methods: {
       locatorButtonPressed() {
       },
     }
   };
</script>
```

###Get User Geographic Coordinates Using HTML5 Geolocation API

To get the geographic coordinates (latitude and longitude), invoke the getCurrentPosition() method on the navigator object.

```JavaScript
locatorButtonPressed() {
   navigator.geolocation.getCurrentPosition(
      position => {
         console.log(position.coords.latitude);
         console.log(position.coords.longitude);
      },
      error => {
         console.log(error.message);
      },
   )
}
```

GetCurrentPosition() method takes a couple of arguments.

The first one is the success callback function which returns an object that has coordinate data specified in a parameter called position.

The second one is the error callback function.

When getCurrentPosition() method is called, the browser will show the notification where the user can either allow (success callback function) or block (error callback function).

![alt text](https://softauthor.com/wp-content/uploads/2020/01/Screen-Shot-2020-01-06-at-1.03.29-AM.png)

Pretty straightforward.

###Convert coordinates to street address Using Geocoding API

**Geocoding API** is a part of Google Maps API, and it’s the process of converting a street address into geographic coordinates (like latitude and longitude).

But what we want is…**Reverse Geocoding** which is the process of converting geographic coordinates into a human-readable address.

In order to use this API, you need to [obtain a key](https://softauthor.com/get-user-current-location-html5-geolocation-api-javascript/#obtain-the-google-maps-api-Key) from google’s cloud platform and [enable Geocoding API and Maps JavaScript API](https://softauthor.com/get-user-current-location-html5-geolocation-api-javascript/#enable-geocoding-api).

{% youtube ASiEw-eakWM %}

Let’s make an HTTP request to the Geocoding API using Axios HTTP client.

To do that, create another function called getStreetAddressFrom(lat, long) with parameters inside methods object.

```JavaScript
async getStreetAddressFrom(lat, long) {
   try {
      var {
         data
      } = await axios.get(
         "https://maps.googleapis.com/maps/api/geocode/json?latlng=" +
         lat +
         "," +
         long +
         "&key={yourAPIKey}"
      );
      if (data.error_message) {
         console.log(data.error_message)
      } else {
         this.address = data.results[0].formatted_address;
      }
   } catch (error) {
      console.log(error.message);
   }
}
```

As you can see, I use Async and Await pattern in the getStreetAddressFrom() and inside the try block, make an HTTP request to geocoding API using Axios with a couple of query parameters.

The first parameter is latlong and the value of it would be the latitude and longitude that are passed into the function and the API key.

[Continue Reading...](https://softauthor.com/vuejs-geolocation-get-user-location/)