Vue.js + Places API: Multiple Autocomplete Input Fields

Google Maps API Vue.js

Sometimes, you would want to add place autocomplete functionality to more than one input field.

The typical example would be finding a travel distance between two locations. In that case, the user will have two input fields with the autocomplete feature enabled on them.

Let’s see how to instantiate the autocomplete object for a single input field.

Place Autocomplete For a Single Input field

In your vue template, define the input field with the ref attribute.

<input type="text" placeholder="Origin" ref="origin" />

Inside the mounted() function, instantiate the Autocomplete object by passing the Input field DOM element using the ref attribute which is more efficient than using the traditional id.

mounted() {
    const autocomplete = new google.maps.places.Autocomplete(this.$refs["origin"]);
},

Pretty straight forward!

If it does not work for you, make sure to add the Places Javascript library to the index.html file.

<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=[YOUR_API_KEY]"></script>

Also, make sure to enable both the Maps JavaScript API & Places API libraries in the Google Cloud Console website if you haven’t done so already.

Place Autocomplete for Multiple Input Fields

Let’s add another input field for destination.

<input type="text" placeholder="Origin" ref="origin" />
<input type="text" placeholder="Destination" ref="destination" />

As you know, when we add a ref attribute with a value to an HTML element in the vue template, it will be added to the this.$refs Javascript object.

Let’s loop through this.$refs object and access input DOM elements dynamically.

mounted() {
    for (let ref in this.$refs) {
       console.log(this.$refs[ref]);
    }
}

Now, instantiate the Autocomplete object for each input field inside the loop.

mounted() {
    for (let ref in this.$refs) {
         const autocomplete = new google.maps.places.Autocomplete(this.$refs[ref]);
    }
}

Attach a Click Event To Autocomplete Objects

To get a user-selected address, we need to attach a place_changed event to the Autocomplete object.

mounted() {
    for (let ref in this.$refs) {
         const autocomplete = new google.maps.places.Autocomplete(this.$refs[ref]);

      autocomplete.addListener("place_changed", () => {
        const place = autocomplete.getPlace();
        console.log(place);
       }
    }
}

There you have it!