Create a draggable marker

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://js.api.mappable.world/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 {LngLat, MMapCenterLocation} from '@mappable-world/mappable-types';
            import {LOCATION} from '../variables';
            import {createMarkerTitleFromCoords, InfoMessage} from './common';
            
            window.map = null;
            
            main();
            async function main() {
                // Waiting for all api elements to be loaded
                await mappable.ready;
                const {MMap, MMapDefaultSchemeLayer, MMapDefaultFeaturesLayer, MMapControls} = mappable;
            
                // Import the package to add a default marker
                const {MMapDefaultMarker} = await mappable.import('@mappable-world/mappable-default-ui-theme');
            
                // Initialize the map
                map = new MMap(
                    // 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 MMapDefaultSchemeLayer({}),
                        // Add a layer of geo objects to display the markers
                        new MMapDefaultFeaturesLayer({})
                    ]
                );
            
                // Create a handler function that will update the parameters of marker on drag move
                function onDragMoveHandler(coordinates: LngLat) {
                    draggableMarker.update({coordinates, title: createMarkerTitleFromCoords(coordinates)});
                }
            
                /* Create and add a marker to the map.
              To make it draggable, add the draggable = true parameter */
                const draggableMarker = new MMapDefaultMarker({
                    coordinates: (LOCATION as MMapCenterLocation).center,
                    draggable: true,
                    size: 'normal',
                    iconName: 'fallback',
                    title: createMarkerTitleFromCoords((LOCATION as MMapCenterLocation).center),
                    onDragMove: onDragMoveHandler
                });
            
                map.addChild(draggableMarker);
            
                /* Create and add a shared container for controls to the map. */
                const topLeftControl = new MMapControls({position: 'top left'});
                // Add a custom information message control to the map
                topLeftControl.addChild(new InfoMessage({text: 'Try to drag a marker'}));
            
                map.addChild(topLeftControl);
            }
        </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/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://js.api.mappable.world/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 {LngLat, MMapCenterLocation} from '@mappable-world/mappable-types';
            import {LOCATION} from '../variables';
            import {createMarkerTitleFromCoords, InfoMessage} 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 @mappable-world/mappable-reactify
                const [mappableReact] = await Promise.all([mappable.import('@mappable-world/mappable-reactify'), mappable.ready]);
                const reactify = mappableReact.reactify.bindTo(React, ReactDOM);
                const {MMap, MMapDefaultSchemeLayer, MMapDefaultFeaturesLayer, MMapControls} = reactify.module(mappable);
            
                // Import the package to add a default marker
                const {MMapDefaultMarker} = await reactify.module(await mappable.import('@mappable-world/mappable-default-ui-theme'));
            
                // Using mappable-rectify, we turn a custom InfoMessage into a React component
                const {InfoMessage: InfoMessageR} = reactify.module({InfoMessage});
            
                const {useState, useCallback} = React;
                function App() {
                    // Declare the initial states of the marker
                    const [markerTitle, setMarkerTitle] = useState(
                        createMarkerTitleFromCoords((LOCATION as MMapCenterLocation).center)
                    );
                    const [markerCoordinates, setMarkerCoordinates] = useState((LOCATION as MMapCenterLocation).center);
            
                    // Create a handler function that will update the parameters of marker on drag move
                    const onDragMoveHandler = useCallback((coordinates: LngLat) => {
                        setMarkerTitle(createMarkerTitleFromCoords(coordinates));
                        setMarkerCoordinates(coordinates);
                    }, []);
            
                    return (
                        // Initialize the map and pass initialization parameters
                        <MMap location={LOCATION} showScaleInCopyrights={true} ref={(x) => (map = x)}>
                            {/* Add a map scheme layer */}
                            <MMapDefaultSchemeLayer />
                            {/* Add a layer of geo objects to display the markers */}
                            <MMapDefaultFeaturesLayer />
            
                            {/* Add a marker to the map. To make it draggable, add the draggable = true parameter */}
                            <MMapDefaultMarker
                                coordinates={markerCoordinates}
                                draggable
                                title={markerTitle}
                                size="normal"
                                iconName="fallback"
                                onDragMove={onDragMoveHandler}
                            />
            
                            {/* Add a shared container for controls to the map.
                            Using MMapControls you can change the position of the control */}
                            <MMapControls position="top left">
                                {/* Add a custom information message control to the map */}
                                <InfoMessageR text="Try to drag a marker" />
                            </MMapControls>
                        </MMap>
                    );
                }
            
                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://js.api.mappable.world/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 {MMapCenterLocation} from '@mappable-world/mappable-types';
            import {LOCATION} from '../variables';
            import {createMarkerTitleFromCoords, InfoMessage} 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 @mappable-world/mappable-vuefy
                const [mappableVue] = await Promise.all([mappable.import('@mappable-world/mappable-vuefy'), mappable.ready]);
                const vuefy = mappableVue.vuefy.bindTo(Vue);
                const {MMap, MMapDefaultSchemeLayer, MMapDefaultFeaturesLayer, MMapControls} = vuefy.module(mappable);
            
                // Import the package to add a default marker
                const {MMapDefaultMarker} = await vuefy.module(await mappable.import('@mappable-world/mappable-default-ui-theme'));
            
                const {InfoMessage: InfoMessageV} = vuefy.module({InfoMessage});
            
                const app = Vue.createApp({
                    components: {
                        MMap,
                        MMapDefaultSchemeLayer,
                        MMapDefaultFeaturesLayer,
                        MMapDefaultMarker,
                        MMapControls,
                        InfoMessageV
                    },
                    setup() {
                        const refMap = (ref) => {
                            window.map = ref?.entity;
                        };
            
                        const markerCoordinates = Vue.ref((LOCATION as MMapCenterLocation).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-->
                      <MMap :location="LOCATION" :showScaleInCopyrights="true" :ref="refMap">
                        <!--Add a map scheme layer-->
                        <MMapDefaultSchemeLayer/>
            
                        <!-- Add a layer of geo objects to display the markers -->
                        <MMapDefaultFeaturesLayer/>
            
                        <!-- Add a marker to the map. To make it draggable, add the draggable = true parameter -->
                        <MMapDefaultMarker
                            :coordinates="markerCoordinates"
                            :draggable="true"
                            :title="markerTitle"
                            size="normal"
                            iconName="fallback"
                            @drag-move="onDragMoveHandler"
                        />
            
                        <MMapControls position="top left">
                          <InfoMessageV text="Try to drag a marker" />
                        </MMapControls>
                      </MMap>`
                });
                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 {MMapLocationRequest} from '@mappable-world/mappable-types';

export const LOCATION: MMapLocationRequest = {
    center: [55.428, 25.3556], // starting position [lng, lat]
    zoom: 14 // starting zoom
};
import type {LngLat} from '@mappable-world/mappable-types';

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

export const createMarkerTitleFromCoords = (coordinates: LngLat) => {
    return `${coordinates[0].toFixed(4)}; ${coordinates[1].toFixed(4)}`;
};

// Create a custom information message control
export let InfoMessage = null;

interface InfoMessageProps {
    text: string;
}

// Wait for the api to load to access the entity system (MMapComplexEntity)
mappable.ready.then(() => {
    class InfoMessageClass extends mappable.MMapComplexEntity<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.innerHTML = props.text;

            return infoWindow;
        }

        // Method for attaching the control to the map
        _onAttach() {
            this._element = this._createElement(this._props);
            this._detachDom = mappable.useDomContext(this, this._element, this._element);
        }

        // Method for detaching control from the map
        _onDetach() {
            this._detachDom();
            this._detachDom = undefined;
            this._element = undefined;
        }
    }

    InfoMessage = InfoMessageClass;
});
.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;
}