google 地图:在特定国家搜索

google maps: search in specific countries

我的 PHP 应用程序中有一个表格,用于搜索欧洲的位置:德国、法国、波兰、捷克共和国、西班牙、奥地利、罗马尼亚、意大利。

这是我的基本查询:

$address = "https://maps.googleapis.com/maps/api/geocode/json?address={$input}";

如果用户尝试查找 "mannheim",例如,它应该 return 德国曼海姆。 相反,它 return 是美国宾夕法尼亚州的一个点。我尝试添加此地址组件限制:&components=administrative_area:EU, 但这不可靠,因为它没有找到德国曼海姆,而是指向 300 公里外的地方:

https://www.google.ro/maps/dir/50.5320001,6.6364339/Mannheim/@50.0388399,8.4546225,7.25z/data=!4m8!4m7!1m0!1m5!1m1!1s0x4797cc24518e3f45:0xb1e4fe7aa406e687!2m2!1d8.4660395!2d49.4874592?hl=en

如果我追加 , Germany:

$address = "https://maps.googleapis.com/maps/api/geocode/json?address={$input}, Germany";

则回答正确

是否可以指定搜索的某些国家/地区?

最后的办法是对每个国家/地区进行单独搜索,但考虑到我搜索的大约 10-12 个国家/地区,这将非常缓慢。

通过国家/地区限制来限制 google 搜索结果,如下所示:

var options = {
        componentRestrictions: {country: 'DE'}
      };

并将选项参数放在自动完成或您正在使用的其他功能中。

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

看起来现在可以了:https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-multiple-countries#maps_places_autocomplete_multiple_countries-javascript

  // Sets a listener on a given radio button. The radio buttons specify
  // the countries used to restrict the autocomplete search.
  function setupClickListener(id, countries) {
    const radioButton = document.getElementById(id);
    radioButton.addEventListener("click", () => {
      autocomplete.setComponentRestrictions({ country: countries });
    });
  }
  setupClickListener("changecountry-usa", "us");
  setupClickListener("changecountry-usa-and-uot", [
    "us",
    "pr",
    "vi",
    "gu",
    "mp",
  ]);

根据 google 文档,我们最多可以在组件过滤器中添加 5 个国家 https://developers.google.com/maps/documentation/places/web-service/autocomplete

您希望将搜索结果限制到的一组地点。目前,您最多可以使用组件过滤 5 个国家/地区。国家必须作为两个字符传递,ISO 3166-1 Alpha-2 兼容国家代码。例如:components=country:fr 会将您的结果限制在法国境内的地点。必须将多个国家/地区作为多个 country:XX 过滤器传递,并使用竖线字符 |作为分隔符。例如:components=country:us|country:pr|country:vi|country:gu|country:mp 会将您的结果限制在美国及其未合并的有组织领土内的地方。