如何将 Google Maps Places Library 的自动完成功能限制为仅提供一个城市地点的建议? [英] How can I restrict the Google Maps Places Library's Autocomplete to suggestions of only one city's places?

查看:25
本文介绍了如何将 Google Maps Places Library 的自动完成功能限制为仅提供一个城市地点的建议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用给定的代码,但这仅将建议限制在一个国家/地区.我见过一个实现,但它使用 jQuery,我想在不使用 jQuery 的情况下实现它.

I am currently using the given code, but this only restricts suggestions to one country. I have seen one implementation but its using jQuery and I want to do it without using jQuery.

var input = document.getElementById('searchTextField');
var options = {
    //types: ['(cities)'],
    componentRestrictions: { country: 'pk' }
};
var autocomplete = new google.maps.places.Autocomplete( input, options );

推荐答案

尝试将 bounds 属性添加到您传递给 Autocomplete<的 options 对象/code> 构造函数,如下代码所示:

Try adding a bounds property to the options object you are passing to the Autocomplete constructor, as shown in this code:

var southWest = new google.maps.LatLng( 25.341233, 68.289986 );
var northEast = new google.maps.LatLng( 25.450715, 68.428345 );
var hyderabadBounds = new google.maps.LatLngBounds( southWest, northEast );

var options = {
    bounds: hyderabadBounds,
    types:  ['establishment [or whatever fits your usage]'],
    componentRestrictions: { country: 'pk' }
};

如果您希望 Autocomplete 边界由地图的当前视口驱动,您可以通过这种方式将地图边界绑定到 Autocomplete:

If you want the Autocomplete bounds to be driven by the current viewport of the map, you can bind the bounds of the map to the Autocomplete this way:

autocomplete.bindTo('bounds', map);

或者,如果它在您的应用程序中效果更好,您还可以选择在必要时显式设置边界:

Or, if it works better in your application, you also have the option to set the bounds explicitly whenever necessary:

autocomplete.setBounds( someOtherBounds );

这可能意味着您创建了一个默认城市,就像我在上面的示例中对海贝拉巴所做的那样.或者您允许您的用户从城市列表中选择开始,然后将地图视口设置为所选城市.如果您从 country 'PK'componentRestrictions 开始,Autocomplete 将建议城市名称,就像您已经在做的那样.您会知道什么最适合您的应用程序.

This may mean that you create a default city, as I did with Hyberabad in the example above. Or that you allow your users to select from a list of cities to start and then set the map viewport to the selected city. The Autocomplete will suggest city names if you start out with just the componentRestrictions of country 'PK' as you are already doing. You will know what works best for your application.

最后,这并没有真正完全地将 Autocomplete 限制在城市中,但它会尽可能接近您希望的结果.

Finally, this does not truly and completely restrict the Autocomplete to just the city, but it will achieve the result you wish as closely as currently possible.

这篇关于如何将 Google Maps Places Library 的自动完成功能限制为仅提供一个城市地点的建议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆