我一直在看上面的例子:
http://code.google.com/apis/maps/documentation/javascript/examples/places-autocomplete.html
并决定将其合并到我的网站中。
是否可以将地址限制为仅限英国地址?
发布于 2012-07-20 10:45:20
试试这个:
var input = document.getElementById('searchTextField');
var options = {
types: ['(cities)'],
componentRestrictions: {country: 'tr'}//Turkey only
};
var autocomplete = new google.maps.places.Autocomplete(input,options);
发布于 2011-09-01 17:16:38
你不能严格/硬限制它找到的位置,尽管系统中有这样做的功能请求,但你可以在结果上设置“偏差”。它作为参数传递给autocomplete方法,作为google地图边界对象。然后,Autocomplete将优先选择这些边界内的位置。但是,请注意,由于这不是一个硬边界,如果在边界之外有匹配的搜索,它将返回这些匹配。
从我的使用来看,它看起来有点by,可以做一些改进--特别是考虑到你的边界之外的任何东西根本不是通过邻近来标记的,所以边界外的一个街区的东西和1000英里外的东西一样有可能显示出来,所以要确保你的边界是正确的。
发布于 2012-03-15 18:59:41
您可以截获由google.maps.places.Autocomplete功能返回的JSONP结果,并在您认为合适的时候使用它们,例如按国家/地区限制并显示结果。
基本上,您在head元素上重新定义了appendChild方法,然后监视Google autocomplete代码插入到DOM for JSONP中的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);
};
https://stackoverflow.com/questions/7179452
复制