谷歌地图自动完成边界不起作用。

7

我想在谷歌地图服务上使用自动完成边界,但没有起作用。

//----autocomplete start
var input = (document.getElementById('searchPlace'));
var defaultBounds = new google.maps.LatLngBounds(
            new google.maps.LatLng(40.518, 29.215),
            new google.maps.LatLng(41.242, 30.370));

var options = {
            bounds:defaultBounds,
            componentRestrictions: { country: 'XX'},};

var autocomplete = new google.maps.places.Autocomplete(input, options);
//----autocomplete end

当我在文本框中输入时,地址会出现在XX国家。但是我想限制搜索到该国的某个地区,例如一个城市边界。但是其他地址却位于这个边界之外。边界没有被考虑进去。


【来自文档】(https://developers.google.com/maps/documentation/javascript/places#places_autocomplete):结果偏向于但不限于这些范围内包含的地点。 - Dr.Molle
5个回答

8
问题在于LatLngBounds期望的是西南和东北角。也称为左下和右上角。
而不是:
var defaultBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(40.518, 29.215),
    new google.maps.LatLng(41.242, 30.370));

应该是:

它应该是:

var defaultBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(41.242, 29.215),
    new google.maps.LatLng(40.518, 30.370));

这在2018年仍然正确。东南x西北不行。 - Alex R
也将strictBounds:true添加到选项中 - sachsom

2

1
上面的链接似乎已经失效了。备用网址为https://developers.google.com/maps/documentation/javascript/places-autocomplete#address_forms。 - Chun Lin
2
现在他们添加了一个名为“strictBounds”的新布尔参数。如果设置为true,则API即使匹配用户输入,也不会返回此区域之外的结果。 - Channel

1
var defaultBounds = new google.maps.LatLngBounds(
                new google.maps.LatLng(17.2916377 ,78.2387067),
                new google.maps.LatLng(17.5608321, 78.6223912)
);

var input = document.getElementById('destination');
var options = {
  bounds: defaultBounds,
  types: ['establishment'],
  strictBounds: true
};

var destination_autocomplete = new google.maps.places.Autocomplete(input, options)

0
也许当您使用边界时,不能使用组件限制...

试试这个...

    //----autocomplete start
    var input = (document.getElementById('searchPlace'));
    var defaultBounds = new google.maps.LatLngBounds(
        new google.maps.LatLng(40.518, 29.215),
        new google.maps.LatLng(41.242, 30.370));

    var options = {
        bounds:defaultBounds
    };
    var autocomplete = new google.maps.places.Autocomplete(input, options);
    //----autocomplete end

-1

Bounds仅适用于地图API,而不适用于地点API。

对于地点API中的位置偏好,您需要在选项中使用位置latlng对象和半径(以米为单位)。

        var myLatlng = new google.maps.LatLng(35.9907,-84.0497);

        var acOptions = {
            location: myLatlng,
            radius: 150000,  // (in meters; this is 150Km)
            types: ['address'],
            componentRestrictions: {country: 'us'}
        };

请注意,这仅会将自动完成结果偏向您输入的半径范围;它并不会限制结果在该半径范围内。

当我尝试使用该方法时,出现“TypeError:a.lat不是函数”的错误。如果Places API不支持Bounds,为什么要在文档中记录它呢? - Longblog
是的,我也有这样的印象,即根据他们的文档,Places API不支持边界。然而,它确实支持。只需在选项中指定“bounds”属性,并仅在指定的边界内查找地址。 - Aleksey Kuznetsov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接