位置预测和 .getPlace() 使用 Google 地点自动完成的地图加载器在 Vue 中不起作用

Location predictions and .getPlace() using Google Maps loader for Place Autocomplete not working in Vue

我使用 vue cli 启动了一个 Vue 2 应用程序。当我输入地址时,我没有看到下拉列表中出现任何建议。在 newtwork 选项卡中,我看到 AutocompletionService.GetPredictions 呼叫触发并且页面加载时没有错误。

根据我之前的问题,, I was prompted to use the google maps loader,npm,我做了。

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <!-- <HelloWorld msg="Welcome to Your Vue.js App" /> -->
    <input
      id="detailedLocation"
      ref="autocomplete"
      type="text"
      v-model="address"
      @input="locatorInfo"
    />
    <ul>
      <li v-for="(result, i) in searchResults" :key="i">
        {{ result }} // list of all places
      </li>
    </ul>
  </div>
</template>

<script>
import { Loader } from "@googlemaps/js-api-loader";
const loader = new Loader({
  apiKey: "AIzaSyCcm...........",
  version: "weekly",
  libraries: ["places", "map"],
});

export default {
  name: "App",
  data() {
    return {
      info: null,
      searchResults: [],
      address: "",
    };
  },
  async mounted() {
    let location;
    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 input = document.getElementById("detailedLocation");
    const options = {
      types: ["address"], // the error was type: cities
      bounds: defaultBounds,
      fields: ["place_id", "geometry", "name", "address_components"],
    };
    loader
      .load()
      .then((google) => {
        location = new google.maps.places.Autocomplete(input, options);

        location.addListener(
          // document.getElementById("detailedLocation"),
          "place_changed",
          onPlaceChanged
        );
        console.log(location);
      })
      .catch((e) => {
        console.log(e);
        // do something
      });
    const onPlaceChanged = () => {
      const place = location.getPlace();
      console.log(location, place, "LINE 79");

      if (!place.geometry) {
        document.getElementById("detailedLocation").placeholder =
          "Enter a place";
      } else {
        document.getElementById("detailedLocation").innerHTML =
          place.formatted_address;
        console.log(place.formatted_address, "line 60");
      }
    };
  },
  methods: {
    locatorInfo() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position) => {
          console.log(position.coords.latitude, position.coords.longitude);
        });
      }
    },
    printData() {
      this.displaySuggestions();
      console.log(this.$refs["autocomplete"].value);
    },
    displaySuggestions(predictions, status) {
      if (status !== window.google.maps.places.PlacesServiceStatus.OK) {
        this.searchResults = [];
        return;
      }
      this.searchResults = predictions.map(
        (prediction) => prediction.description
      );
    },
  },
};
</script>

输入地址提交后也没有报错。我不确定我做错了什么。我关注了 google 开发者视频,google places autocomplete widget, and closely checked the docs, AutocompleteService Class。如上所述,网络调用是对 AutocompleteService class 而不仅仅是自动完成(因为这是一个小部件)。我的加载程序正在调用自动​​完成的构造函数。为什么是这样?我如何连接它才能工作?

编辑

我加了一个codesandbox and modified the code from defining onPlaceChanged, to an anonymous function as in the docs, docs example

一切正确,错误出在选项对象中。而不是类型:城市,它应该是类型:地址(至少对我来说是这样)。使用 @googlemaps/js-api-loader 效果很好,是在 index.html 中添加脚本标签的绝佳解决方案。对于后面的参考,也可以只使用文档中看到的匿名函数,autocomplete docs example。另外,注意错别字。很容易输入 'AutoComplete' 而不是应该的 'Autocomplete'。 api 加载器的文档非常少,我仍然不确定是否有回调字段。除此之外,这个例子应该会让你继续。