vue3-google-address-autocomplete
Version:
A Vue 3 component for Google address autocomplete
2 lines (1 loc) • 1.59 kB
JavaScript
(function(e,l){typeof exports=="object"&&typeof module<"u"?module.exports=l(require("vue")):typeof define=="function"&&define.amd?define(["vue"],l):(e=typeof globalThis<"u"?globalThis:e||self,e.GoogleAddressAutocomplete=l(e.Vue))})(this,function(e){"use strict";const l=e.defineComponent({props:{modelValue:{type:String,default:""},apiKey:{type:String,required:!0},placeholder:{type:String,default:""},class:{type:String,default:""}},emits:["update:modelValue","callback"],setup(t,{emit:a}){const o=e.ref(null);let s=!1;function p(){return new Promise((n,c)=>{if(window.google&&window.google.maps&&window.google.maps.places)n();else if(!s){s=!0;const r=document.createElement("script");r.setAttribute("src",`https://maps.googleapis.com/maps/api/js?key=${t.apiKey}&libraries=places&callback=initMap`),window.initMap=()=>{n()},r.onerror=m=>{c(m)},document.head.appendChild(r)}})}e.onMounted(async()=>{try{await p(),await e.nextTick(),i()}catch(n){console.error("Failed to load Google Maps API",n)}}),e.onBeforeUnmount(()=>{delete window.initMap});function i(){if(o.value){const n=new google.maps.places.Autocomplete(o.value);n.addListener("place_changed",()=>{const c=n.getPlace();a("update:modelValue",c.formatted_address),a("callback",c)})}}return{autocompleteInput:o}}}),d=(t,a)=>{const o=t.__vccOpts||t;for(const[s,p]of a)o[s]=p;return o},u=["placeholder"];function f(t,a,o,s,p,i){return e.openBlock(),e.createElementBlock("input",{ref:"autocompleteInput",type:"text",autocomplete:"off",placeholder:t.placeholder,class:e.normalizeClass(t.class)},null,10,u)}return d(l,[["render",f]])});