Создание перетаскиваемого маркера

Open on 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 type {LngLat, YMapCenterLocation} from '@yandex/ymaps3-types';
      import {LOCATION} from './common';

      window.map = null;

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

          // Import the package to add a default marker
          const {YMapDefaultMarker} = await ymaps3.import('@yandex/ymaps3-markers@0.0.1');

          // 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 markers
                  new YMapDefaultFeaturesLayer({})
              ]
          );

          // Create a handler function that will update the parameters of marker on drag move
          function onDragMoveHandler(coordinates: LngLat) {
              const longitude = `Longitude: ${coordinates[0].toFixed(2)}`;
              const latitude = `Latitude: ${coordinates[1].toFixed(2)}`;
              draggableMarker.update({coordinates, title: `${longitude} <br> ${latitude}`});
          }

          /* Create and add a marker to the map.
          To make it draggable, add the draggable = true parameter */
          const draggableMarker = new YMapDefaultMarker({
              coordinates: (LOCATION as YMapCenterLocation).center,
              draggable: true,
              title: `Longitude: ${(LOCATION as YMapCenterLocation).center[0].toFixed(2)} <br>
              Latitude: ${(LOCATION as YMapCenterLocation).center[1].toFixed(2)}`,
              onDragMove: onDragMoveHandler
          });

          map.addChild(draggableMarker);
      }
    </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>
  </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="react, typescript"
      type="text/babel"
      src="./common.ts"
    ></script>
    <script data-plugins="transform-modules-umd" data-presets="react, typescript" type="text/babel">
      import type {LngLat, YMapCenterLocation} from '@yandex/ymaps3-types';
      import {LOCATION} 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} = reactify.module(ymaps3);

          // Import the package to add a default marker
          const {YMapDefaultMarker} = reactify.module(await ymaps3.import('@yandex/ymaps3-markers@0.0.1'));

          const {useState, useCallback} = React;
          function App() {
              // Declare the initial states of the marker
              const [markerTitle, setMarkerTitle] = useState(
                  `Longitude: ${(LOCATION as YMapCenterLocation).center[0].toFixed(2)} <br>
                  Latitude: ${(LOCATION as YMapCenterLocation).center[1].toFixed(2)}`
              );
              const [markerCoordinates, setMarkerCoordinates] = useState((LOCATION as YMapCenterLocation).center);

              // Create a handler function that will update the parameters of marker on drag move
              const onDragMoveHandler = useCallback((coordinates: LngLat) => {
                  const longitude = `Longitude: ${coordinates[0].toFixed(2)}`;
                  const latitude = `Latitude: ${coordinates[1].toFixed(2)}`;
                  setMarkerTitle(`${longitude} <br> ${latitude}`);
                  setMarkerCoordinates(coordinates);
              }, []);

              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 markers */}
                      <YMapDefaultFeaturesLayer />

                      {/* Add a marker to the map. To make it draggable, add the draggable = true parameter */}
                      <YMapDefaultMarker
                          coordinates={markerCoordinates}
                          draggable
                          title={markerTitle}
                          onDragMove={onDragMoveHandler}
                      />
                  </YMap>
              );
          }

          ReactDOM.render(
              <React.StrictMode>
                  <App />
              </React.StrictMode>,
              document.getElementById('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>
  </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 type {LngLat, YMapCenterLocation} from '@yandex/ymaps3-types';
      import {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} = vuefy.module(ymaps3);

        // Import the package to add a default marker
        const {YMapDefaultMarker} = vuefy.module(await ymaps3.import('@yandex/ymaps3-markers@0.0.1'));

        const app = Vue.createApp({
          components: {
            YMap,
            YMapDefaultSchemeLayer,
            YMapDefaultFeaturesLayer,
            YMapDefaultMarker
          },
          setup() {
            const refMap = (ref) => {
              window.map = ref?.entity;
            };
            const createMarkerTitleFromCoords = (coordinates: LngLat) => {
              return `Longitude: ${coordinates[0].toFixed(2)} <br> Latitude: ${coordinates[1].toFixed(2)}`;
            };

            const markerCoordinates = Vue.ref(LOCATION.center);
            const markerTitle = Vue.ref(createMarkerTitleFromCoords(markerCoordinates.value));

            const onDragMoveHandler = (coordinates) => {
              markerTitle.value = createMarkerTitleFromCoords(coordinates);
              markerCoordinates.value = coordinates;
            };

            return {
              LOCATION,
              refMap,
              markerCoordinates,
              markerTitle,
              onDragMoveHandler
            };
          },
          template: `
          <!--Initialize the map and pass initialization parameters-->
          <YMap :location="LOCATION" :showScaleInCopyrights="true" :ref="refMap">
            <!--Add a map scheme layer-->
            <YMapDefaultSchemeLayer/>

            <!-- Add a layer of geo objects to display the markers -->
            <YMapDefaultFeaturesLayer/>

            <!-- Add a marker to the map. To make it draggable, add the draggable = true parameter -->
            <YMapDefaultMarker
                :coordinates="markerCoordinates"
                :draggable="true"
                :title="markerTitle"
                @drag-move="onDragMoveHandler"
            />
          </YMap>`
        });
        app.mount('#app');
      }
      main();
    </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>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>
import type {YMapLocationRequest} from '@yandex/ymaps3-types';

export const LOCATION: YMapLocationRequest = {
  center: [37.62, 55.75], // starting position [lng, lat]
  zoom: 9 // starting zoom
};