Algolia Places is closing. We can help.

Recent searches demo

Introduction #

Save a user's search history in local storage so that frequent searches can be repeated easily.

View live on CodePen

HTML #

            
<html>

    <head>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-theme-classic"/>
    </head>

    <body>

        <div id="search-container"></div>

        <script src="https://cdn.jsdelivr.net/algoliasearch/3/algoliasearch.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-js"></script>
        <script src="https://cdn.jsdelivr.net/npm/@algolia/autocomplete-plugin-recent-searches"></script>
        <script src="/assets/js/app.js"></script>

    </body>
</html>
            
        

CSS #

            
body {
    background: black;
    color: white;
    padding-top: 60px;
}

p {
    margin-bottom: 0;
}

.algolia-autocomplete {
    width: 100%;
}

.algolia-autocomplete .aa-input,
.algolia-autocomplete .aa-hint {
    width: 100%;
}

.algolia-autocomplete .aa-hint {
    color: #999;
}

.algolia-autocomplete .aa-dropdown-menu {
    width: 100%;
    background-color: #fff;
    border: 1px solid #999;
    border-top: none;
}

.algolia-autocomplete .aa-dropdown-menu .aa-suggestion {
    cursor: pointer;
    padding: 5px 4px;
}

.algolia-autocomplete .aa-dropdown-menu .aa-suggestion.aa-cursor {
    background-color: #b2d7ff;
}

.algolia-autocomplete .aa-dropdown-menu .aa-suggestion em {
    font-weight: bold;
    font-style: normal;
}

#search-container {
    margin-top: 30px;
}
            
        

JavaScript #

            
const { autocomplete, getAlgoliaResults } = window["@algolia/autocomplete-js"];
const { createLocalStorageRecentSearchesPlugin } = window["@algolia/autocomplete-plugin-recent-searches"];

const recentSearchesPlugin = createLocalStorageRecentSearchesPlugin(
    {
        key: "RECENT_SEARCH",
        limit: 5,
    }
);

const searchClient = algoliasearch(
    "DM340JGS49",
    "YOUR_PLACESAPI_KEY_HERE"
);

autocomplete({
    container: "#search-container",
    detachedMediaQuery: "none",
    placeholder: "Search for places...",
    plugins: [recentSearchesPlugin],
    getSources() {
        return [{
            sourceId: "places",
            getItems({ query }) {
                return getAlgoliaResults({
                    searchClient,
                    queries: [
                        {
                            indexName: "places",
                            query,
                        },
                    ],
                });
            },
            templates: {
                item({ item }) {
                    return `${item.name}, ${item.county}, ${item.country}`;
                },
            },
            onSelect: function (event) {
                event.setQuery(event.item.name + ", " + event.item.county + ", " + event.item.country);
            },
        }];
    },
});