Поиск по своей коллекции объектов

Open in CodeSandbox

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
        <script crossorigin src="https://cdn.jsdelivr.net/npm/@babel/standalone@7/babel.min.js"></script>
        <!-- To make the map appear, you must add your apikey -->
        <script src="https://api-maps.yandex.ru/v3/?apikey=<YOUR_APIKEY>&lang=en_US" type="text/javascript"></script>

        <script
            data-plugins="transform-modules-umd"
            data-presets="typescript"
            type="text/babel"
            src="../variables.ts"
        ></script>
        <script
            data-plugins="transform-modules-umd"
            data-presets="typescript"
            type="text/babel"
            src="./common.ts"
        ></script>
        <script data-plugins="transform-modules-umd" data-presets="typescript" type="text/babel">
            import type {YMapSearchControlProps} from '@yandex/ymaps3-default-ui-theme';
            import type {SuggestResponseItem} from '@yandex/ymaps3-types';
            import {COMMON_LOCATION_PARAMS, type ExtendedFeature, searchFromList} from './common';
            import {LOCAL_LIST, LOCATION} from '../variables';
            
            interface InfoMessageProps {
                text: string;
            }
            
            window.map = null;
            
            main();
            
            async function main() {
                // Waiting for all api elements to be loaded
                await ymaps3.ready;
                const {YMap, YMapDefaultSchemeLayer, YMapDefaultFeaturesLayer, YMapControls, YMapControl} = ymaps3;
                const {YMapSearchControl, YMapDefaultMarker} = await ymaps3.import('@yandex/ymaps3-default-ui-theme');
            
                // Initialize the map
                map = new YMap(
                    // Pass the link to the HTMLElement of the container
                    document.getElementById('app'),
                    // Pass the map initialization parameters
                    {location: LOCATION, showScaleInCopyrights: true},
                    // Add a map scheme layer
                    [new YMapDefaultSchemeLayer({}), new YMapDefaultFeaturesLayer({})]
                );
            
                class InfoMessageClass extends ymaps3.YMapComplexEntity<InfoMessageProps> {
                    private _element!: HTMLDivElement;
                    private _detachDom!: () => void;
            
                    // Method for create a DOM control element
                    _createElement(props: InfoMessageProps) {
                        // Create a root element
                        const infoWindow = document.createElement('div');
                        infoWindow.classList.add('info-window');
                        infoWindow.innerText = props.text;
            
                        return infoWindow;
                    }
            
                    // Method for attaching the control to the map
                    _onAttach() {
                        this._element = this._createElement(this._props);
                        this._detachDom = ymaps3.useDomContext(this, this._element, this._element);
                    }
            
                    // Method for detaching control from the map
                    _onDetach() {
                        this._detachDom();
                        this._detachDom = undefined;
                        this._element = undefined;
                    }
                }
            
                const search: YMapSearchControlProps['search'] = ({params}) => {
                    return searchFromList(params.uri, LOCAL_LIST);
                };
            
                const suggest: YMapSearchControlProps['suggest'] = ({text}) => {
                    return searchFromList(text, LOCAL_LIST).map(
                        (object: ExtendedFeature) =>
                            ({
                                uri: object.properties.name,
                                title: {
                                    text: object.properties.name
                                },
                                subtitle: {
                                    text: object.properties.id
                                }
                            } as SuggestResponseItem)
                    );
                };
            
                const searchResult: YMapSearchControlProps['searchResult'] = (searchResult) => {
                    map.update({location: {center: searchResult[0].geometry.coordinates, ...COMMON_LOCATION_PARAMS}});
                };
            
                const searchControl = new YMapSearchControl({
                    placeholder: 'Search from your objects',
                    search,
                    searchResult,
                    suggest
                });
            
                map.addChild(
                    new YMapControls(
                        {
                            position: 'top right'
                        },
                        [searchControl]
                    )
                );
            
                const control = new YMapControl({transparent: true}).addChild(
                    new InfoMessageClass({text: 'This is what users see'})
                );
                map.addChild(new YMapControls({position: 'top left'}, [control]));
            
                const listElement = document.getElementById('list');
            
                LOCAL_LIST.forEach((object) => {
                    map.addChild(
                        new YMapDefaultMarker({
                            iconName: object.properties.iconName,
                            coordinates: object.geometry.coordinates,
                            title: object.properties.name,
                            size: 'normal'
                        })
                    );
                    const listItem = document.createElement('li');
                    listItem.classList.add('list_item');
            
                    const listItemIcon = document.createElement('div');
                    listItemIcon.classList.add('list_item__icon');
                    listItemIcon.innerText = object.properties.id;
            
                    const listItemText = document.createElement('div');
                    listItemText.classList.add('list_item__text');
                    listItemText.innerText = object.properties.name;
            
                    listItem.appendChild(listItemIcon);
                    listItem.appendChild(listItemText);
            
                    listElement.appendChild(listItem);
                });
            }
        </script>

        <style> html, body, #app { width: 100%; height: 100%; margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; } .toolbar { position: absolute; z-index: 1000; top: 0; left: 0; display: flex; align-items: center; padding: 16px; } .toolbar a { padding: 16px; }  </style>
        <link rel="stylesheet" href="./common.css" />
        <link rel="stylesheet" href="../variables.css" />
    </head>
    <body>
        <div class="container">
            <div class="list">
                <div class="list__title">Your local list of objects</div>
                <ul class="list__items" id="list"></ul>
            </div>
            <div id="app" class="map"></div>
        </div>
    </body>
</html>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
        <script crossorigin src="https://cdn.jsdelivr.net/npm/react@17/umd/react.production.min.js"></script>
        <script crossorigin src="https://cdn.jsdelivr.net/npm/react-dom@17/umd/react-dom.production.min.js"></script>
        <script crossorigin src="https://cdn.jsdelivr.net/npm/@babel/standalone@7/babel.min.js"></script>
        <!-- To make the map appear, you must add your apikey -->
        <script src="https://api-maps.yandex.ru/v3/?apikey=<YOUR_APIKEY>&lang=en_US" type="text/javascript"></script>

        <script
            data-plugins="transform-modules-umd"
            data-presets="typescript"
            type="text/babel"
            src="../variables.ts"
        ></script>
        <script
            data-plugins="transform-modules-umd"
            data-presets="typescript"
            type="text/babel"
            src="./common.ts"
        ></script>
        <script data-plugins="transform-modules-umd" data-presets="react, typescript" type="text/babel">
            import type {YMapSearchControlProps} from '@yandex/ymaps3-default-ui-theme';
            import type {SuggestResponseItem} from '@yandex/ymaps3-types';
            import {LOCATION, LOCAL_LIST} from '../variables';
            import {COMMON_LOCATION_PARAMS, type ExtendedFeature, searchFromList} from './common';
            
            window.map = null;
            
            main();
            
            async function main() {
                const [ymaps3React] = await Promise.all([ymaps3.import('@yandex/ymaps3-reactify'), ymaps3.ready]);
                const reactify = ymaps3React.reactify.bindTo(React, ReactDOM);
                const {YMap, YMapDefaultSchemeLayer, YMapDefaultFeaturesLayer, YMapControls, YMapControl} = reactify.module(ymaps3);
                const {YMapSearchControl, YMapDefaultMarker} = await reactify.module(
                    await ymaps3.import('@yandex/ymaps3-default-ui-theme')
                );
                const {useCallback} = React;
            
                function App() {
                    const search: YMapSearchControlProps['search'] = useCallback(({params}) => {
                        return searchFromList(params.uri, LOCAL_LIST);
                    }, []);
            
                    const suggest: YMapSearchControlProps['suggest'] = useCallback(({text}) => {
                        return searchFromList(text, LOCAL_LIST).map(
                            (object: ExtendedFeature) =>
                                ({
                                    uri: object.properties.name,
                                    title: {
                                        text: object.properties.name
                                    },
                                    subtitle: {
                                        text: object.properties.id
                                    }
                                } as SuggestResponseItem)
                        );
                    }, []);
            
                    const searchResult: YMapSearchControlProps['searchResult'] = useCallback((searchResult) => {
                        map.update({location: {center: searchResult[0].geometry.coordinates, ...COMMON_LOCATION_PARAMS}});
                    }, []);
            
                    return (
                        <div className="container">
                            <div className="list">
                                <span className="list__title">Your local list of objects</span>
                                <ul className="list__items">
                                    {LOCAL_LIST.map((object) => (
                                        <li className="list_item" key={object.properties.id}>
                                            <div className="list_item__icon">{object.properties.id}</div>
                                            <div className="list_item__text">{object.properties.name}</div>
                                        </li>
                                    ))}
                                </ul>
                            </div>
                            <div className="map">
                                <YMap location={LOCATION} showScaleInCopyrights={true} ref={(x) => (map = x)}>
                                    <YMapDefaultSchemeLayer />
            
                                    <YMapDefaultFeaturesLayer />
            
                                    <YMapControls position="top left">
                                        <YMapControl transparent>
                                            <div className="info-window">This is what users see</div>
                                        </YMapControl>
                                    </YMapControls>
            
                                    <YMapControls position="top right">
                                        <YMapSearchControl
                                            placeholder="Search from your objects"
                                            suggest={suggest}
                                            search={search}
                                            searchResult={searchResult}
                                        />
                                    </YMapControls>
            
                                    {LOCAL_LIST.map((marker) => (
                                        <YMapDefaultMarker
                                            key={marker.properties.id}
                                            coordinates={marker.geometry.coordinates}
                                            iconName={marker.properties.iconName}
                                            title={marker.properties.name}
                                            size="normal"
                                        />
                                    ))}
                                </YMap>
                            </div>
                        </div>
                    );
                }
            
                ReactDOM.render(
                    <React.StrictMode>
                        <App />
                    </React.StrictMode>,
                    document.getElementById('app')
                );
            }
        </script>

        <style> html, body, #app { width: 100%; height: 100%; margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; } .toolbar { position: absolute; z-index: 1000; top: 0; left: 0; display: flex; align-items: center; padding: 16px; } .toolbar a { padding: 16px; }  </style>
        <link rel="stylesheet" href="./common.css" />
        <link rel="stylesheet" href="../variables.css" />
    </head>
    <body>
        <div id="app"></div>
    </body>
</html>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
        <script crossorigin src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.js"></script>
        <script crossorigin src="https://cdn.jsdelivr.net/npm/@babel/standalone@7/babel.min.js"></script>
        <!-- To make the map appear, you must add your apikey -->
        <script src="https://api-maps.yandex.ru/v3/?apikey=<YOUR_APIKEY>&lang=en_US" type="text/javascript"></script>

        <script
            data-plugins="transform-modules-umd"
            data-presets="typescript"
            type="text/babel"
            src="../variables.ts"
        ></script>
        <script
            data-plugins="transform-modules-umd"
            data-presets="typescript"
            type="text/babel"
            src="./common.ts"
        ></script>
        <script data-plugins="transform-modules-umd" data-presets="typescript" type="text/babel">
            import type {YMapSearchControlProps} from '@yandex/ymaps3-default-ui-theme';
            import type {SuggestResponseItem} from '@yandex/ymaps3-types';
            import {COMMON_LOCATION_PARAMS, type ExtendedFeature, searchFromList} from './common';
            import {LOCAL_LIST, LOCATION} from '../variables';
            
            window.map = null;
            
            async function main() {
                // For each object in the JS API, there is a Vue counterpart
                // To use the Vue version of the API, include the module @yandex/ymaps3-vuefy
                const [ymaps3Vue] = await Promise.all([ymaps3.import('@yandex/ymaps3-vuefy'), ymaps3.ready]);
                const vuefy = ymaps3Vue.vuefy.bindTo(Vue);
                const {YMap, YMapDefaultSchemeLayer, YMapDefaultFeaturesLayer, YMapControls, YMapControl} = vuefy.module(ymaps3);
                const {YMapSearchControl, YMapDefaultMarker} = await vuefy.module(
                    await ymaps3.import('@yandex/ymaps3-default-ui-theme')
                );
            
                const app = Vue.createApp({
                    components: {
                        YMap,
                        YMapDefaultSchemeLayer,
                        YMapDefaultFeaturesLayer,
                        YMapControls,
                        YMapControl,
                        YMapSearchControl,
                        YMapDefaultMarker
                    },
                    setup() {
                        const refMap = (ref) => {
                            window.map = ref?.entity;
                        };
            
                        const search: YMapSearchControlProps['search'] = ({params}) => {
                            return searchFromList(params.text, LOCAL_LIST);
                        };
            
                        const suggest: YMapSearchControlProps['suggest'] = ({text}) => {
                            return searchFromList(text, LOCAL_LIST).map(
                                (object: ExtendedFeature) =>
                                    ({
                                        uri: object.properties.name,
                                        title: {
                                            text: object.properties.name
                                        },
                                        subtitle: {
                                            text: object.properties.id
                                        }
                                    } as SuggestResponseItem)
                            );
                        };
            
                        const searchResult: YMapSearchControlProps['searchResult'] = (searchResult) => {
                            map.update({location: {center: searchResult[0].geometry.coordinates, ...COMMON_LOCATION_PARAMS}});
                        };
            
                        return {
                            LOCATION,
                            LOCAL_LIST,
                            refMap,
                            search,
                            suggest,
                            searchResult
                        };
                    },
                    template: `
                  <div class="container">
                    <div class="list">
                      <span class="list__title">Your local list of objects</span>
                      <ul class="list__items">
                        <template v-for="object in LOCAL_LIST" :key="object.properties.id">
                          <li class="list_item">
                            <div class="list_item__icon">{{ object.properties.id }}</div>
                            <div class="list_item__text">{{ object.properties.name }}</div>
                          </li>
                        </template>
                      </ul>
                    </div>
                    <div class="map">
                      <!-- Initialize the map and pass initialization parameters -->
                      <YMap
                        :location="LOCATION"
                        :showScaleInCopyrights="true"
                        :ref="refMap"
                      >
                        <!-- Add a map scheme layer -->
                        <YMapDefaultSchemeLayer/>
            
                        <YMapDefaultFeaturesLayer/>
                        
                        <YMapControls position="top left">
                          <YMapControl :transparent="true">
                            <div class="info-window">
                              This is what users see
                            </div>
                          </YMapControl>
                        </YMapControls>
            
                        <YMapControls position="top right">
                          <YMapSearchControl
                            placeholder="Search from your objects"
                            :suggest="suggest"
                            :search="search"
                            :searchResult="searchResult"
                          />
                        </YMapControls>
            
                        <template v-for="object in LOCAL_LIST" :key="object.properties.id">
                          <YMapDefaultMarker
                            :coordinates="object.geometry.coordinates"
                            :iconName="object.properties.iconName"
                            :title="object.properties.name"
                            size="normal"
                          />
                        </template>
                      </YMap>
                    </div>
                  </div>
                `
                });
                app.mount('#app');
            }
            
            main();
        </script>

        <style> html, body, #app { width: 100%; height: 100%; margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; } .toolbar { position: absolute; z-index: 1000; top: 0; left: 0; display: flex; align-items: center; padding: 16px; } .toolbar a { padding: 16px; }  </style>
        <link rel="stylesheet" href="./common.css" />
        <link rel="stylesheet" href="../variables.css" />
    </head>
    <body>
        <div id="app"></div>
    </body>
</html>
import type {YMapCenterZoomLocation} from '@yandex/ymaps3-types';
import type {ExtendedFeature} from './common';

export const LOCATION: YMapCenterZoomLocation = {
    center: [49.1117, 55.7995],
    zoom: 12.5
};

export const LOCAL_LIST: Array<ExtendedFeature> = [
    {
        properties: {
            name: 'School',
            id: '1',
            iconName: 'college',
            description: null
        },
        geometry: {
            type: 'Point',
            coordinates: [49.0519, 55.821]
        }
    },
    {
        properties: {
            name: 'Hospital',
            id: '2',
            iconName: 'hospital',
            description: null
        },
        geometry: {
            type: 'Point',
            coordinates: [49.1171, 55.8266]
        }
    },
    {
        properties: {
            name: 'Shopping mall',
            id: '3',
            iconName: 'malls',
            description: null
        },
        geometry: {
            type: 'Point',
            coordinates: [49.1717, 55.7818]
        }
    },
    {
        properties: {
            name: 'Business center',
            id: '4',
            iconName: 'office',
            description: null
        },
        geometry: {
            type: 'Point',
            coordinates: [49.1024, 55.7732]
        }
    },
    {
        properties: {
            name: 'Sport center',
            id: '5',
            iconName: 'sportcenter',
            description: null
        },
        geometry: {
            type: 'Point',
            coordinates: [49.1038, 55.7957]
        }
    },
    {
        properties: {
            name: 'University',
            id: '6',
            iconName: 'college',
            description: null
        },
        geometry: {
            type: 'Point',
            coordinates: [49.2026, 55.8077]
        }
    },
    {
        properties: {
            name: 'Spa and beauty salon',
            id: '7',
            iconName: 'spa',
            description: null
        },
        geometry: {
            type: 'Point',
            coordinates: [49.1427, 55.791]
        }
    },
    {
        properties: {
            name: 'Boat',
            id: '8',
            iconName: 'boat_station',
            description: null
        },
        geometry: {
            type: 'Point',
            coordinates: [49.0759, 55.7599]
        }
    }
];
:root {
    --icon-background-color: rgba(235, 85, 71, 1);
}
import type {Feature} from '@yandex/ymaps3-types';
import type {YMapDefaultMarkerProps} from '@yandex/ymaps3-default-ui-theme';
import type {YMapLocationRequest} from '@yandex/ymaps3-types/imperative/YMap';

export type ExtendedFeature = {
    properties: Feature['properties'] & {
        id: string;
        iconName: YMapDefaultMarkerProps['iconName'];
    };
    geometry: Feature['geometry'];
};

ymaps3.ready.then(() => {
    ymaps3.import.registerCdn('https://cdn.jsdelivr.net/npm/{package}', '@yandex/ymaps3-default-ui-theme@0.0');
});

export const COMMON_LOCATION_PARAMS: YMapLocationRequest = {easing: 'ease-in-out', duration: 2000, zoom: 16};

export function searchFromList(text: string, objects: ExtendedFeature[]): Feature[] {
    const trimmedText = text.trim().toLowerCase();
    return objects.filter((object) => {
        const trimmedObjectName = object.properties.name.trim().toLowerCase();
        const trimmedObjectDescription = object.properties.id.trim().toLowerCase();
        return trimmedObjectDescription.includes(trimmedText) || trimmedObjectName.includes(trimmedText);
    });
}
.info-window {
    padding: 8px 12px 8px 40px;
    border-radius: 12px;
    background-color: #313133;
    background-image: url('./info-icon.svg');
    background-position: 10px 8px;
    background-repeat: no-repeat;
    color: #f2f5fa;
    font-size: 14px;
    line-height: 20px;
    min-width: max-content;
}

.container {
    width: 100%;
    height: 100%;
    display: flex;
    gap: 10px;
}

.map {
    border-radius: 8px;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    overflow: hidden;
}

.list {
    width: 260px;
    flex-shrink: 0;
    border-radius: 8px;
    border: 1px solid rgba(92, 94, 102, 0.14);
    padding: 12px;
    box-sizing: border-box;
}

.list__title {
    line-height: 20px;
    font-weight: 500;
    font-size: 14px;
    color: #000;
}

.list__items {
    list-style: none;
    margin-top: 24px;
    padding: 0;
}

.list_item {
    display: flex;
    flex-direction: row;
    gap: 8px;
    margin-top: 12px;
}

.list_item__icon {
    width: 16px;
    height: 16px;
    border-radius: 4px;
    text-align: center;
    background-color: var(--icon-background-color);
    color: #ffffff;
    font-weight: 700;
    font-size: 11px;
    line-height: 16px;
}

.list_item__text {
    font-size: 14px;
}