【问题标题】:How can I restrict the Google Maps Places Library's Autocomplete to suggestions of only one city's places?如何将 Google Maps Places Library 的自动完成功能限制为仅推荐一个城市的地点?
【发布时间】:2012-05-25 02:47:21
【问题描述】:

我目前正在使用给定的代码,但这只会将建议限制在一个国家/地区。 我见过一种实现,但它使用 jQuery,我想不使用 jQuery 来实现。

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

【问题讨论】:

    标签: google-maps google-maps-api-3 autocomplete google-places-api


    【解决方案1】:

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

    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

    autocomplete.bindTo('bounds', map);
    

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

    autocomplete.setBounds( someOtherBounds );
    

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

    最后,这并没有真正完全地将Autocomplete 限制在城市范围内,但它会尽可能地达到您希望的结果。

    【讨论】:

    • hittheroad.ie 仅在爱尔兰允许自动完成,没有其他建议。这怎么可能?
    • 抱歉这个愚蠢的问题,但是我如何找到一个国家特定城市的界限?
    • @SiddharthAjmera:这并不傻,但是如果您:打开一个新问题,提供有关您要实现的目标的更多详细信息,包括当前代码的示例,以及解释为什么该代码不起作用。
    • 用于自动完成地理边界的 javascript sdk 不起作用。你能指出我的错误吗,或者如果这是贬低 autocomplete = new google.maps.places.Autocomplete( (document.getElementById('loc' )), { types: ['geocode'], bounds: cityBounds, city: [cc], componentRestrictions: { country: 'in', city: cc } });
    • @user3775217:我很乐意查看并尝试提供帮助,但您应该发布一个新问题 - 添加一个新项目作为对现有问题的评论不是它的工作方式在stackoverflow上。我不会让你难过;只是想帮助您了解一切如何运作。
    【解决方案2】:

    我找到了使用 Autocomplete 类按国家/地区限制或限制搜索结果的绝佳示例,即有一个名为 setComponentRestrictions 的方法允许您设置国家/地区(属性),可在此处找到 - https://developers.google.com /maps/documentation/javascript/reference#ComponentRestrictions

    请查看https://code.google.com/p/gmaps-samples-v3/source/browse/trunk/places/2012-may-hangout/autocomplete.html?r=290 获取示例。

    【讨论】:

      【解决方案3】:

      您可以使用多个国家/地区限制

      var options = {
          types: ['(cities)'],
          componentRestrictions: {
              country: ['de','at','ch']
          }
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-03-26
        • 2018-03-24
        • 1970-01-01
        • 1970-01-01
        • 2017-04-12
        • 1970-01-01
        • 2013-10-06
        相关资源
        最近更新 更多