DEV Community

Cover image for Vue.js + Google Places: Autocomplete Multiple Input Fields
Raja Tamil
Raja Tamil

Posted on • Originally published at softauthor.com

Vue.js + Google Places: Autocomplete Multiple Input Fields

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

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"]);
},
Enter fullscreen mode Exit fullscreen mode

alt text

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

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

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]);
    }
}
Enter fullscreen mode Exit fullscreen mode

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]);
    }
}
Enter fullscreen mode Exit fullscreen mode

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

alt text

There you have it!

Top comments (0)