簡體   English   中英

Algolia 自動完成 - 如何從自動完成建議中刪除“行政”市/區

[英]Algolia autocomplete - how to remove "administrative" municipalities/districts from autocomplete suggestions

我正在集成 Algolia 自動完成功能,不喜歡自動完成建議的外觀。 具體來說,我不希望建議中出現行政直轄市和區,只有address, city, country。 我怎樣才能省略管理查詢?

例如,如果我輸入“Sarajevo”,建議顯示為“Sarajevo, Kanton of Sarajevo, Bosnia and Herzegovina”——我希望它顯示為“Sarajevo, Bosnia and Herzegovina”。

您應該使用 Places 構造函數的templates選項。

這是一個簡單的例子:

const placesInstance = places({
    ...
    templates: {
        suggestion: function(s) {
            return [s.highlight.name, s.highlight.city, s.highlight.country].join(', ');
        }
    }
});

查看默認使用的函數以獲得更詳細的示例: https ://github.com/algolia/places/blob/master/src/formatDropdownValue.js

我對此進行了調整(由於某種原因,請使用雙逗號),它運行良好-再次感謝您! :d

templates: {
                   suggestion: function({ name, country, highlight }) {
            return (highlight.name || name) + ', ' + (highlight.country || country);
                    }
                 },

我剛剛意識到,即使自動完成建議忽略了管理級別,一旦選擇了“地點”,管理級別也會顯示在搜索欄中。 關於如何編輯返回值的任何建議,即選擇城市/國家后顯示什么?

謝謝。

解決一旦您選擇“地點”,行政級別就會顯示在搜索欄中的問題。 ,您可以利用 jquery 的 focusout 事件。

例子

    var cityCountry  ,searchInput;
    searchInput = $('#search-input'); //our search field

    //Initialize
    var placesAutocomplete = places({
        // appId: 'YOUR_PLACES_APP_ID',
        // apiKey: 'YOUR_PLACES_API_KEY',
        container: document.querySelector('#search-input'),
    });

    //Attach required data to cityCountry  
    placesAutocomplete.on('change', function(e){
        let suggestion,city,country;
        suggestion = e.suggestion;
        city = suggestion.name;
        country= suggestion.country;
        cityCountry  = city+', '+country;
    });

    //Manipulate the search field on focusout
    searchInput.on('focusout', function(){
        setTimeout(function () {
            searchInput.val(cityCountry);
        },1)
    });

請注意,沒有setTimeout()它將無法工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM