【问题标题】:Autocomplete only city name List using Google Maps API使用 Google Maps API 仅自动完成城市名称列表
【发布时间】:2018-03-26 17:29:15
【问题描述】:

我在我的网站上使用以下代码,但它不起作用。问题是什么?我已经包含了用于错误报告的 sn-p。

 <head>
 <script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places" type="text/javascript">
</script>

    <script type="text/javascript">

        function initialize() {
            var options = {
                types: ['(cities)'],
                componentRestrictions: {country: "us"}
            };

            var input = document.getElementById('searchTextField');
            var autocomplete = new google.maps.places.Autocomplete(input , options);
        }

        google.maps.event.addDomListener(window, 'load', initialize);

    </script>

</head>
<body>

    <div class = "row">
        <input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">
    </div>
    </body>

【问题讨论】:

  • 什么不完全有效?您收到任何错误消息吗?
  • 不,我只想要城市名称。

标签: javascript google-maps


【解决方案1】:

从脚本的 src 属性中删除 sensor=false&amp;amp; 并添加您的 API 密钥:

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

以下内容对我有用:

<body>
  <input id="searchTextField" />
  <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
  <script>
    function initialize() {
      var options = {
        types: ['(cities)'],
        componentRestrictions: {
          country: "us"
        }
      };

      var input = document.getElementById('searchTextField');
      var autocomplete = new google.maps.places.Autocomplete(input, options);
    }

    google.maps.event.addDomListener(window, 'load', initialize);
  </script>
</body>

【讨论】:

  • 要使用您的 google API 密钥,您需要同时启用 Google Maps Javascript API 和 Places API。
  • 我们可以在无钥匙系统中进行测试吗?
  • 你的意思是没有 API 密钥?
  • 我刚刚测试了这个,它显示了城市以及州和国家。它不应该只显示城市吗?
  • 抱歉@default123,我有一段时间没有使用 API,所以我不确定。我希望你能弄清楚。
猜你喜欢
  • 2015-03-26
  • 2013-10-06
  • 2015-07-06
  • 1970-01-01
  • 2018-06-04
  • 1970-01-01
  • 2018-03-24
  • 2013-06-03
  • 1970-01-01
相关资源
最近更新 更多