vue3-google-address-autocomplete
Version:
A Vue 3 component for Google address autocomplete
84 lines (83 loc) • 2.08 kB
JavaScript
import { defineComponent as i, ref as d, onMounted as u, nextTick as m, onBeforeUnmount as f, openBlock as g, createElementBlock as w, normalizeClass as _ } from "vue";
const h = i({
props: {
modelValue: {
type: String,
default: ""
},
apiKey: {
type: String,
required: !0
},
placeholder: {
type: String,
default: ""
},
class: {
type: String,
default: ""
}
},
emits: ["update:modelValue", "callback"],
setup(e, { emit: a }) {
const t = d(null);
let l = !1;
function n() {
return new Promise((o, c) => {
if (window.google && window.google.maps && window.google.maps.places)
o();
else if (!l) {
l = !0;
const p = document.createElement("script");
p.setAttribute(
"src",
`https://maps.googleapis.com/maps/api/js?key=${e.apiKey}&libraries=places&callback=initMap`
), window.initMap = () => {
o();
}, p.onerror = (s) => {
c(s);
}, document.head.appendChild(p);
}
});
}
u(async () => {
try {
await n(), await m(), r();
} catch (o) {
console.error("Failed to load Google Maps API", o);
}
}), f(() => {
delete window.initMap;
});
function r() {
if (t.value) {
const o = new google.maps.places.Autocomplete(
t.value
);
o.addListener("place_changed", () => {
const c = o.getPlace();
a("update:modelValue", c.formatted_address), a("callback", c);
});
}
}
return { autocompleteInput: t };
}
}), y = (e, a) => {
const t = e.__vccOpts || e;
for (const [l, n] of a)
t[l] = n;
return t;
}, k = ["placeholder"];
function M(e, a, t, l, n, r) {
return g(), w("input", {
ref: "autocompleteInput",
type: "text",
autocomplete: "off",
placeholder: e.placeholder,
class: _(e.class)
}, null, 10, k);
}
const S = /* @__PURE__ */ y(h, [["render", M]]);
export {
S as default
};