Добавление контрола геолокации на карту

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="./common.ts"
        ></script>
        <script data-plugins="transform-modules-umd" data-presets="typescript" type="text/babel">
            import {LOCATION, InfoMessage, COMMON_LOCATION_PARAMS} 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;
            
                // Load the control package and extract the geolocation control from it
                const {YMapGeolocationControl} = 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({}),
                        // Add a layer of geo objects to display the geolocation marker
                        new YMapDefaultFeaturesLayer({})
                    ]
                );
            
                map.addChild(
                    // Using YMapControls you can change the position of the control
                    new YMapControls({position: 'right'})
                        // Add the geolocation control to the map
                        .addChild(new YMapGeolocationControl(COMMON_LOCATION_PARAMS))
                );
                map.addChild(
                    // Using YMapControls you can change the position of the control
                    new YMapControls({position: 'top left'})
                        // Add the geolocation control to the map
                        .addChild(
                            new InfoMessage({
                                text: 'Click on the button on the right side'
                            })
                        )
                );
            }
        </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" />
    </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="react, typescript" type="text/babel">
            import type {LngLat} from '@yandex/ymaps3-types';
            import {LOCATION, InfoMessage, COMMON_LOCATION_PARAMS} 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 {YMap, YMapDefaultSchemeLayer, YMapDefaultFeaturesLayer, YMapControls, YMapListener} =
                    reactify.module(ymaps3);
            
                // Load the control package and extract the geolocation control from it
                const {YMapGeolocationControl} = reactify.module(await ymaps3.import('@yandex/ymaps3-default-ui-theme'));
            
                // Using ymaps3-rectify, we turn a custom InfoMessage and EventListener into a React component
                const InfoMessageR = reactify.entity(InfoMessage);
            
                function App() {
                    return (
                        // Initialize the map and pass initialization parameters
                        <YMap location={LOCATION} showScaleInCopyrights={true} ref={(x) => (map = x)}>
                            {/* Add a map scheme layer */}
                            <YMapDefaultSchemeLayer />
                            {/* Add a layer of geo objects to display the geolocation marker */}
                            <YMapDefaultFeaturesLayer />
                            {/* Using YMapControls you can change the position of the control */}
                            <YMapControls position="right">
                                {/* Add the geolocation control to the map */}
                                <YMapGeolocationControl {...COMMON_LOCATION_PARAMS} />
                            </YMapControls>
                            {/* Create Info Message */}
                            <YMapControls position="top left">
                                <InfoMessageR text="Click on the button on the right side" />
                            </YMapControls>
                        </YMap>
                    );
                }
            
                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" />
    </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="./common.ts"
        ></script>
        <script data-plugins="transform-modules-umd" data-presets="typescript" type="text/babel">
            import {COMMON_LOCATION_PARAMS, InfoMessage, LOCATION} from './common';
            
            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} = vuefy.module(ymaps3);
            
                // Load the control package and extract the geolocation control from it
                const {YMapGeolocationControl} = vuefy.module(await ymaps3.import('@yandex/ymaps3-default-ui-theme'));
            
                // Using ymaps3-vuefy, we turn a custom InfoMessage and EventListener into a Vue component
                const InfoMessageV = vuefy.entity(InfoMessage, {text: String});
            
                const app = Vue.createApp({
                    components: {
                        YMap,
                        YMapDefaultSchemeLayer,
                        YMapDefaultFeaturesLayer,
                        YMapControls,
                        YMapGeolocationControl,
                        InfoMessageV
                    },
                    setup() {
                        const refMap = (ref) => {
                            window.map = ref?.entity;
                        };
            
                        return {LOCATION, refMap, COMMON_LOCATION_PARAMS};
                    },
                    template: `
                  <!--Initialize the map and pass initialization parameters-->
                  <YMap :location="LOCATION" :showScaleInCopyrights="true" :ref="refMap">
                    <!--Add a map scheme layer-->
                    <YMapDefaultSchemeLayer/>
                    <YMapDefaultFeaturesLayer/>
                    <!-- Using YMapControls you can change the position of the control -->
                    <YMapControls position="right">
                      <!-- Add the geolocation control to the map -->
                      <YMapGeolocationControl v-bind="COMMON_LOCATION_PARAMS"/>
                    </YMapControls>
                    <!-- Using YMapControls you can change the position of the info window -->
                    <YMapControls position="top left">
                      <!-- Add the geolocation control to the map -->
                      <InfoMessageV text="Click on the button on the right side" />
                    </YMapControls>
                  </YMap>`
                });
                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" />
    </head>
    <body>
        <div id="app"></div>
    </body>
</html>
import type {YMapLocationRequest, YMapComplexEntity} from '@yandex/ymaps3-types';

// Wait for the api to load to access the map configuration
ymaps3.ready.then(() => {
    ymaps3.import.registerCdn('https://cdn.jsdelivr.net/npm/{package}', '@yandex/ymaps3-default-ui-theme@0.0');
});

export const LOCATION: YMapLocationRequest = {
    center: [19.04096055984523, 30.046728482547582], // starting position [lng, lat]
    zoom: 3 // starting zoom
};

/* Initialize a custom information message control
Assign a value to it after loading the map api */
export let InfoMessage: new (...args: any[]) => YMapComplexEntity<InfoMessageProps> = null;

interface InfoMessageProps {
    text: string;
}

// Wait for the api to load to access the entity system (YMapComplexEntity)
ymaps3.ready.then(() => {
    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('infoWindow');
            infoWindow.innerHTML = 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;
        }
    }
    InfoMessage = InfoMessageClass;
});

export const COMMON_LOCATION_PARAMS: YMapLocationRequest = {easing: 'ease-in-out', duration: 2000, zoom: 15};
.infoWindow {
    padding: 8px 12px 8px 32px;
    border-radius: 8px;
    background-color: #313133;
    background-image: url('./info-icon.svg');
    background-position: 8px 50%;
    background-repeat: no-repeat;
    gap: 8px;
    color: #f2f5fa;
    font-size: 14px;
    line-height: 20px;
}