javascript - 예제 - new google maps places searchbox
AJAX를 통해 Google지도/지역 정보 '자동 완성'API를 사용할 수 있습니까? (6)
Google 지역 정보 자동 완성 API를 사용하여 데이터 입력을 쉽게하기 위해 설정 데이터가있는 웹 애플리케이션의 양식을 미리 채우려고합니다. 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 cannot load 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. Origin http://localhost:8086 is not allowed by Access-Control-Allow-Origin.
이 API가 무엇을 의미하지 않는 것입니까? 누구나 해결 방법이나 작동하도록 추가 매개 변수를 알 수 있습니까?
최신 정보:
이 호출에 대한 API 문서에 대한 링크가 있습니다. 부모 문서에는 실제로 JavaScript JSON 구문 분석 예제가 있습니다. 이것이 왜 서버 측에서 종료 될지 혼란 스럽습니다.
http://code.google.com/apis/maps/documentation/places/autocomplete.html
Google Maps Autocomplete API에 액세스하는 방법에는 두 가지가 있습니다.
첫 번째 방법은 google.maps.places.Autocomplete
클래스를 사용하는 것입니다. 이것은 Javascript에서 필요한 모든 구현을 제공합니다. 그러나 스타일을 완벽하게 제어 할 수 있습니다. pac-container
및 pac-item
CSS 클래스를 사용하십시오.
두 번째는 http://code.google.com/apis/maps/documentation/places/autocomplete.html 를 통해 이루어집니다. 원본 정책 이 동일 하기 때문에 브라우저를 통해 액세스 할 수 없습니다 (JSONP API 없음). 자동 완성 결과에 액세스하는 가장 유연한 방법입니다.
Google Maps Javascript API의 지역 정보 라이브러리 사용 : Javascript Places Autocomplete
Places API는 Maps API와 다릅니다.
PHP를 사용하여이 문제를 피할 수 있습니다.
PHP 스크립트에서 file_get_contents를 사용하여 다음과 같이 URL을 쿼리하십시오.
$ suggestions = json_decode (file_get_contents ( 'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=blabla&sensor=false&types=establishment&radius=10000')
그런 다음 PHP 스크립트에 AJAX 요청을 사용하면 크로스 도메인 제약 조건을 우회하는 결과를 효과적으로 반환 할 수 있습니다.
이 시나리오를 이해할 미래의 독자를위한 코드 스 니펫입니다.
이 코드 스 니펫은 'Maps API'대신 'Places 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 페이지 에 나열되어 있습니다.
이와 같이 도메인 간 AJAX 호출을하려면 JSONP를 콜백과 함께 사용해야합니다. 그러나 Google은 자동 완성을 위해 JSONP 인터페이스를 제공하지 않습니다 .
이 자동 완성 클래스를 대신 사용할 수는 있지만 드롭 다운의 스타일을 지정하는 것은 불가능합니다.
편집 이것을 할 수있는 방법이있을 수 있습니다. geo-autocomplete jQuery Plugin을 확인하자. two demos 있습니다. 나는 아직 이것에 적당한보기를 아직주지 않았다.
google.maps.places.Autocomplete 기능에 의해 반환 된 JSONP 결과를 가로 채고 적절하게 사용합니다.
기본적으로 head 요소에 appendChild 메소드를 재정의 한 다음 Google 자동 완성 코드가 JSONP 용 DOM에 삽입하는 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);
};