代码之家  ›  专栏  ›  技术社区  ›  mrbob

Google Places Autocomplete不工作,接收到我的函数不是函数的错误

  •  -1
  • mrbob  · 技术社区  · 1 年前

    我正在构建一个包含用户所在城市和省份的表单,并希望使用Google Places自动完成功能。不管怎样,我似乎遇到了错误。

    我在代码中添加了以下脚本:

    <Script src="https://maps.googleapis.com/maps/api/js?key=$MY_KEY&loading=async&libraries=places&callback=initAutocomplete" async defer/>
    

    然后,我将以下函数添加到将使用自动完成的组件中:

    function initAutocomplete () {
            autocomplete = new google.maps.places.Autocomplete(
                document.getElementById("city-and-province"),
                {
                    types: ['establishment'],
                    componentRestrictions: {'country': ['ca']},
                    fields: ['place_id', 'geometry', 'name']
                }
            ) 
        }
    

    我一直收到这样的错误:

    initAutocomplete不是函数。

    如果我从脚本中删除回调,或者如果我尝试创建 useEffect 我没有使用函数,而是得到了错误“谷歌未定义”。

    我很困惑。有人知道问题出在哪里吗?

    0 回复  |  直到 1 年前
        1
  •  0
  •   MrUpsidown    1 年前

    对我来说效果很好。

    Loading the API Adding an Autocomplete widget

    function initMap() {
      const input = document.getElementById("city-and-province");
      const options = {
        types: ['establishment'],
      componentRestrictions: {
        'country': ['ca']
      },
      fields: ['place_id', 'geometry', 'name']
      };
      const autocomplete = new google.maps.places.Autocomplete(input, options);
    }
    <input type="text" id="city-and-province">
    
    <script async
        src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&loading=async&libraries=places&callback=initMap">
    </script>