【问题标题】:limiting google maps autocomplete to UK address only将谷歌地图自动完成限制为仅限英国地址
【发布时间】:2011-08-24 17:07:13
【问题描述】:

我一直在查看以下示例:

http://code.google.com/apis/maps/documentation/javascript/examples/places-autocomplete.html

并决定将其合并到我的网站中。

是否可以将地址限制为仅限英国地址?

【问题讨论】:

    标签: google-maps


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • componentRestrictions: {country: 'gb'} // 仅根据问题限制在英国
    【解决方案2】:

    您不能严格/硬限制它找到的位置,尽管系统中有一个功能请求可以这样做,但您可以对结果设置“偏差”。它作为 google maps bounds 对象的参数传递给 autocomplete 方法。然后,自动完成将有利于这些边界内的位置。但是请注意,由于这不是硬边界,因此如果在边界之外有匹配的搜索,它将返回那些。

    从我的使用情况来看,它似乎有点问题,并且可以进行一些改进 - 特别是考虑到您边界之外的任何东西根本没有被接近度标记,因此边界外一个街区的东西很可能与 1000 英里外的东西一样显示,因此请确保您尝试使边界正常工作。

    【讨论】:

    • 正确的答案是使用componentRestrictions,它允许您将自动完成限制在国家/地区,如Ercan的回答所示。
    • 正确。它于 2012 年 7 月 25 日添加到 API v3.9。截至撰写上述答案时,API 为 v3.6。这是谷歌对上述功能请求的回答。截至今天,v3.12 是交付的最低版本,因此这应该是任何 API 请求的标准。
    【解决方案3】:

    您可以拦截google.maps.places.Autocomplete 功能返回的JSONP 结果,并根据需要使用它们,例如按国家/地区限制并显示结果。

    基本上,您在 head 元素上重新定义 appendChild 方法,然后监视 Google 自动完成代码插入 DOM 以用于 JSONP 的 javascript 元素。添加 javascript 元素后,您将覆盖 Google 定义的 JSONP 回调,以便访问原始自动完成数据。

    这是一个 hack,在这里(我正在使用 jQuery,但这个 hack 没有必要工作):

    //The head element, where the Google Autocomplete code will insert a tag 
    //for a javascript file.
    var head = $('head')[0];  
    //The name of the method the Autocomplete code uses to insert the tag.
    var method = 'appendChild';  
    //The method we will be overriding.
    var originalMethod = head[method];
    
    head[method] = function () {
      if (arguments[0] && arguments[0].src && arguments[0].src.match(/GetPredictions/)) {  //Check that the element is a javascript tag being inserted by Google.
        var callbackMatchObject = (/callback=([^&]+)&|$/).exec(arguments[0].src);  //Regex to extract the name of the callback method that the JSONP will call.
        var searchTermMatchObject = (/\?1s([^&]+)&/).exec(arguments[0].src);  //Regex to extract the search term that was entered by the user.
        var searchTerm = unescape(searchTermMatchObject[1]);
        if (callbackMatchObject && searchTermMatchObject) {
          var names = callbackMatchObject[1].split('.');  //The JSONP callback method is in the form "abc.def" and each time has a different random name.
          var originalCallback = names[0] && names[1] && window[names[0]] && window[names[0]][names[1]];  //Store the original callback method.
          if (originalCallback) {
            var newCallback = function () {  //Define your own JSONP callback
              if (arguments[0] && arguments[0][3]) {
                var data = arguments[0][4];  //Your autocomplete results
                //SUCCESS! - Limit results here and do something with them, such as displaying them in an autocomplete dropdown.
              }
            }
    
            //Add copy all the attributes of the old callback function to the new callback function. This prevents the autocomplete functionality from throwing an error.
            for (name in originalCallback) {  
              newCallback[name] = originalCallback[name];
            }
            window[names[0]][names[1]] = newCallback;  //Override the JSONP callback
          }
        }
    
      //Insert the element into the dom, regardless of whether it was being inserted by Google.
      return originalMethod.apply(this, arguments);
    };
    

    【讨论】:

    • 您的方法似乎非常有趣,并且是唯一一种解决使用 Google 自己的参数限制到一个区域的固有问题的方法。你能发布一个完整的工作 JSFiddle 或类似的内容吗?我很难理解它如何适合 Google 的示例,一个完整的工作示例将是一个很大的帮助。谢谢
    【解决方案4】:

    詹姆斯·阿尔代是正确的:

    http://code.google.com/apis/maps/documentation/javascript/places.html#places_autocomplete

    var defaultBounds = new google.maps.LatLngBounds(
      new google.maps.LatLng(49.00, -13.00),
      new google.maps.LatLng(60.00, 3.00));
    
    var acOptions = {
      bounds: defaultBounds,
      types: ['geocode']
    };
    

    这有点烦人,因为搜索达勒姆会给出北卡罗来纳州达勒姆作为第二个结果,无论您如何说服它接受区域偏差 - 您可以将其设置为视口地图边界,它仍然会尝试建议 NC状态... 可以在此处找到 jQuery 解决方案,但似乎没有提供与 v3 API 一样多的结果。 http://code.google.com/p/geo-autocomplete/

    【讨论】:

      【解决方案5】:

      执行此操作的最佳方法是自己查询地点 api 并将查询的字符串附加到您的国家/地区。或者,当然,使用geo-autocomplete jQuery plugin

      【讨论】:

        【解决方案6】:

        只需将地图的 google 域更改为您所在国家/地区的域,它将仅在您的国家/地区自动搜索:

        所以: http://maps.google.com/maps/api/geocode/xml?address={0}&sensor=false&language=zh

        到: http://maps.google.nl/maps/api/geocode/xml?address={0}&sensor=false&language=nl

        【讨论】:

          【解决方案7】:

          试试这样的。

          // Change Bangalore, India to your cities boundary.
          var bangaloreBounds = new google.maps.LatLngBounds(
              new google.maps.LatLng(12.864162, 77.438610),
              new google.maps.LatLng(13.139807, 77.711895));
          
          var autocomplete = new google.maps.places.Autocomplete(this, {
              bounds: bangaloreBounds,
              strictBounds: true,
          });
          
          autocomplete.addListener('place_changed', function () {
          });
          

          【讨论】:

            【解决方案8】:

            我发现,如果您将地图设置为您想要的大致位置,然后为其设置边界,则搜索首先会找到该区域中的位置。您不要实际显示地图。

            它比先给随机的海外地址更好,设置为国家不起作用。

            自动补全获取latln的代码为:

                <div id="map_canvas"></div>
                    <input type="text" name="location" id="location" placeholder="Type location...">
                    <input type="text" name="loc_latitude" id="latitude">
                    <input type="text" name="loc_longitude" id="longitude">
            
            and the JS is:
            
            $(document).ready(function () {
            
                      var mapOptions = {
                          center: new google.maps.LatLng(52.41041560, -1.5752999),
                          zoom: 13,
                          mapTypeId: google.maps.MapTypeId.ROADMAP
                      };
                      var map = new google.maps.Map(document.getElementById('map_canvas'),
                      mapOptions);
            
                var autocomplete;
                autocomplete = new google.maps.places.Autocomplete((document.getElementById(searchInput)), {
                    types: ['geocode'],
                });
                
                autocomplete.bindTo('bounds', map);
                
                google.maps.event.addListener(autocomplete, 'place_changed', function () {
                    var near_place = autocomplete.getPlace();
                    document.getElementById('latitude').value = near_place.geometry.location.lat();
                    document.getElementById('longitude').value = near_place.geometry.location.lng();
                });
            });
            
            $(document).on('change', '#'+searchInput, function () {
                document.getElementById('latitude').value = '';
                document.getElementById('longitude').value = '';
            });
            

            不完全符合您的要求,但对我有用。

            【讨论】:

              猜你喜欢
              • 2017-12-03
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-07-02
              • 2012-11-22
              • 2019-08-25
              • 2017-12-23
              • 2017-04-12
              相关资源
              最近更新 更多