【问题标题】:Bias google maps autocomplete using location and radius使用位置和半径偏置谷歌地图自动完成
【发布时间】:2014-05-31 14:16:57
【问题描述】:

我正在尝试根据位置和半径 (https://developers.google.com/places/webservice/autocomplete#location_biasing) 偏向 google.maps.places.Autocomplete。以下返回结果,但基于客户端的 IP 而不是我指定的位置。谷歌地图自动完成如何正确地偏向位置? http://jsbin.com/nazufozeyu/1/

var autocomplete = new google.maps.places.Autocomplete(
  document.getElementById('address'), {
    types: ['geocode'],
    radius: 1000,
    location:[47.64864,-122.348927]
  }
);

【问题讨论】:

  • 我猜你的位置格式是问题所在。一般来说,对于 Google Maps Javascript API,您必须使用 google.maps.LatLng 对象,或像 {lat:47.64864,lng:-122.348927} 这样的 latlng 文字

标签: javascript google-maps geolocation


【解决方案1】:

我相信这可以做得更好,但以下方法会起作用。 http://jsbin.com/vetayoreto/1/

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>google.maps.places.Autocomplete</title>  
        <style type="text/css">
            input{width:600px; display:block;}
        </style> 
        <script type="text/javascript" src="//maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false&amp;libraries=places"></script>
    </head>
    <body>
        <input id="input" type="text" value="" />
        <script>
            var center = new google.maps.LatLng(40.7,-74);
            var circle = new google.maps.Circle({
                center: center,
                radius: 10000
            });
            var autocomplete5 = new google.maps.places.Autocomplete(
                document.getElementById('input'),
                {
                    types: ['geocode']
                }
            );
            autocomplete5.setBounds(circle.getBounds());
        </script>
    </body> 
</html> 

【讨论】:

  • 关于如何使用 Circle 和 getBounds() 进行此类调用的好例子。
【解决方案2】:

因此,在检查 API 之后,您提供的位置似乎被忽略了。您可以选择可以做什么,但您需要在 LatLngBounds 类型的选项中提供边界属性。请参阅自动完成选项 API:https://developers.google.com/maps/documentation/javascript/reference#AutocompleteOptions

您可以提供圆形、矩形、折线等,然后从中拉出边界。无论如何,您都需要提供搜索范围,不能只提供一个经纬度点。 @user1032531 提供了一个很好的例子来说明如何用圆圈来做。

如果您想在某个城市/国家/地区进行搜索,可以使用地理编码 API:https://developers.google.com/maps/documentation/geocoding/

像这样调用 API:https://maps.googleapis.com/maps/api/geocode/json?address=Toledo&key=API_KEY,你会得到一些带有“bounds”键的 JSON。获取您的boundbox,并将其传递给places API 调用。

【讨论】:

    猜你喜欢
    • 2012-08-02
    • 2012-02-20
    • 2023-03-31
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    • 2021-09-17
    相关资源
    最近更新 更多