【问题标题】:autocomplete display only results from specific country or zip code自动完成仅显示来自特定国家或邮政编码的结果
【发布时间】:2011-08-22 18:49:30
【问题描述】:
如何让我的自动填充功能仅显示来自特定国家或邮政编码的结果?
这就是我目前所做的
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
【问题讨论】:
标签:
javascript
html
google-maps
geolocation
【解决方案2】:
您可以截获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);
};