Build a route between two points

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, RouteFeature} from '@mappable-world/mappable-types';
            import {fetchRoute, getPointStr, MARGIN, RoutesEnum} from './common';
            import {INITIAL_ROUTE_POINTS, LINE_STYLE, LOCATION, MARKER_A_COLOR, MARKER_B_COLOR} from '../variables';
            
            window.map = null;
            
            interface InfoMessageProps {
                text: string;
            }
            
            interface ButtonGroupProps {
                buildTransitRoute: () => void;
                buildTruckRoute: () => void;
                buildDrivingRoute: () => void;
                buildWalkingRoute: () => void;
                activeTab?: RoutesEnum;
            }
            
            main();
            async function main() {
                // Waiting for all api elements to be loaded
                await mappable.ready;
                const {MMap, MMapDefaultSchemeLayer, MMapDefaultFeaturesLayer, MMapFeature, MMapControls, MMapControl} = mappable;
                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, margin: MARGIN},
                    [
                        // Add a map scheme layer
                        new MMapDefaultSchemeLayer({}),
                        // Add a layer of geo objects to display markers and line
                        new MMapDefaultFeaturesLayer({})
                    ]
                );
            
                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.textContent = 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;
                    }
                }
            
                class ButtonGroupClass extends mappable.MMapComplexEntity<ButtonGroupProps> {
                    private _element!: HTMLDivElement;
                    private _detachDom!: () => void;
                    private drivingButton: HTMLButtonElement;
                    private truckButton: HTMLButtonElement;
                    private walkingButton: HTMLButtonElement;
                    private transitButton: HTMLButtonElement;
                    private firstDivider: HTMLDivElement;
                    private secondDivider: HTMLDivElement;
                    private thirdDivider: HTMLDivElement;
            
                    // Method for create a DOM control element
                    _createElement(props: ButtonGroupProps) {
                        // Create a root element
                        const buttonGroupContainer = document.createElement('div');
                        buttonGroupContainer.classList.add('tabs__pills');
                        buttonGroupContainer.id = 'button_group';
            
                        const drivingButton = document.createElement('button');
                        drivingButton.id = RoutesEnum.Driving;
                        drivingButton.innerText = RoutesEnum.Driving;
                        drivingButton.onclick = props.buildDrivingRoute;
                        drivingButton.classList.add('tab__button', 'active');
            
                        const firstDivider = document.createElement('hr');
                        firstDivider.id = 'divider_first';
                        firstDivider.classList.add('divider', 'hidden');
            
                        const truckButton = document.createElement('button');
                        truckButton.id = RoutesEnum.Truck;
                        truckButton.innerText = RoutesEnum.Truck;
                        truckButton.onclick = props.buildTruckRoute;
                        truckButton.classList.add('tab__button');
            
                        const secondDivider = document.createElement('hr');
                        secondDivider.id = 'divider_second';
                        secondDivider.classList.add('divider');
            
                        const walkingButton = document.createElement('button');
                        walkingButton.id = RoutesEnum.Walking;
                        walkingButton.innerText = RoutesEnum.Walking;
                        walkingButton.onclick = props.buildWalkingRoute;
                        walkingButton.classList.add('tab__button');
            
                        const thirdDivider = document.createElement('hr');
                        thirdDivider.id = 'divider_third';
                        thirdDivider.classList.add('divider');
            
                        const transitButton = document.createElement('button');
                        transitButton.id = RoutesEnum.Transit;
                        transitButton.innerText = RoutesEnum.Transit;
                        transitButton.onclick = props.buildTransitRoute;
                        transitButton.classList.add('tab__button');
            
                        buttonGroupContainer.appendChild(drivingButton);
                        buttonGroupContainer.appendChild(firstDivider);
                        buttonGroupContainer.appendChild(truckButton);
                        buttonGroupContainer.appendChild(secondDivider);
                        buttonGroupContainer.appendChild(walkingButton);
                        buttonGroupContainer.appendChild(thirdDivider);
                        buttonGroupContainer.appendChild(transitButton);
            
                        this.drivingButton = drivingButton;
                        this.truckButton = truckButton;
                        this.walkingButton = walkingButton;
                        this.transitButton = transitButton;
                        this.firstDivider = firstDivider;
                        this.secondDivider = secondDivider;
                        this.thirdDivider = thirdDivider;
            
                        return buttonGroupContainer;
                    }
            
                    update(changedProps: Partial<ButtonGroupProps>) {
                        [this.transitButton, this.drivingButton, this.truckButton, this.walkingButton].forEach((btn) => {
                            if (btn.id === changedProps.activeTab) {
                                btn.classList.add('active');
                                return;
                            }
                            btn.classList.remove('active');
                        });
            
                        switch (changedProps.activeTab) {
                            case RoutesEnum.Driving:
                                this.firstDivider.classList.add('hidden');
                                this.secondDivider.classList.remove('hidden');
                                this.thirdDivider.classList.remove('hidden');
                                break;
                            case RoutesEnum.Transit:
                                this.firstDivider.classList.remove('hidden');
                                this.secondDivider.classList.remove('hidden');
                                this.thirdDivider.classList.add('hidden');
                                break;
                            case RoutesEnum.Truck:
                                this.firstDivider.classList.add('hidden');
                                this.secondDivider.classList.add('hidden');
                                this.thirdDivider.classList.remove('hidden');
                                break;
                            case RoutesEnum.Walking:
                                this.firstDivider.classList.remove('hidden');
                                this.secondDivider.classList.add('hidden');
                                this.thirdDivider.classList.add('hidden');
                        }
                    }
            
                    // 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;
                    }
                }
            
                // Create and add route start and end markers to the map.
                const pointA = new MMapDefaultMarker({
                    coordinates: INITIAL_ROUTE_POINTS[0],
                    draggable: true,
                    title: 'Point A',
                    subtitle: getPointStr(INITIAL_ROUTE_POINTS[0]),
                    onDragMove: onDragMovePointAHandler,
                    onDragEnd: onDragEndHandler,
                    size: 'normal',
                    iconName: 'fallback',
                    color: MARKER_A_COLOR
                });
                const pointB = new MMapDefaultMarker({
                    coordinates: INITIAL_ROUTE_POINTS[1],
                    draggable: true,
                    title: 'Point B',
                    subtitle: getPointStr(INITIAL_ROUTE_POINTS[1]),
                    onDragMove: onDragMovePointBHandler,
                    onDragEnd: onDragEndHandler,
                    size: 'normal',
                    iconName: 'fallback',
                    color: MARKER_B_COLOR
                });
                map.addChild(pointA).addChild(pointB);
            
                // Create and add a route line to the map
                const routeLine = new MMapFeature({geometry: {type: 'LineString', coordinates: []}, style: LINE_STYLE});
                map.addChild(routeLine);
            
                // Get and process data about the initial route
                fetchRoute(pointA.coordinates, pointB.coordinates).then(routeHandler);
            
                /* Create and add a shared container for controls to the map.
              Using MMapControls you can change the position of the control */
                const infoMessage = new MMapControls({position: 'top left'});
                map.addChild(infoMessage);
                // Add a custom information message control to the map
                infoMessage.addChild(new InfoMessageClass({text: 'Drag any marker to rebuild the route'}));
            
                const buildRoute = (activeTab: RoutesEnum, routeType: 'driving' | 'truck' | 'walking' | 'transit') => {
                    fetchRoute(pointA.coordinates, pointB.coordinates, routeType).then(routeHandler);
                    buttonGroup.update({activeTab});
                };
                const buttonGroup = new ButtonGroupClass({
                    buildTruckRoute: () => buildRoute(RoutesEnum.Truck, 'truck'),
                    buildWalkingRoute: () => buildRoute(RoutesEnum.Walking, 'walking'),
                    buildTransitRoute: () => buildRoute(RoutesEnum.Transit, 'transit'),
                    buildDrivingRoute: () => buildRoute(RoutesEnum.Driving, 'driving')
                });
            
                const topLeftControls = new MMapControls({position: 'top right'}, [
                    new MMapControl({transparent: true}).addChild(buttonGroup)
                ]);
                map.addChild(topLeftControls);
            
                // The handler functions for updating the coordinates and subtitle of the marker when dragging
                function onDragMovePointAHandler(coordinates: LngLat) {
                    pointA.update({coordinates, subtitle: getPointStr(coordinates)});
                }
                function onDragMovePointBHandler(coordinates: LngLat) {
                    pointB.update({coordinates, subtitle: getPointStr(coordinates)});
                }
            
                // The handler function for updating route data after dragging the marker
                function onDragEndHandler() {
                    fetchRoute(pointA.coordinates, pointB.coordinates).then(routeHandler);
                }
            
                /* A handler function that updates the route line
              and shifts the map to the new route boundaries, if they are available. */
                function routeHandler(newRoute: RouteFeature) {
                    // If the route is not found, then we alert a message and clear the route line
                    if (!newRoute) {
                        alert('Route not found');
                        routeLine.update({geometry: {type: 'LineString', coordinates: []}});
                        return;
                    }
            
                    routeLine.update({...newRoute});
                    if (newRoute.properties.bounds) {
                        map.setLocation({bounds: newRoute.properties.bounds, duration: 300});
                    }
                }
            }
        </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://js.api.mappable.world/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"
            src="../variables.ts"
        ></script>
        <script data-plugins="transform-modules-umd" data-presets="react, typescript" type="text/babel">
            import type {LngLat, RouteFeature} from '@mappable-world/mappable-types';
            import {fetchRoute, getPointStr, MARGIN, RoutesEnum} from './common';
            import {INITIAL_ROUTE_POINTS, LINE_STYLE, LOCATION, MARKER_A_COLOR, MARKER_B_COLOR} from '../variables';
            
            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, MMapFeature, MMapControls, MMapControl} =
                    reactify.module(mappable);
            
                // Import the package to add a default marker
                const {MMapDefaultMarker} = reactify.module(await mappable.import('@mappable-world/mappable-default-ui-theme'));
            
                const {useState, useCallback, useEffect} = React;
            
                function App() {
                    const [location, setLocation] = useState(LOCATION);
                    const [waypointA, setWaypointA] = useState({
                        coordinates: INITIAL_ROUTE_POINTS[0],
                        subtitle: getPointStr(INITIAL_ROUTE_POINTS[0])
                    });
                    const [waypointB, setWaypointB] = useState({
                        coordinates: INITIAL_ROUTE_POINTS[1],
                        subtitle: getPointStr(INITIAL_ROUTE_POINTS[1])
                    });
                    const [route, setRoute] = useState<RouteFeature>(null);
                    const [tab, setTab] = useState(RoutesEnum.Driving);
            
                    // Get and process route data during the first rendering
                    useEffect(() => {
                        fetchRoute(waypointA.coordinates, waypointB.coordinates).then(routeHandler);
                    }, []);
            
                    // The handler functions for updating the coordinates and subtitle of the marker when dragging
                    const onDragMovePointAHandler = useCallback((coordinates: LngLat) => {
                        setWaypointA({
                            coordinates: coordinates,
                            subtitle: getPointStr(coordinates)
                        });
                    }, []);
                    const onDragMovePointBHandler = useCallback((coordinates: LngLat) => {
                        setWaypointB({
                            coordinates: coordinates,
                            subtitle: getPointStr(coordinates)
                        });
                    }, []);
            
                    // The handler function for updating route data after dragging the marker
                    const onDragEndHandler = useCallback(() => {
                        fetchRoute(waypointA.coordinates, waypointB.coordinates).then(routeHandler);
                    }, [waypointA, waypointB]);
            
                    const buildDrivingRoute = useCallback(() => {
                        fetchRoute(waypointA.coordinates, waypointB.coordinates, 'driving').then(routeHandler);
                        setTab(RoutesEnum.Driving);
                    }, [waypointA, waypointB]);
                    const buildTruckRoute = useCallback(() => {
                        fetchRoute(waypointA.coordinates, waypointB.coordinates, 'truck').then(routeHandler);
                        setTab(RoutesEnum.Truck);
                    }, [waypointA, waypointB]);
                    const buildWalkingRoute = useCallback(() => {
                        fetchRoute(waypointA.coordinates, waypointB.coordinates, 'walking').then(routeHandler);
                        setTab(RoutesEnum.Walking);
                    }, [waypointA, waypointB]);
                    const buildTransitRoute = useCallback(() => {
                        fetchRoute(waypointA.coordinates, waypointB.coordinates, 'transit').then(routeHandler);
                        setTab(RoutesEnum.Transit);
                    }, [waypointA, waypointB]);
            
                    /* A handler function that updates the route line
              and shifts the map to the new route boundaries, if they are available. */
                    const routeHandler = useCallback((newRoute: RouteFeature) => {
                        // If the route is not found, then we alert a message and clear the route line
                        if (!newRoute) {
                            alert('Route not found');
                            setRoute(null);
                            return;
                        }
            
                        setRoute(newRoute);
                        if (newRoute.properties.bounds) {
                            setLocation({bounds: newRoute.properties.bounds, duration: 300});
                        }
                    }, []);
                    return (
                        // Initialize the map and pass initialization parameters
                        <MMap location={location} showScaleInCopyrights={true} ref={(x) => (map = x)} margin={MARGIN}>
                            {/* Add a map scheme layer */}
                            <MMapDefaultSchemeLayer />
                            {/* Add a layer of geo objects to display markers and line */}
                            <MMapDefaultFeaturesLayer />
            
                            {/* Add route start and end markers to the map */}
                            <MMapDefaultMarker
                                coordinates={waypointA.coordinates}
                                title="Point A"
                                subtitle={waypointA.subtitle}
                                draggable
                                size="normal"
                                iconName="fallback"
                                color={MARKER_A_COLOR}
                                onDragMove={onDragMovePointAHandler}
                                onDragEnd={onDragEndHandler}
                            />
                            <MMapDefaultMarker
                                coordinates={waypointB.coordinates}
                                title="Point B"
                                subtitle={waypointB.subtitle}
                                draggable
                                size="normal"
                                iconName="fallback"
                                color={MARKER_B_COLOR}
                                onDragMove={onDragMovePointBHandler}
                                onDragEnd={onDragEndHandler}
                            />
            
                            {/* Add the route line to the map when it becomes available */}
                            {route && <MMapFeature {...route} style={LINE_STYLE} />}
            
                            {/* Add a shared container for controls to the map.
                            Using MMapControls you can change the position of the control */}
                            <MMapControls position="top left">
                                <MMapControl transparent>
                                    {/* Add a custom information message control to the map */}
                                    <div className="info-window">Drag any marker to rebuild the route</div>
                                </MMapControl>
                            </MMapControls>
                            <MMapControls position="top right">
                                <MMapControl transparent>
                                    <div className="tabs__pills">
                                        <button
                                            id={RoutesEnum.Driving}
                                            className={`tab__button ${tab === RoutesEnum.Driving && 'active'}`}
                                            onClick={buildDrivingRoute}
                                        >
                                            Driving
                                        </button>
                                        <hr
                                            className={`divider ${
                                                [RoutesEnum.Truck, RoutesEnum.Driving].includes(tab) && 'hidden'
                                            }`}
                                        />
                                        <button
                                            id={RoutesEnum.Truck}
                                            className={`tab__button ${tab === RoutesEnum.Truck && 'active'}`}
                                            onClick={buildTruckRoute}
                                        >
                                            Truck
                                        </button>
                                        <hr
                                            className={`divider ${
                                                [RoutesEnum.Truck, RoutesEnum.Walking].includes(tab) && 'hidden'
                                            }`}
                                        />
                                        <button
                                            id={RoutesEnum.Walking}
                                            className={`tab__button ${tab === RoutesEnum.Walking && 'active'}`}
                                            onClick={buildWalkingRoute}
                                        >
                                            Walking
                                        </button>
                                        <hr
                                            className={`divider ${
                                                [RoutesEnum.Transit, RoutesEnum.Walking].includes(tab) && 'hidden'
                                            }`}
                                        />
                                        <button
                                            id={RoutesEnum.Transit}
                                            className={`tab__button ${tab === RoutesEnum.Transit && 'active'}`}
                                            onClick={buildTransitRoute}
                                        >
                                            Transit
                                        </button>
                                    </div>
                                </MMapControl>
                            </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" />
    </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://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, RouteFeature} from '@mappable-world/mappable-types';
            import {getPointStr, fetchRoute, RoutesEnum, MARGIN} from './common';
            import {INITIAL_ROUTE_POINTS, LOCATION, LINE_STYLE, MARKER_A_COLOR, MARKER_B_COLOR} from '../variables';
            
            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, MMapFeature, MMapControls, MMapControl} =
                    vuefy.module(mappable);
            
                // Import the package to add a default marker
                const {MMapDefaultMarker} = vuefy.module(await mappable.import('@mappable-world/mappable-default-ui-theme'));
            
                const {createApp, onMounted, ref} = Vue;
            
                const app = createApp({
                    components: {
                        MMap,
                        MMapDefaultSchemeLayer,
                        MMapDefaultFeaturesLayer,
                        MMapFeature,
                        MMapControls,
                        MMapDefaultMarker,
                        MMapControl
                    },
                    setup() {
                        const refMap = (ref) => {
                            window.map = ref?.entity;
                        };
            
                        const location = ref(LOCATION);
                        const waypointA = ref({
                            coordinates: INITIAL_ROUTE_POINTS[0],
                            subtitle: getPointStr(INITIAL_ROUTE_POINTS[0])
                        });
                        const waypointB = ref({
                            coordinates: INITIAL_ROUTE_POINTS[1],
                            subtitle: getPointStr(INITIAL_ROUTE_POINTS[1])
                        });
                        const route = ref<RouteFeature>(null);
                        const tab = ref(RoutesEnum.Driving);
            
                        // Get and process route data during the first rendering
                        onMounted(() => {
                            fetchRoute(waypointA.value.coordinates, waypointB.value.coordinates).then(routeHandler);
                        });
            
                        // The handler functions for updating the coordinates and subtitle of the marker when dragging
                        const onDragMovePointAHandler = (coordinates: LngLat) => {
                            waypointA.value.subtitle = getPointStr(coordinates);
                            waypointA.value.coordinates = coordinates;
                        };
                        const onDragMovePointBHandler = (coordinates: LngLat) => {
                            waypointB.value.subtitle = getPointStr(coordinates);
                            waypointB.value.coordinates = coordinates;
                        };
            
                        // The handler function for updating route data after dragging the marker
                        const onDragEndHandler = () => {
                            fetchRoute(waypointA.value.coordinates, waypointB.value.coordinates).then(routeHandler);
                        };
            
                        const buildDrivingRoute = () => {
                            fetchRoute(waypointA.value.coordinates, waypointB.value.coordinates, 'driving').then(routeHandler);
                            tab.value = RoutesEnum.Driving;
                        };
                        const buildTruckRoute = () => {
                            fetchRoute(waypointA.value.coordinates, waypointB.value.coordinates, 'truck').then(routeHandler);
                            tab.value = RoutesEnum.Truck;
                        };
                        const buildWalkingRoute = () => {
                            fetchRoute(waypointA.value.coordinates, waypointB.value.coordinates, 'walking').then(routeHandler);
                            tab.value = RoutesEnum.Walking;
                        };
                        const buildTransitRoute = () => {
                            fetchRoute(waypointA.value.coordinates, waypointB.value.coordinates, 'transit').then(routeHandler);
                            tab.value = RoutesEnum.Transit;
                        };
            
                        /* A handler function that updates the route line
                  and shifts the map to the new route boundaries, if they are available. */
                        const routeHandler = (newRoute: RouteFeature) => {
                            // If the route is not found, then we alert a message and clear the route line
                            if (!newRoute) {
                                alert('Route not found');
                                route.value = null;
                                return;
                            }
            
                            route.value = newRoute;
                            if (newRoute.properties.bounds) {
                                location.value = {bounds: newRoute.properties.bounds, duration: 300};
                            }
                        };
            
                        return {
                            MARKER_A_COLOR,
                            MARKER_B_COLOR,
                            LINE_STYLE,
                            MARGIN,
                            RoutesEnum,
                            refMap,
                            location,
                            waypointA,
                            waypointB,
                            route,
                            tab,
                            onDragMovePointAHandler,
                            onDragMovePointBHandler,
                            onDragEndHandler,
                            buildDrivingRoute,
                            buildTruckRoute,
                            buildWalkingRoute,
                            buildTransitRoute
                        };
                    },
                    template: `
                  <!--Initialize the map and pass initialization parameters-->
                  <MMap :location="location" :showScaleInCopyrights="true" :margin="MARGIN" :ref="refMap">
                    <!--Add a map scheme layer-->
                    <MMapDefaultSchemeLayer />
                    <!--Add a layer of geo objects to display markers and line-->
                    <MMapDefaultFeaturesLayer />
            
                    <!--Add route start and end markers to the map-->
                    <MMapDefaultMarker
                        :coordinates="waypointA.coordinates"
                        title="Point A"
                        :subtitle="waypointA.subtitle"
                        :draggable="true"
                        :onDragMove="onDragMovePointAHandler"
                        :onDragEnd="onDragEndHandler"
                        size="normal"
                        iconName="fallback"
                        :color="MARKER_A_COLOR"
                    />
                    <MMapDefaultMarker
                        :coordinates="waypointB.coordinates"
                        title="Point B"
                        :subtitle="waypointB.subtitle"
                        :draggable="true"
                        :onDragMove="onDragMovePointBHandler"
                        :onDragEnd="onDragEndHandler"
                        size="normal"
                        iconName="fallback"
                        :color="MARKER_B_COLOR"
                    />
            
                    <!--Add the route line to the map when it becomes available-->
                    <MMapFeature v-if="route" v-bind="route" :style="LINE_STYLE" />
            
                    <!--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-->
                      <MMapControl :transparent="true">
                        <div class="info-window">
                          Drag any marker to rebuild the route
                        </div>
                      </MMapControl>
                    </MMapControls>
                    <MMapControls position="top right">
                      <MMapControl :transparent="true">
                        <div class="tabs__pills">
                          <button
                            :id="RoutesEnum.Driving"
                            :class="['tab__button', tab === RoutesEnum.Driving ? 'active' : '']"
                            @click="buildDrivingRoute"
                          >
                            Driving
                          </button>
                          <hr :class="['divider', [RoutesEnum.Truck, RoutesEnum.Driving].includes(tab) ? 'hidden' : '']"/>
                          <button
                            :id="RoutesEnum.Truck"
                            :class="['tab__button', tab === RoutesEnum.Truck ? 'active' : '']"
                            @click="buildTruckRoute"
                          >
                            Truck
                          </button>
                          <hr :class="['divider', [RoutesEnum.Truck, RoutesEnum.Walking].includes(tab) ? 'hidden' : '']"/>
                          <button
                            :id="RoutesEnum.Walking"
                            :class="['tab__button', tab === RoutesEnum.Walking ? 'active' : '']"
                            @click="buildWalkingRoute"
                          >
                            Walking
                          </button>
                          <hr :class="['divider', [RoutesEnum.Transit, RoutesEnum.Walking].includes(tab) ? 'hidden' : '']"/>
                          <button
                            :id="RoutesEnum.Transit"
                            :class="['tab__button', tab === RoutesEnum.Transit ? 'active' : '']"
                            @click="buildTransitRoute"
                          >
                            Transit
                          </button>
                        </div>
                      </MMapControl>
                    </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" />
    </head>
    <body>
        <div id="app"></div>
    </body>
</html>
import type {MMapLocationRequest, LngLat, DrawingStyle} from '@mappable-world/mappable-types';

export const LOCATION: MMapLocationRequest = {
    center: [55.2922, 25.21832], // starting position [lng, lat]
    zoom: 14.5 // starting zoom
};

// The initial coordinates of the starting and ending points of the route
export const INITIAL_ROUTE_POINTS: LngLat[] = [
    [55.2761, 25.2122],
    [55.3048, 25.2196]
];

// An object containing the route line style
export const LINE_STYLE: DrawingStyle = {
    simplificationRate: 0,
    stroke: [
        {width: 7, color: '#34D9AD'},
        {width: 9, color: '#050D33', opacity: 0.4}
    ]
};

export const MARKER_A_COLOR = {day: '#2E4CE5', night: '#D6FD63'};
export const MARKER_B_COLOR = {day: '#313133', night: '#C8D2E6'};
import type {LngLat, Margin, RouteOptions, TruckParameters} from '@mappable-world/mappable-types';

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

    // 
});

export const MARGIN: Margin = [100, 100, 100, 100];

export enum RoutesEnum {
    Walking = 'Walking',
    Driving = 'Driving',
    Truck = 'Truck',
    Transit = 'Transit'
}

// Converting [Lng, Lat] coordinates to string format
export function getPointStr(point: LngLat) {
    return point.map((c) => c.toFixed(4)).join(', ');
}

// The function for fetching a route between two points
export async function fetchRoute(
    startCoordinates: LngLat,
    endCoordinates: LngLat,
    type: RouteOptions['type'] = 'driving'
) {
    let truck: TruckParameters;
    if (type === 'truck') {
        // set truck with trailer by default
        truck = {
            weight: 40,
            maxWeight: 40,
            axleWeight: 10,
            payload: 20,
            height: 4,
            width: 2.5,
            length: 16,
            ecoClass: 4,
            hasTrailer: true
        };
    }
    // Request a route from the Router API with the specified parameters.
    const routes = await mappable.route({
        points: [startCoordinates, endCoordinates], // Start and end points of the route LngLat[]
        type, // Type of the route
        bounds: true, // Flag indicating whether to include route boundaries in the response
        truck
    });

    // Check if a route was found
    if (!routes[0]) return;

    // Convert the received route to a RouteFeature object.
    const route = routes[0].toRoute();

    // Check if a route has coordinates
    if (route.geometry.coordinates.length == 0) return;

    return route;
}
.info-window {
    min-width: max-content;
    padding: 8px 12px 8px 30px;

    font-size: 14px;
    line-height: 20px;

    color: #f2f5fa;
    border-radius: 12px;
    background-color: #313133;
    background-image: url('./info-icon.svg');
    background-repeat: no-repeat;
    background-position: 8px 8px;
}

.tabs__pills {
    display: flex;
    align-items: center;

    padding: 2px;

    border-radius: 8px;
    background-color: #edeeee;
    box-shadow: 0 0 2px 0 rgba(95, 105, 131, 0.08), 0 2px 4px 0 rgba(95, 105, 131, 0.2);
    gap: 2px;
}

.tab__button {
    padding: 10px 12px;

    font-size: 14px;
    line-height: 16px;
    cursor: pointer;

    color: #7b7d85;
    border: none;
    border-radius: 8px;
    background-color: #edeeee;

    transition: transform 0.3s ease, background-color 0.3s ease;
}

.tab__button.active {
    opacity: 1;
    color: #050d33;
    background-color: #fff;

    transform: translateX(0);
}

.tab__button:hover {
    background-color: #e8e8e8;
}

.tab__button.active:hover {
    background-color: #fff;
}

.divider {
    width: 1px;
    height: 22px;
    margin: 0;

    border: none;
    background-color: rgba(92, 94, 102, 0.14);
}

.hidden {
    opacity: 0;
}