YMapSearchControl

Класс YMapSearchControl — добавляет элемент управления на карту в виде строки поиска. Также в него встроены подсказки при вводе названия места или организации.

YMapSearchControl не отображает маркеры на карте, он только возвращает координаты и параметры местоположения, за их отображение на карте отвечает разработчик.

Примечание

Данный класс является компонентом пакета @yandex/ymaps3-default-ui-theme и предоставляет дополнительную функциональность в JS API, которая не входит в основное API.

Для подключения пакета воспользуйтесь инструкцией.

Пример использования

<!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="./common.ts"
    ></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">
      import type {SearchResponse} from '@yandex/ymaps3-types';
      import {LOCATION, MARGIN, initialMarkerProps} from '../variables';
      import {findSearchResultBoundsRange} from './common';

      window.map = null;

      main();
      async function main() {
        // Waiting for all api elements to be loaded
        await ymaps3.ready;
        const {YMap, YMapDefaultSchemeLayer, YMapDefaultFeaturesLayer, YMapControls} = ymaps3;

        const {YMapDefaultMarker, YMapSearchControl} = await ymaps3.import(
          '@yandex/ymaps3-default-ui-theme'
        );

        map = new YMap(document.getElementById('app'), {location: LOCATION, margin: MARGIN});

        map.addChild(new YMapDefaultSchemeLayer({}));
        map.addChild(new YMapDefaultFeaturesLayer({}));

        const initialMarker = new YMapDefaultMarker({
          title: initialMarkerProps.properties.name,
          subtitle: initialMarkerProps.properties.description,
          coordinates: initialMarkerProps.geometry.coordinates,
          size: 'normal',
          iconName: 'fallback',
          onClick: () => {
            map.removeChild(initialMarker);
          }
        });
        map.addChild(initialMarker);
        const searchMarkers = [initialMarker];

        const updateSearchMarkers = (searchResult: SearchResponse) => {
          searchMarkers.forEach((marker) => {
            map.removeChild(marker);
          });

          searchResult.forEach((element) => {
            const marker = new YMapDefaultMarker({
              title: element.properties.name,
              subtitle: element.properties?.description,
              coordinates: element.geometry.coordinates,
              size: 'normal',
              iconName: 'fallback',
              onClick: () => {
                map.removeChild(marker);
              }
            });
            map.addChild(marker);
            searchMarkers.push(marker);
          });
        };

        const updateMapLocation = (searchResult: SearchResponse) => {
          if (searchResult.length !== 0) {
            let center;
            let zoom;
            let bounds;

            if (searchResult.length === 1) {
              center = searchResult[0].geometry?.coordinates;
              zoom = 12;
            } else {
              bounds = findSearchResultBoundsRange(searchResult);
            }

            map.update({
              location: {
                center,
                zoom,
                bounds,
                duration: 400
              }
            });
          }
        };

        const searchResultHandler = (searchResult: SearchResponse) => {
          updateSearchMarkers(searchResult);
          updateMapLocation(searchResult);
        };

        map.addChild(
          new YMapControls({position: 'top'}).addChild(
            new YMapSearchControl({
              searchResult: searchResultHandler
            })
          )
        );
      }
    </script>

    <!-- prettier-ignore -->
    <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" />
  </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/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="./common.ts"
    ></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="react, typescript" type="text/babel">
      import type {SearchResponse, Feature} from '@yandex/ymaps3-types';
      import {LOCATION, MARGIN, initialMarkerProps} from '../variables';
      import {findSearchResultBoundsRange} from './common';

      window.map = null;

      main();
      async function main() {
        // For each object in the JS API, there is a React counterpart
        // To use the React version of the API, include the module @yandex/ymaps3-reactify
        const [ymaps3React] = await Promise.all([
          ymaps3.import('@yandex/ymaps3-reactify'),
          ymaps3.ready
        ]);
        const reactify = ymaps3React.reactify.bindTo(React, ReactDOM);

        const {useState, useCallback} = React;

        const {YMap, YMapDefaultSchemeLayer, YMapDefaultFeaturesLayer, YMapControls} = reactify.module(ymaps3);

        const {YMapDefaultMarker, YMapSearchControl} = reactify.module(
          await ymaps3.import('@yandex/ymaps3-default-ui-theme')
        );

        ReactDOM.render(
          <React.StrictMode>
            <App />
          </React.StrictMode>,
          document.getElementById('app')
        );

        function App() {
          const [location, setLocation] = useState(LOCATION);
          const [searchMarkersProps, setSearchMarkersProps] = useState([initialMarkerProps]);

          const updateMapLocation = useCallback((searchResult: SearchResponse) => {
            if (searchResult.length !== 0) {
              let center;
              let zoom;
              let bounds;

              if (searchResult.length === 1) {
                center = searchResult[0].geometry?.coordinates;
                zoom = 12;
              } else {
                bounds = findSearchResultBoundsRange(searchResult);
              }

              setLocation({
                center,
                zoom,
                bounds,
                duration: 400
              });
            }
          }, []);

          const searchResultHandler = useCallback((searchResult: SearchResponse) => {
            setSearchMarkersProps(searchResult);
            updateMapLocation(searchResult);
          }, []);

          const onClickSearchMarkerHandler = useCallback(
            (clickedMarker: Feature) => {
              setSearchMarkersProps(searchMarkersProps.filter((marker) => marker !== clickedMarker));
            },
            [searchMarkersProps]
          );

          return (
            <YMap location={location} margin={MARGIN} ref={(x) => (map = x)}>
              <YMapDefaultSchemeLayer />
              <YMapDefaultFeaturesLayer />
              <YMapControls position="top">
                <YMapSearchControl searchResult={searchResultHandler} />
              </YMapControls>

              {searchMarkersProps.map((marker) => (
                <YMapDefaultMarker
                  key={+marker.geometry.coordinates}
                  title={marker.properties.name}
                  subtitle={marker.properties.description}
                  coordinates={marker.geometry.coordinates}
                  onClick={() => onClickSearchMarkerHandler(marker)}
                  size="normal"
                  iconName="fallback"
                />
              ))}
            </YMap>
          );
        }
      }
    </script>

    <!-- prettier-ignore -->
    <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" />
  </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>

    <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="./common.ts"
    ></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">
      import type {Feature, SearchResponse} from '@yandex/ymaps3-types';
      import {LOCATION, MARGIN, initialMarkerProps} from '../variables';
      import {findSearchResultBoundsRange} from './common';

      window.map = null;

      main();
      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 {createApp, ref} = Vue;

        const {YMap, YMapDefaultSchemeLayer, YMapDefaultFeaturesLayer, YMapControls} = vuefy.module(ymaps3);

        const {YMapDefaultMarker, YMapSearchControl} = vuefy.module(
          await ymaps3.import('@yandex/ymaps3-default-ui-theme')
        );

        const app = createApp({
          components: {
            YMap,
            YMapDefaultSchemeLayer,
            YMapDefaultFeaturesLayer,
            YMapControls,
            YMapDefaultMarker,
            YMapSearchControl
          },
          setup() {
            const refMap = (ref: any) => {
              window.map = ref?.entity;
            };

            const location = ref(LOCATION);

            const searchMarkersProps = ref([initialMarkerProps]);

            const updateMapLocation = (searchResult: SearchResponse) => {
              if (searchResult.length !== 0) {
                let center;
                let zoom;
                let bounds;

                if (searchResult.length === 1) {
                  center = searchResult[0].geometry?.coordinates;
                  zoom = 12;
                } else {
                  bounds = findSearchResultBoundsRange(searchResult);
                }

                location.value = {
                  center,
                  zoom,
                  bounds,
                  duration: 400
                };
              }
            };

            const searchResultHandler = (searchResult: SearchResponse) => {
              searchMarkersProps.value = searchResult;
              updateMapLocation(searchResult);
            };

            const onClickSearchMarkerHandler = (clickedMarker: Feature) => {
              searchMarkersProps.value = searchMarkersProps.value.filter((marker) => marker !== clickedMarker);
            };

            return {location, MARGIN, refMap, searchResultHandler, searchMarkersProps, onClickSearchMarkerHandler};
          },
          template: `
            <YMap :location="location" :margin="MARGIN" :ref="refMap">
                <YMapDefaultSchemeLayer />
                <YMapDefaultFeaturesLayer />
                <YMapControls position="top">
                    <YMapSearchControl :searchResult="searchResultHandler" />
                </YMapControls>

                <YMapDefaultMarker
                    v-for="marker in searchMarkersProps"
                    :key="marker.geometry.coordinates"
                    :title="marker.properties.name"
                    :subtitle="marker.properties.description"
                    :coordinates="marker.geometry.coordinates"
                    :onClick="()=>onClickSearchMarkerHandler(marker)"
                    size="normal"
                    iconName="fallback"
                />
            </YMap>`
        });
        app.mount('#app');
      }
    </script>

    <!-- prettier-ignore -->
    <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" />
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>

Конструктор

new YMapSearchControl(props)

Параметры конструктора

Параметр

Тип

props

YMapSearchControlProps

Унаследовано от

YMapComplexEntity.constructor

Props

type YMapSearchControlProps = {
    placeholder?: string;
    search?: SearchCallback;
    suggest?: SuggestCallback;
    searchResult: SearchResultCallback;
};

Параметры

Параметр

Описание

search

Функция, которая переопределяет функцию search. По умолчанию используется ymaps3.search

suggest

Функция, которая переопределяет функцию suggest. По умолчанию используется ymaps3.suggest

searchResult

Обратный вызов, который получает результаты поиска.

Методы

update

update(changedProps): void

Параметр

Тип

Описание

changedProps

Partial<YMapSearchControlProps>

Новые значения props.

Возвращается

void

Унаследовано от

YMapComplexEntity.update

Предыдущая