There seems to be no direct way to maintain the visual appearance of v-autocomplete
while using only google.maps.places.Autocomplete
. In order to achieve this, I have wrapped the getPlacePredictions()
method of the API - which is not a component - and instead called it from the Autocomplete Service:
PlacesUtils.js
/* global google */
const GetSuggestions = async searchText => {
let result
try {
const rawResult = await searchLocation(searchText)
result = rawResult.map((res) => {
return {
id: res.place_id,
value: res.description
}
})
} catch (err) {
console.log('An error occurred', err)
result = null
}
return result
}
// Auxiliary functions
// wrapping google api's callback in an async function
const searchLocation = async val => {
let promise = await new Promise((resolve, reject) => {
var displaySuggestions = (predictions, status) => {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
reject(status)
}
resolve(predictions)
}
var service = new google.maps.places.AutocompleteService()
service.getPlacePredictions({
input: val,
types: ['geocode']
},
displaySuggestions)
}).catch(function (err) { throw err })
return promise
}
export { GetSuggestions }
Next, by adding a watch
for the model of v-autocomplete
, I invoke this method whenever the user makes changes:
Place.vue
<template>
<v-layout row justify-center>
<!-- ... -->
<v-autocomplete
label="Location"
v-model="autocompleteLocationModel"
:items="locationFoundItems"
:search-input.sync="locationSearchText"
item-text="value"
item-value="id"
hide-no-data
return-object
>
</v-autocomplete>
<!-- ... -->
</v-layout>
</template>
<script>
/* eslint handle-callback-err: "warn" */
import { GetSuggestions } from '@/utils/PlaceUtils'
export default {
data () {
return {
autocompleteLocationModel: null,
locationSearchText: null,
locationEntries: []
}
},
computed: {
locationFoundItems () {
return this.locationEntries
}
},
watch: {
locationSearchText (newVal) {
var _vue = this
// Do not search if less than 3 characters typed
if (!newVal || newVal.length <= 3) return
// Call the method mentioned earlier here
GetSuggestions(newVal)
.then(function (res) {
_vue.locationEntries = res
})
.catch(function (err) {
// error handling logic goes here
})
}
}
// ...
}
</script>