我正在尝试使用 Google Places 自动完成 API 在 Web 应用程序上使用企业数据预填写表单,以简化数据输入。 API 非常简单,但似乎不想接受 XHR。
$.getJSON("https://maps.googleapis.com/maps/api/place/autocomplete/json",{
input: input.term,
sensor: false,
types: 'establishment',
location: '40.01496,-105.27029',
radius: 10000,
key: Config.googleplaceskey
},function(places_response){
//Some other code.
});
我在控制台中得到了这个:
XMLHttpRequest 无法加载 https://maps.googleapis.com/maps/api/place/autocomplete/json?input=At&sensor=false&types=establishment&location=40.01496%2C-105.27029&radius=10000&key=AIzaSyDKzUgcLklQE_U5494vHq_SzrFakNHugaQ。 Access-Control-Allow-Origin 不允许来源 http://localhost:8086。
这在某种程度上不是 API 的用途吗?任何人都知道解决方法,或者我可以发送某种额外参数以使其工作?
更新:
这是此调用的 API 文档的链接。父文档实际上什至有 JavaScript JSON 解析示例。真的很困惑为什么这会在服务器端关闭。
http://code.google.com/apis/maps/documentation/places/autocomplete.html
最佳答案
这里是一个代码片段,供 future 遇到这种情况的读者使用。
使用“Places API”而不是“Maps API”,此代码片段使用 Google 返回的数据填充我的表单元素(包括用于自动完成的输入)。
/* Use google place API to auto complete the address field and populate form inputs */
function addressAutoComplete(){
var planAddress = document.getElementById('mps_planaddress'),
planCity = document.getElementById('mps_plancity'),
planCounty = document.getElementById('mps_plancounty'),
planZip = document.getElementById('mps_planzip'),
planSub = document.getElementById('mps_plansubdivision'),
options = {
componentRestrictions: {country: 'us'}
};
autocomplete = new google.maps.places.Autocomplete(planAddress, options);
// After the user selects the address
google.maps.event.addListener(autocomplete, 'place_changed', function() {
planSub.focus();
var place = autocomplete.getPlace();
planAddress.value = place.name;
planCity.value = place.address_components[2].long_name;
planCounty.value = place.address_components[3].long_name;
planZip.value = place.address_components[6].long_name;
});
}
在“place_changed”(他们从列表中选择了一些东西)的自动完成上放置一个监听器,然后用返回的数据填充输入。
所有这些都列在 Place Library Google page 上.
关于javascript - 可以通过 AJAX 使用 Google map /地点 'autocomplete' API 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6803521/