Custom display for search results

Open in CodeSandbox

This example shows how to set a custom view for search results.

The selected results are added to the GeoObjectCollection collection, where the "click" event is listened for. When a found object is clicked, its placemark turns red.

In the same way, the collection's objects have a custom layout set for the popup hint.

<!DOCTYPE html>
<html>
    <head>
        <title>Examples. Setting a custom display for search results</title>
        <meta
            http-equiv="Content-Type"
            content="text/html; charset=UTF-8"
        />
        <!--
        Set your own API-key. Testing key is not valid for other web-sites and services.
        Get your API-key on the Developer Dashboard: https://developer.tech.yandex.ru/keys/
    -->
        <script
            src="https://api-maps.yandex.ru/2.1/?lang=en_RU&amp;apikey=<your API-key>"
            type="text/javascript"
        ></script>
        <script
            src="custom_search_results.js"
            type="text/javascript"
        ></script>
        <style>
            html,
            body,
            #map {
                width: 100%;
                height: 100%;
                padding: 0;
                margin: 0;
            }
        </style>
    </head>
    <body>
        <div id="map"></div>
    </body>
</html>
ymaps.ready(function () {
    var myMap = new ymaps.Map("map", {
            center: [59.22, 39.89],
            zoom: 12,
            controls: [],
        }),
        // Creating an instance of the ymaps.control.SearchControl class.
        mySearchControl = new ymaps.control.SearchControl({
            options: {
                noPlacemark: true,
            },
        }),
        // The search results will be placed in the collection.
        mySearchResults = new ymaps.GeoObjectCollection(null, {
            hintContentLayout:
                ymaps.templateLayoutFactory.createClass(
                    "$[properties.name]"
                ),
        });
    myMap.controls.add(mySearchControl);
    myMap.geoObjects.add(mySearchResults);
    // When the found object is clicked, the placemark turns red.
    mySearchResults.events.add("click", function (e) {
        e.get("target").options.set("preset", "islands#redIcon");
    });
    // Putting the selected result in the collection.
    mySearchControl.events
        .add("resultselect", function (e) {
            var index = e.get("index");
            mySearchControl.getResult(index).then(function (res) {
                mySearchResults.add(res);
            });
        })
        .add("submit", function () {
            mySearchResults.removeAll();
        });
});