了解/控制 Google Places API 返回地点预测的顺序

问题描述 投票:0回答:1

我有一个示例页面,它根据搜索的位置返回机场。我们这样做是因为我们希望在我们正在构建的自定义搜索中获取城市的 IATA 代码。

我遇到的问题是我不明白为什么结果按顺序返回。据我所知,文档似乎没有提到这一点。

请参阅下面的示例,我正在搜索“伦敦”。任何人都可以帮助澄清这一点以及是否有办法控制它?理想情况下,我想要的是地理位置上最接近我输入的任何位置的机场。因此,以伦敦为例(谷歌与所有城市一样,似乎在其中心地理点标记了城市的地理编码),那就是伦敦城市机场。

function initAutocomplete() {
    var autoComplete = new google.maps.places.Autocomplete(
        document.getElementById('cityTown'),{types: ['geocode']}
    );

    google.maps.event.addListener(autoComplete, 'place_changed', () => { // arrow function
        this.location.loc = autoComplete.getPlace();
        $.each(this.location.loc.address_components, function(key,value) {
            if(value.types=='country,political'){               
                document.getElementById('country__c').value= value.long_name;
            }
        });
        //console.log('Place changed to: "'+this.location.loc.formatted_address+'"');
    });
}




function getAirports(city){
     
     // Initialize AutocompleteService for airports
     const autoCompleteAirport = new google.maps.places.AutocompleteService();
     // Get input and suggestion list elements
    
     const input = city;
     const suggestionsList = document.getElementById('suggestions');

     // Use AutocompleteService to get airport suggestions based on the city
     autoCompleteAirport.getPlacePredictions({ input: `${input}`, types: ['airport'] }, (predictions, status) => {
         if (status === google.maps.places.PlacesServiceStatus.OK) {
             // Clear previous suggestions
             suggestionsList.innerHTML = '';

             // Display new suggestions
             predictions.forEach((prediction) => {
                    var matches = prediction.description.match(/\((.*?)\)/);

                    //  // Check if there is a match
                    if (matches && matches.length > 1) {
                                const suggestion = document.createElement('li');
                                suggestion.textContent = prediction.description;
                                suggestionsList.appendChild(suggestion);
                    }
                });

                console.log(predictions);
         }
     });
     
}

if(city!=''){ 
    setTimeout(getAirports(city), 5000);
}else{
    alert('No city found');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//maps.googleapis.com/maps/api/js?libraries=places&callback=initAutocomplete&key=AIzaSyBbsCQreb9i_t_d30cSgtf7JLOZlS_aS8U" ></script>


<script>
// Setup and call function 
var city='London'; 

</script>

<h2>Results from Places API</h2>
<ul id="suggestions"></ul>

google-places-api
1个回答
0
投票

获取按距离排序的预测列表(注意:直线距离)的唯一方法是在调用 API 之前获取城市的坐标,并使用

origin: new google.maps.LatLng(51.5287398,-0.1222089)
将它们传递给查询(在本例中我已经使用伦敦市中心的坐标)。

使用

origin
,您的结果将包含
distance_meters
参数,该参数表示从
origin
到结果的直线距离。然后,通过此参数对结果进行排序,即可达到预期结果(请参阅示例)。

function initAutocomplete() {
    var autoComplete = new google.maps.places.Autocomplete(
        document.getElementById('cityTown'),{types: ['geocode']}
    );

    google.maps.event.addListener(autoComplete, 'place_changed', () => { // arrow function
        this.location.loc = autoComplete.getPlace();
        $.each(this.location.loc.address_components, function(key,value) {
            if(value.types=='country,political'){               
                document.getElementById('country__c').value= value.long_name;
            }
        });
        //console.log('Place changed to: "'+this.location.loc.formatted_address+'"');
    });
}




function getAirports(city){
     
     // Initialize AutocompleteService for airports
     const autoCompleteAirport = new google.maps.places.AutocompleteService();
     // Get input and suggestion list elements
    
     const input = city;
     const suggestionsList = document.getElementById('suggestions');

     // Use AutocompleteService to get airport suggestions based on the city
     autoCompleteAirport.getPlacePredictions({ input: `${input}`, types: ['airport'], origin: new google.maps.LatLng(51.5287398,-0.1222089) }, (predictions, status) => {
         if (status === google.maps.places.PlacesServiceStatus.OK) {
             // Clear previous suggestions
             suggestionsList.innerHTML = '';

             // Order by straight-line distance
             predictions = predictions.sort(function(a, b) {
                 return a.distance_meters - b.distance_meters;
             });


             // Display new suggestions
             predictions.forEach((prediction) => {
                    var matches = prediction.description.match(/\((.*?)\)/);

                    //  // Check if there is a match
                    if (matches && matches.length > 1) {
                                const suggestion = document.createElement('li');
                                suggestion.textContent = prediction.description;
                                suggestionsList.appendChild(suggestion);
                    }
                });

                console.log(predictions);
         }
     });
     
}

if(city!=''){ 
    setTimeout(getAirports(city), 5000);
}else{
    alert('No city found');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//maps.googleapis.com/maps/api/js?libraries=places&callback=initAutocomplete&key=AIzaSyBbsCQreb9i_t_d30cSgtf7JLOZlS_aS8U" ></script>


<script>
// Setup and call function 
var city='London'; 

</script>

<h2>Results from Places API</h2>
<ul id="suggestions"></ul>

© www.soinside.com 2019 - 2024. All rights reserved.