【问题标题】:Google Places API Dropdown does not show upGoogle Places API 下拉菜单未显示
【发布时间】:2020-11-27 19:10:30
【问题描述】:

我正在使用 Python Flask 和 Google Places API 来自动完成地点。我希望我的网站自动完成该地点,然后通过fetch 将其发送到 Flask 服务器。现在,我只想将位置记录到控制台。但是,当我使用 Places API (https://developers.google.com/places/web-service/autocomplete) 实现 API 时,下拉菜单甚至没有出现。这是我的代码的相关sn-p:

<div id="locationField">
  <input
    id="autocomplete"
    placeholder="Enter your address"
    onfocus="geolocate()"
    type="text"
  />
</div>
<script defer
    src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places&callback=initMap">
  let placeSearch;
  let autocomplete;
  function initAutocomplete() {
    // Create the autocomplete object, restricting the search predictions to
    // geographical location types.
    autocomplete = new google.maps.places.Autocomplete(
      document.getElementById("autocomplete"),
      { types: ["geocode"] }
    );
    // Avoid paying for data that you don't need by restricting the set of
    // place fields that are returned to just the address components.
    autocomplete.setFields(["address_component"]);
    // When the user selects an address from the drop-down, populate the
    // address fields in the form.
    autocomplete.addListener("place_changed", getAddress);
  }
  
  function getAddress() {
    console.log(autocomplete.getPlace());
  }
  
  function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition((position) => {
      const geolocation = {
        lat: position.coords.latitude,
        lng: position.coords.longitude,
      };
      const circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy,
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}
</script>

感谢任何帮助。提前谢谢你!

编辑: 我检查了开发工具,发现 2 个 JS 错误:submit:1 Uncaught (in promise) leUncaught ReferenceError: geolocate is not defined at HTMLInputElement.onfocus (submit:76)

【问题讨论】:

    标签: javascript google-maps google-places-api google-places googleplacesautocomplete


    【解决方案1】:

    查看加载 Google Maps JavaScript API 的脚本:

    <script defer
    src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places&callback=initMap">
    

    注意它有以下参数callback=initMap。这意味着一旦完全加载了 Google Maps JavaScript API,它将调用名称为 initMap() 的函数。

    您的代码中不存在此函数。你还有一个名为initAutocomplete()的函数,所以你应该在回调参数中使用这个函数名:

    callback=initAutocomplete.

    编辑:

    此外,您没有正确关闭标签。加载 Maps JavaScript API 的脚本必须使用 &lt;/script&gt; 标记关闭,然后是 &lt;script&gt; 用于定义您的函数的代码部分。 查看解决问题的代码 sn-p。

    <div id="locationField">
      <input
        id="autocomplete"
        placeholder="Enter your address"
        onfocus="geolocate()"
        type="text"
      />
    </div>
    <script defer
        src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&libraries=places&callback=initAutocomplete">
    </script>
    <script>
      let placeSearch;
      let autocomplete;
      function initAutocomplete() {
        // Create the autocomplete object, restricting the search predictions to
        // geographical location types.
        autocomplete = new google.maps.places.Autocomplete(
          document.getElementById("autocomplete"),
          { types: ["geocode"] }
        );
        // Avoid paying for data that you don't need by restricting the set of
        // place fields that are returned to just the address components.
        autocomplete.setFields(["address_component"]);
        // When the user selects an address from the drop-down, populate the
        // address fields in the form.
        autocomplete.addListener("place_changed", getAddress);
      }
      
      function getAddress() {
        console.log(autocomplete.getPlace());
      }
      
      function geolocate() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position) => {
          const geolocation = {
            lat: position.coords.latitude,
            lng: position.coords.longitude,
          };
          const circle = new google.maps.Circle({
            center: geolocation,
            radius: position.coords.accuracy,
          });
          autocomplete.setBounds(circle.getBounds());
        });
      }
    }
    </script>

    希望这能解决您的问题。

    【讨论】:

    • 我更改了回调参数,但它似乎仍然不起作用...&lt;script defer src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&amp;libraries=places&amp;callback=initAutocomplete"&gt;。我什至尝试清除缓存并使用其他浏览器。我还通过在 Google 上加载 src url 来检查 API Key,我得到了一个以window.google = window.google 开头的长代码文件。所以我相信 API KEY 是正确的并且有效。还有其他可能的修复方法吗?
    • 我用在 DevTools 上发现的 2 个错误编辑了问题,这有帮助吗?
    • 我编辑了我的答案并创建了一个代码 sn-p 来修复您的代码。运行 sn-p 以查看它的实际效果。
    • 谢谢!我认为 Javascript 代码应该放在链接到 API 的脚本中,而不是放在另一个脚本中。再次感谢您的帮助!
    猜你喜欢
    • 2017-01-30
    • 2016-10-27
    • 2016-06-22
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多