简体   繁体   中英

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

I am integrating Algolia autocomplete and do not like the look of the autocomplete suggestions. Specifically, I don't want the administrative municipalities and districts to appear in the suggestions, only address, city, country. How can I omit the administrative query?

For example, if I type in "Sarajevo" the suggestions appear as "Sarajevo, Kanton of Sarajevo, Bosnia and Herzegovina" - I want it to appear as simply "Sarajevo, Bosnia and Herzegovina".

You should use the templates option of the Places constructor.

Here's a simple example:

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

Have a look at the function that is used by default for a more elaborate sample: https://github.com/algolia/places/blob/master/src/formatDropdownValue.js

I tweaked your code (as it was for some reason giving a double comma) to this and it is working well - thank you again! :D

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

I've just realised that even though the autocomplete suggestions omit the administrative level, once you select a 'place', the administrative level gets displayed in the search bar. Any suggestions on how to edit the return value, ie what is displayed AFTER you select a city/country?

Thank you.

To solve the problem of once you select a 'place', the administrative level gets displayed in the search bar. , you can leverage on jquery's focusout event.

Example

    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)
    });

Note, it won't work without the setTimeout() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM