Google 地点自动完成 API 错误,"google is not defined"

Google Places Autocomplete API error, "google is not defined"

我正在使用 Vue 使用 google 地点和地图 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 developers youtube 示例效果很好,但我想在 Vue 上下文中实现它。 另一个注意事项,我尝试在 .google 之前添加 window,没有骰子。

更新 1

根据您的建议,我安装了 googlemaps api loader 并在 App.vue:

 <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
     });

现在这个问题是选择的下拉列表没有出现。

问题是您的 Vue App JS 在 google maps JS 之前加载。有一些选项:

  1. 通过从脚本中删除异步和延迟来阻止您的应用在 Google 地图上加载。删除 async/defer.
  2. 后,确保脚本标签位于 Vue JS 上方
  3. 合并一个回调参数或只检查 window.google 在你的 vue 组件中是否存在,并允许 vue 在可用时更新。
  4. 使用 @googlemaps/js-api-loader in the Vue component. See 了解合并方式。

我推荐选项 3。