谷歌地图API - 仅限美国的自动完成预测

11

我正在使用名为 'Retrieving Autocomplete Predictions'的Google Maps API示例。 我无法弄清楚如何筛选它,以便它仅返回美国境内的地点。 我知道如何在其他示例中进行处理...

var input = document.getElementById('searchTextField');
var options = {
      types: ['(cities)'],
      componentRestrictions: {country: 'us'}
    };

autocomplete = new google.maps.places.Autocomplete(input, options);
但是我似乎无法弄清楚如何将其应用于我的示例。这是我的代码...
function GetAddressPredictions(Search) {
    var displaySuggestions = function (predictions, status) {
    if (status != google.maps.places.PlacesServiceStatus.OK) {
        return;
    }
    predictions.forEach(function (prediction) {
        PredictionArray.push(prediction);
    });
};
var service = new google.maps.places.AutocompleteService();
service.getQueryPredictions({input: Search}, displaySuggestions);
}

我尝试过这个,但它没有起作用。

function GetAddressPredictions(Search) {
    var displaySuggestions = function (predictions, status) {
    if (status != google.maps.places.PlacesServiceStatus.OK) {
        return;
    }
    predictions.forEach(function (prediction) {
        PredictionArray.push(prediction);
    });
};
var options = {
    types: ['(cities)'],
    componentRestrictions: {country: 'us'}
      };
    var service = new google.maps.places.AutocompleteService();
    service.getQueryPredictions({input: Search, options}, displaySuggestions);
}

有什么想法吗?谢谢。

5个回答

8
您非常接近目标,但是要实现这种特定的行为,您需要使用getPlacePredictions()而不是getQueryPredictions()。这使您可以使用AutocompletionRequest,其中包括componentRestrictions,但QueryAutocompletionRequest不支持componetRestictions,您必须回退到使用bounds来限制搜索范围为方框或使用location来偏好搜索靠近某个点的位置。

下面是使用getPlacePredictions()的解决方案:

  var service = new google.maps.places.AutocompleteService();
  var options = {
    input: Search,
    types: ['(cities)'],
    componentRestrictions: {country: 'us'}
  };
  service.getPlacePredictions(options , displaySuggestions);

如果您必须使用getQueryPredictions(),则可以将locationbounds作为键添加到选项对象中。


1
运行完美。谢谢。 - nachshon f

4
函数 getQueryPredictions 的参数是一个 QueryAutocompletionRequest 对象,但该对象没有属性可以限制其仅搜索特定国家。
尽管如此,在发送请求之前,您可以在查询字符串后面简单地添加“美国”或“USA”的字符以实现限制搜索美国的目的。
service.getQueryPredictions({
   input: 'pizza near Syd' + ' usa'
}, displaySuggestions);

如果您不想在返回结果中显示", USA",您可以使用JavaScript的replace函数将其删除:
predictions.forEach(function(prediction) {
   var li = document.createElement('li');
   li.appendChild(document.createTextNode(prediction.description.replace(', USA', '')));
   document.getElementById('results').appendChild(li);
});

演示: https://jsfiddle.net/sdz4yssL/2/

同时请注意,如果搜索项中已经包含"USA"或其变体的风险,则需要首先从搜索项中删除所有出现的内容(通常使用正则表达式忽略大小写),否则搜索"pizza usa usa"之类的内容将不会返回任何结果:

input: (' ' + 'pizza near us Syd usa United States US' + ' ').replace(/ usa /ig,' ').replace(/ US /ig,' ').replace(/ united states /ig,' ') + ' usa'

(我在查询前后添加了一个空格,以便替换函数仍然可以在开头和结尾处匹配)


我之前也有过这个想法,但问题是,在你开始输入时,它会返回带有字母US的结果...请看这个例子... https://s23.postimg.org/idefab67v/Screen_Shot_2017-07-17_at_8.08.17_AM.png - 这真的限制了它的能力。还有其他解决方案吗? - nachshon f
我的正则表达式匹配[空格]US[空格],所以没有尾随空格的US-41不应该是一个问题。你用我的代码试过了吗? - K Scandrett
如果您要在屏幕截图中添加“US”到查询中,最好使用我所做的“USA”,甚至是“美国”。 - K Scandrett
我也尝试了US、USA和United States。它们都返回包含这些名称的结果。我该怎么办?你确定没有办法使用国家限制吗? - nachshon f
1
如果您查看我的jsfiddle,我会在搜索中添加“美国”,然后在最后将其从搜索结果中删除,这是您的意思吗?在您的屏幕截图中出现US-41等内容,您要求谷歌仅通过一个数字来搜索整个美国;没有其他上下文。如果我是Google搜索,我不知道您在寻找什么。您期望返回什么? - K Scandrett
显示剩余3条评论

2
通过一些搜索,找到了解决方案。
该请求已于今年早些时候获得批准和发布:Google请求 此类信息的文档可以从这里阅读:Google文档 实现:
HTML:
<div id="text">
  Search Place:
</div>

<div id="locationField">
  <input id="autocomplete" placeholder="Enter text" type="text" />
</div>


<div id="map"></div>

限制使用全局变量的国家,例如英国用UK,美洲用US等...
var countryRestrict = {
  'country': 'uk'
};
var autocomplete;

自动完成是根据以下内容构建的:
 autocomplete = new google.maps.places.Autocomplete(
     (
      document.getElementById('autocomplete')), {
      componentRestrictions: countryRestrict
    });
  places = new google.maps.places.PlacesService(map);

  autocomplete.addListener('place_changed', onPlaceChanged);

当文本发生变化时,我们调用onPlacesChanged函数:
function onPlaceChanged() {
  var place = autocomplete.getPlace();
  if (place.geometry) {
    map.panTo(place.geometry.location);
    map.setZoom(5);
    var marker = new google.maps.Marker({
      position: place.geometry.location,
      map: map,
    });
  } else {
    document.getElementById('autocomplete').placeholder = 'Enter a Value';
  }
}

这段话调用了“获取地点”函数,并将标记添加到您所点击的值上。
JSFIDDLE链接:https://jsfiddle.net/hn8091fk/

1
你尝试过像这样的东西吗:

function GetAddressPredictions(Search) {

    var displaySuggestions = function(predictions, status) {
        if (status != google.maps.places.PlacesServiceStatus.OK) {
            return;
        }

        predictions.forEach(function(prediction) {
            PredictionArray.push(prediction);
        });
    };

    var service = new google.maps.places.AutocompleteService();
    service.getQueryPredictions({ 
            input: Search, 
            types: ['(cities)'], 
            componentRestrictions: {country: 'us'} 
        }, displaySuggestions);
}

1
抱歉,没有起作用。它仍然返回其他国家的结果。控制台中没有错误,所以我能提供的信息很少。 - nachshon f

1
与上文相反,AutocompleteService 只需传递 QueryAutocompletionRequestAutocompletionRequest,因此我认为您传递选项的方式是错误的。难道不是这样简单吗:
var options = {
    input: Search, 
    types: ['(cities)'],
    componentRestrictions: {country: 'us'}
};

var service = new google.maps.places.AutocompleteService();
service.getQueryPredictions(options, displaySuggestions);

请记住,这全部都是为了“预测偏差”,您不能要求PAC排除结果,只能进行偏差处理。

1
我按照你说的做了,但是没有起作用。其中一个最初的结果在西班牙。我看不出结果与我的原始代码有什么区别。无论如何,还是谢谢你的尝试。 - nachshon f
@nachshonf 很抱歉。有没有可能创建一个 jsfiddle 或类似的东西来查看它?我以前没有使用过这些方法来使用 Google PAC。 - Paul Thomas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接