Skip to content

Instantly share code, notes, and snippets.

@santiagoaloi
Created July 12, 2023 22:49
Show Gist options
  • Save santiagoaloi/f9372866cd1c2054f2929641584441ab to your computer and use it in GitHub Desktop.
Save santiagoaloi/f9372866cd1c2054f2929641584441ab to your computer and use it in GitHub Desktop.
Google Places - Vuetify Autocomplete SFC Concept + Composable
export default function (link) {
return new Promise((resolve, reject) => {
let googleScript = document.querySelector(`script[src="${link}"]`);
if (!googleScript) {
googleScript = document.createElement('script');
googleScript.src = link;
googleScript.async = true;
document.head.append(googleScript);
googleScript.addEventListener('error', () => {
reject();
})
googleScript.addEventListener('load', () => {
resolve();
})
}
});
}
<template>
<div class="text-center">
<VCardText>
<WelcomeTitleSubtitle subtitle="Where would you prefer to work?" title="Geographics" />
</VCardText>
<VRow>
<VCol cols="12">
<div class="mx-[1px]">
<VAutocomplete
v-model="countries"
:items="allCountries"
chips
item-title="name"
item-value="code"
multiple
placeholder="Countries..."
variant="outlined"
/>
</div>
</VCol>
<VCol cols="12">
<VAutocomplete
v-model="selectedCity"
v-model:search="searchInput"
:items="suggestions"
chips
item-title="description"
item-value="place_id"
label="City"
multiple
variant="outlined"
></VAutocomplete>
</VCol>
</VRow>
</div>
</template>
<script setup>
import { ref, onMounted, watch } from 'vue'
import allCountries from '@/@core/data/countries'
const countries = ref(['SE'])
const selectedCity = ref(null)
const searchInput = ref('')
const suggestions = ref([])
let autocompleteService = null
const link =
'https://maps.googleapis.com/maps/api/js?key=<YourApiKey>&libraries=places'
onMounted(async () => {
await googlePlaces(link)
autocompleteService = new google.maps.places.AutocompleteService()
})
async function fetchSuggestions() {
const request = {
input: searchInput.value,
types: ['locality'],
componentRestrictions: { country: countries.value }
}
autocompleteService.getPlacePredictions(request, (predictions, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
suggestions.value = predictions
}
})
watch(countries, (newValue) => {
if (autocompleteService) {
request.componentRestrictions = { country: newValue }
}
})
}
watch(searchInput, (val) => {
fetchSuggestions()
})
</script>
@santiagoaloi
Copy link
Author

Screenshot 2023-07-13 at 00 50 57

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment