将谷歌地图自动填充限制为仅英国地址

发布于 2024-12-01 08:45:02 字数 293 浏览 1 评论 0原文

我一直在查看以下示例:

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

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

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

I've been looking at the example on:

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

and have decided to incorporate it into my site.

Is it possible to limit the addresses to UK addresses only?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

会傲 2024-12-08 08:45:02

试试这个:

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

Try this:

var input = document.getElementById('searchTextField');
var options = {
   types: ['(cities)'],
   componentRestrictions: {country: 'tr'}//Turkey only
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
半城柳色半声笛 2024-12-08 08:45:02

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

从我的使用情况来看,它似乎有点问题,可以进行一些改进 - 特别是考虑到边界之外的任何东西都不会被接近度标记,因此边界之外一个街区的东西与 1000 英里之外的东西一样有可能显示,所以确保你努力让边界发挥作用。

You can't strictly/hard limit the locations that it finds, although there is a feature request in the system to do so, but you can set a 'bias' on the results. It's passed in as an argument to the autocomplete method as a google maps bounds object. Autocomplete will then favor locations within those boundaries. Note, however, that since this isn't a hard boundary, if there are matches for the search outside the boundaries it will return those.

From my usage it seems a bit buggy and can use some improvement - especially considering that anything outside your boundary is not tagged by proximity at all, so something one block outside the boundary is just as likely to show as something 1000 miles outside, so make sure you play around with getting the boundaries working right.

姐不稀罕 2024-12-08 08:45:02

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

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

这有点像黑客,如下(我使用的是 jQuery,但这个黑客没有必要工作):

//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);
};

You can intercept the JSONP results that are returned by the google.maps.places.Autocomplete functionality and use them as you see fit, such as to limit by country and display the results.

Basically you redefine the appendChild method on the head element, and then monitor the javascript elements that the Google autocomplete code inserts into the DOM for JSONP. As javascript elements are added, you override the JSONP callbacks that Google defines in order to get access to the raw autocomplete data.

It's a bit of a hack, here goes (I'm using jQuery but it's not necessary for this hack to work):

//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);
};
一花一树开 2024-12-08 08:45:02

James Alday 的说法正确:

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/

James Alday is correct:

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']
};

it is somewhat annoying as searching for Durham gives Durham, North Carolina as the second result, regardless of how you try to persuade it to region bias - you can set it to viewport map bounds and it'll still try to suggest NC state... The jQuery solution can be found here, but doesn't seem to give as many results as the v3 API.
http://code.google.com/p/geo-autocomplete/

滥情哥ㄟ 2024-12-08 08:45:02

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

The best way you would go about doing this, is to query the places api yourself and appending the queried string with your country. Or, of course, use the geo-autocomplete jQuery plugin.

深巷少女 2024-12-08 08:45:02

只需将地图的谷歌域名更改为您所在的国家/地区域名,它就会自动仅在您所在的国家/地区内进行搜索:

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

至:
http://maps.google.nl/maps/api/geocode/xml?地址={0}&传感器=false&语言=nl

Just change the google domain for the maps to your country domain and it will automatically search within your country only:

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

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

清风夜微凉 2024-12-08 08:45:02

尝试这样的事情。

// 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 () {
});

Try something like this.

// 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 () {
});
寻找我们的幸福 2024-12-08 08:45:02

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

它比先随机提供海外地址效果更好,设置为国家/地区不起作用。

自动完成获取 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 = '';
});

不完全是您所要求的,但它对我有用。

I find that if you set the map to roughly where you want then set bounds to it, the search finds places in that area first. You do not to physically show the map.

It works better than giving random overseas addresses first, setting to country does not work.

The code for autocomplete to get latln is:

    <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 = '';
});

Not exactly what you asked for but it works for me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文