😎 Implement Google Maps Autocomplete API | Vue.js
Tags: vue, javascript
Published: 2020-10-29 10:22:27

This tutorial explains how you can easily implement a **Places Autocomplete Service** by **Google Maps API** in `vue.js`

> NOTE: the picture is fancy because I use VUETIFY. This tutorial just explains how Google Places API work, with no CSS! 😐

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/7ajjfzv0gk7ir8qoc3md.png)


[Checkout this video for a demo](https://www.youtube.com/watch?v=HXEC0jy9S2I)

> All we need is a vue component and a plugin called vue-meta (I already use it for SEO)


### First let’s create a file called `Places.vue`
```
// Places.vue

<template>
  <div>
    <input type="text" v-model="location">
    <ul>
      <li v-for="(result, i) in searchResults" :key="i">
        {{ result }} // list of all places
      </li>
    </ul>
  </div>
</template>
```
Now add a `script` tag in the same file and add the following -

```
// Places.vue

<script>
  export default {
    data: () => ({
      location: '',
      searchResults: [],
      service: null // will reveal this later 🕵️
    })
  }
</script>

```
Install [vue-meta](https://www.npmjs.com/package/vue-meta) plugin — the documentation is very easy and the plugin is installed like any other vue plugin.

Putting the `metaInfo hook` in Places.vue -

```
// Places.vue

<script>
  export default {
    data, // already wrote above
    metaInfo () {
      return {
        script: [{
          src: `https://maps.googleapis.com/maps/api/js?key=<YOUR_API_KEY>&libraries=places`,
          async: true,
          defer: true,
          callback: () => this.MapsInit() // will declare it in methods
        }]
      }
    }
  }
</script>

```

So the reason I used metaInfo here is because we can -
1. **Download external JS** files on the go, only when the component is rendered.
2. It gives us the power of the **callback function**, called when the JS file is downloaded! — 😎

Now let’s move ahead and create the most awaited `methods` hook -

```
// Places.vue

<script>
  export default {
    data // defined already,
    metaInfo // defined already,

    methods: {
      MapsInit () {
        this.service = new window.google.maps.places.AutocompleteService()
      },
      displaySuggestions (predictions, status) {
        if (status !== window.google.maps.places.PlacesServiceStatus.OK) {
          this.searchResults = []
          return
        }
        this.searchResults = predictions.map(prediction => prediction.description) 
      }
    }

  }
</script>

```
---

Let's see what these functions **MapsInit** and **displaySuggestions** do.
> **_MapInit()_** - the function that is called when the JS file is loaded.

In this we use a google places service called - _AutocompleteService (Don't bother right now! Check google documentation if you can't live without it 🤷)._

we assign this AutocompleteService() to our data property **'service'** so that we can use it again later.

> **_displaySuggestions(predictions, status)_** - explained a little later.

And this is the last piece of the puzzle. The `watcher` on the `location` property

```
// Places.vue

<script>
  export default {
    data // already defined,
    methods // already defined,
    metaInfo // already defined,
    // the magical part
    watch: {
      location (newValue) {
        if (newValue) {
          this.service.getPlacePredictions({
            input: this.location,
            types: ['(cities)']
          }, this.displaySuggestions)
        }
      }
    }
  }
</script>
```
So, whatever you type in the input field changes the **location** property, and whenever the location property is changed, a **getPlacePredictions** function is called that is attached to the **service** property.

**getPlacePredictions** receives two parameters-

1. An Object that has many things but we only use **input** and **types** here-
a. **input** - the query to be predicted (`this.locations` in our case).
b. **types** - the type of result.

2. the callback function we declared above in methods hook which is - **displaySuggestions**.

All done!

If you enjoyed reading this and found it a little helpful,
[**Consider Buying me a coffee?**](https://www.buymeacoffee.com/arora)