我正在使用谷歌地點搭建一個簡單的原型,并使用 Vue 映射 api。
在index.html 中,我添加了腳本標簽、庫和 api 密鑰,在網路選項卡中得到 200 回應。
<script src="https://maps.googleapis.com/maps/api/js?key=My-api-key&libraries=places" async defer></script>
在 App.vue 中,我添加了以下內容
<input ref="autocomplete" type="text" />
...
<script>
export default {
name: "App",
data() {
return {
autocomplete: "",
};
},
methods: {},
mounted() {
const center = { lat: 40.84498856765032, lng: -73.71060855293794 };
// Create a bounding box with sides ~10km away from the center point
const defaultBounds = {
north: center.lat 0.1,
south: center.lat - 0.1,
east: center.lng 0.1,
west: center.lng - 0.1,
};
const originAutoComplete = google.maps.places.AutoComplete(
this.$refs["autocomplete"],
{
bounds: defaultBounds,
}
);
originAutoComplete.addListener("place_changed", () => {
console.log(originAutoComplete.getPlace());
});
如何解決此錯誤?有沒有辦法在 App.vue 腳本標簽中初始化它?示例google 開發人員 youtube效果很好,但我想在 Vue 背景關系中實作它。另一個注意事項,我嘗試在 .google 之前添加視窗,沒有骰子。
更新 1
根據您的建議,我在 App.vue 中安裝了googlemaps api 加載程式:
<script>
import { Loader } from "@googlemaps/js-api-loader";
const loader = new Loader({
apiKey: "AIzaSyCcm7G8xLfijhdYDyA6xD-4kNiNP_8GbY8",
version: "weekly",
libraries: ["places"],
});
export default {
name: "App",
data() {
return {
autocomplete: "",
};
},
methods: {
printData() {
console.log(this.$refs["autocomplete"].value);
},
},
async mounted() {
let origin;
const center = { lat:40.84498856765032, lng:-73.71060855293794 };
// Create a bounding box with sides ~10km away from the center point
const defaultBounds = {
north: center.lat 0.1,
south: center.lat - 0.1,
east: center.lng 0.1,
west: center.lng - 0.1,
};
loader
.load()
.then((google) => {
origin = new google.maps.places.Autocomplete(
this.$refs["autocomplete"],
{
types: ["cities"],
defaultBounds,
fields: ["place_id", "geometry", "name"],
}
);
origin.addListener("place_changed", () => {
console.log(origin.getPlace());
});
})
.catch((e) => {
console.log(e);
// do something
});
現在這個問題是選擇的下拉沒有出現。
uj5u.com熱心網友回復:
問題是您的 Vue App JS 在 google maps JS 之前加載。有一些選擇:
- 通過從腳本中洗掉 async 和 defer 來阻止您的應用加載到 Google 地圖上。洗掉 async/defer 后,確保腳本標簽位于您的 Vue JS 之上。
- 合并一個回呼引數或只檢查
window.googlevue 組件中是否存在,并允許 vue 在可用時更新。 - 在 Vue 組件中使用@googlemaps/js-api-loader。請參閱Vue.js 中的“async/await”是否可用“mounted”?對于合并的方式。
我推薦選項3。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/380949.html
