2013-02-02 59 views
10

我正在設置一個自定義自動填充字段,其中顯示Google地方中的位置以及來自我的數據庫的匹配搜索查詢的事件。出於這個原因,我使用Google商家信息自動填充服務來獲取查詢預測,而不是直接在自己的文本字段中插入自動填充功能。Google Places自動完成服務按國家/地區篩選

問題是我無法弄清楚如何使用自動完成服務按國家過濾地方自動填充建議。

我已經試過:

var service = new google.maps.places.AutocompleteService(null, { 
     types: ['cities'], 
     componentRestrictions: {country: "au"} 
    }); 

,但它仍然顯示德國自動完成選項和法國:(

任何建議

回答

30

您需要在調用服務時通過限制,而不是在創建服務時通過限制。這裏:

//create service 
service = new google.maps.places.AutocompleteService(); 

//perform request. limit results to Australia 
var request = { 
    input: 'Brisbane', 
    componentRestrictions: {country: 'au'}, 
}; 
service.getPlacePredictions(request, callback); 
+0

Hello Robert,你是如何以及在哪裏定義了你的'callback'? – chaeschuechli

+0

@chaeschuechli查看[官方示例](https://developers.google.com/maps/documentation/javascript/examples/places-queryprediction)。 「displaySuggestions」函數是回調函數。 –

+1

這不行!你可否確認? – Apoorv

1

如文檔reference中介紹,商家信息庫AutocompleteService?不支持AutocompleteOptions。如果您認爲這將是一項有價值的功能,請提交Places API - Feature Request

+1

你能具體談談其中,那就是在文檔中概述?從我看到的,你可以按國家來限制。 – thealexbaron

+0

是的,我也只是選中了「componentRestrictions」 – LeRoy

7

您可以使用AutocompletionRequest指定類型和componentRestrictions。這裏是一個例子 -

var service = new google.maps.places.AutocompleteService(); 

    service.getPlacePredictions({ input: query, types: ['geocode'], 
           componentRestrictions:{ country: 'us' } }, 
      function (predictions, status) { 
       if (status == google.maps.places.PlacesServiceStatus.OK) { 
        var results = document.getElementById('results'); 
        for (var i = 0, prediction; prediction = predictions[i]; i++) { 
         results.innerHTML += '<li>' + prediction.description + '</li>'; 
        } 
       } 
      }); 
0

您應該使用此代碼。

var options = { 
    types: ['(cities)'], 
    componentRestrictions: {country: ["in"]} 
} 
//Find From location  
var input= document.getElementById('input_box_city'); 
var fromAuto = new google.maps.places.Autocomplete(input, options); 
+0

這是用於Autocomplete類的,而不是AutocompleteService類。 AutocompleteService類允許您以編程方式處理結果,而Autocomplete類爲您裝飾輸入元素。 – GuruBob

-1

使用此工作代碼

var input = document.getElementById("query_value"); 
var autocomplete = new google.maps.places.Autocomplete(input, { 
    componentRestrictions: { country: "IN" }, 
    place_id: "YOUR_PLACE_ID" 
}); 
google.maps.event.addListener(autocomplete, "place_changed", function() { 
    var place = autocomplete.getPlace(); 
}); 


https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places&language=en&key=YOUR_KEY 
相關問題