YMapHint

YMapHint — всплывающая подсказка(hint), которая может отображать текстовую или графическую информацию.

Класс YMapHint отображает подсказки на элементах карты с заданными координатами, а их содержимое может содержать HTML-разметку.

Всплывающая подсказка, существует в единственном экземпляре и создается вместе с картой. Открывая новый hint, уже открытый hint на карте, закрывается.

Примечание

Данный класс является компонентом пакета @yandex/ymaps3-hint и предоставляет дополнительную функциональность в 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 src='https://api-maps.yandex.ru/v3/?apikey=%APIKEY%&lang=en_US'></script>
        <script src="common.js"></script>
        <title>Test</title>
        <script>
            window.map = null;
            const {YMapHint, YMapHintContext} = await ymaps3.import('@yandex/ymaps3-hint@0.0.1');
            map.addChild(defaultFeatures = new YMapDefaultFeaturesLayer());
            map.addChild(hint = YMapHint({
               layers: [defaultFeatures.layer],
               hint: object =&gt; object?.properties?.hint
            }));

                        main();
                        async function main() {
                            await ymaps3.ready;
                            const {
                                YMap,
                                YMapDefaultSchemeLayer,
                                YMapDefaultFeaturesLayer,
                                YMapControls,
                                YMapCollection,
                                YMapMarker,
                                YMapFeature,

                                YMapEntity
                            } = ymaps3;

                            const {YMapZoomControl} = await ymaps3.import('@yandex/ymaps3-default-ui-theme');
                            const {YMapHint, YMapHintContext} = await ymaps3.import('@yandex/ymaps3-hint');

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

                            map.addChild(new YMapDefaultSchemeLayer());
                            map.addChild((defaultFeatures = new YMapDefaultFeaturesLayer()));

                            map.addChild(new YMapControls({position: 'right'}).addChild(new YMapZoomControl({})));

                            const bounds = map.bounds;

                            const markers = new YMapCollection({});
                            POINTS.forEach(({coordinates, hint, color}) => {
                                const marker = new YMapMarker({coordinates, properties: {hint}});
                                marker.element.style.transform = 'translate(-15px, -33px)';
                                marker.element.style.position = 'absolute';
                                marker.element.innerHTML = markerSvg(color);

                                markers.addChild(marker);
                            });

                            const lines = new YMapCollection({});
                            LINES.forEach(({geometry, hint, style}) => {
                                lines.addChild(new YMapFeature({geometry, style, properties: {hint}}));
                            });

                            const triangles = new YMapCollection({});
                            TRIANGLES.forEach(({geometry, hint, style}) => {
                                triangles.addChild(new YMapFeature({geometry, style, properties: {hint}}));
                            });

                            map.addChild(markers);
                            map.addChild(lines);
                            map.addChild(triangles);

                            map.addChild(
                                (hint = new YMapHint({
                                    layers: [defaultFeatures.layer],
                                    hint: (object) => object?.properties?.hint
                                }))
                            );

                            hint.addChild(
                                new (class MyHint extends YMapEntity {
                                    _onAttach() {
                                        this._element = document.createElement('div');
                                        this._element.className = 'my-hint';

                                        this._detachDom = ymaps3.useDomContext(this, this._element);
                                        this._watchContext(
                                            YMapHintContext,
                                            () => {
                                                this._element.textContent = this._consumeContext(YMapHintContext)?.hint;
                                            },
                                            {immediate: true}
                                        );
                                    }
                                    _onDetach() {
                                        this._detachDom();
                                    }
                                })()
                            );
                        }
        </script>

        <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://unpkg.com/react@17/umd/react.production.min.js"></script>
        <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
        <script crossorigin src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
        <script src='https://api-maps.yandex.ru/v3/?apikey=%APIKEY%&lang=en_US'></script>
        <script src="common.js"></script>

        <script type="text/babel">
            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,

                    YMapCollection,
                    YMapMarker,
                    YMapFeature
                } = reactify.module(ymaps3);
                const {useState, useCallback} = React;

                const {YMapZoomControl} = reactify.module(await ymaps3.import('@yandex/ymaps3-default-ui-theme'));
                const {YMapHint, YMapHintContext} = reactify.module(await ymaps3.import('@yandex/ymaps3-hint'));
                ReactDOM.render(
                    <React.StrictMode>
                        <App />
                    </React.StrictMode>,
                    document.getElementById('app')
                );

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

                    const getHint = useCallback((object) => object && object.properties && object.properties.hint, []);

                    return (
                        <YMap location={location} ref={(x) => (map = x)}>
                            <YMapDefaultSchemeLayer />
                            <YMapDefaultFeaturesLayer />
                            <YMapControls position="right">
                                <YMapZoomControl />
                            </YMapControls>

                            <YMapHint hint={getHint}>
                                <MyHint />
                            </YMapHint>

                            <YMapCollection>
                                {POINTS.map(({coordinates, hint, color}, ix) => (
                                    <MyMarker key={ix} coordinates={coordinates} properties={{hint}} color={color} />
                                ))}
                            </YMapCollection>
                            <YMapCollection>
                                {LINES.map(({geometry, hint, style}, ix) => (
                                    <YMapFeature key={ix} geometry={geometry} style={style} properties={{hint}} />
                                ))}
                            </YMapCollection>
                            <YMapCollection>
                                {TRIANGLES.map(({geometry, hint, style}, ix) => (
                                    <YMapFeature key={ix} geometry={geometry} style={style} properties={{hint}} />
                                ))}
                            </YMapCollection>
                        </YMap>
                    );
                }
                function MyMarker({coordinates, properties, color}) {
                    return (
                        <YMapMarker properties={properties} coordinates={coordinates}>
                            <div
                                dangerouslySetInnerHTML={{__html: markerSvg(color)}}
                                style={{transform: 'translate(-15px, -33px)', position: 'absolute'}}
                            ></div>
                        </YMapMarker>
                    );
                }
                function MyHint() {
                    const ctx = React.useContext(YMapHintContext);
                    return <div className="my-hint">{ctx && ctx.hint}</div>;
                }
            }
        </script>

<!--        <link rel="stylesheet" href="../common.css" />-->
        <link rel="stylesheet" href="common.css" />
    </head>
    <body>
        <div id="app"></div>
    </body>
</html>

Подробный пример

Конструктор

new YMapHint(props)

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

Параметр

Тип

props

YMapHintProps

Переопределяет

YMapGroupEntity.constructor

Props

YMapHintProps: Object

Параметры

Параметр

Тип

hint

(object: YMapFeature | YMapMarker | YMapHotspot | undefined) => unknown

Методы

addChild

addChild(child, index?): YMapHint

Параметры

Параметр

Тип

child

YMapEntity<unknown, {}>

index?

number

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

YMapHint

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

YMapGroupEntity.addChild

removeChild

removeChild(child): YMapHint

Параметры

Параметр

Тип

child

YMapEntity<unknown, {}>

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

YMapHint

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

YMapGroupEntity.removeChild

update

update(changedProps): void

Параметры

Параметр

Тип

Описание

changedProps

Partial<YMapHintProps>

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

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

void

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

YMapGroupEntity.update