Add route control to the map
vanilla.html
react.html
vue.html
common.ts
variables.ts
<!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 {BaseRouteResponse, LngLat, RouteOptions, MMapFeature} from '@mappable-world/mappable-types';
import type {MMapDefaultMarker} from '@mappable-world/mappable-default-ui-theme';
import {FROM_POINT_STYLE, LOCATION, MARGIN, PREVIEW_POINT_STYLE, TO_POINT_STYLE, getStroke} from '../variables';
import {TRUCK_PARAMS} 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;
const {MMapRouteControl, MMapDefaultMarker} = await mappable.import('@mappable-world/mappable-default-ui-theme');
map = new MMap(document.getElementById('app'), {location: LOCATION, margin: MARGIN}, [
new MMapDefaultSchemeLayer({}),
new MMapDefaultFeaturesLayer({})
]);
const dragEndHandler = () => {
routeControl.update({
waypoints: [
map.children.includes(fromPoint) ? fromPoint.coordinates : null,
map.children.includes(toPoint) ? toPoint.coordinates : null
]
});
};
const fromPoint: MMapDefaultMarker = new MMapDefaultMarker({
coordinates: map.center as LngLat,
onDragEnd: dragEndHandler,
draggable: true,
...FROM_POINT_STYLE
});
const toPoint: MMapDefaultMarker = new MMapDefaultMarker({
coordinates: map.center as LngLat,
onDragEnd: dragEndHandler,
draggable: true,
...TO_POINT_STYLE
});
let previewPoint: MMapDefaultMarker = new MMapDefaultMarker({
coordinates: map.center as LngLat,
...PREVIEW_POINT_STYLE
});
let featuresOnMap: MMapFeature[] = [];
const routeControl = new MMapRouteControl({
truckParameters: TRUCK_PARAMS,
waypoints: [map.center as LngLat, null],
onBuildRouteError() {
featuresOnMap.forEach((f) => map.removeChild(f));
featuresOnMap = [];
},
onRouteResult(result, type) {
featuresOnMap.forEach((f) => map.removeChild(f));
featuresOnMap = getFeatures(result, type);
featuresOnMap.forEach((f) => map.addChild(f));
},
onUpdateWaypoints(waypoints) {
const [from, to] = waypoints;
if (from) {
const {coordinates} = from.geometry;
fromPoint.update({coordinates});
map.addChild(fromPoint);
} else {
map.removeChild(fromPoint);
}
if (to) {
const {coordinates} = to.geometry;
toPoint.update({coordinates});
map.addChild(toPoint);
} else {
map.removeChild(toPoint);
}
if (!to || !from) {
featuresOnMap.forEach((f) => map.removeChild(f));
featuresOnMap = [];
}
},
onMouseMoveOnMap(coordinates, index, lastCall) {
if (!lastCall) {
previewPoint.update({coordinates});
if (!map.children.includes(previewPoint)) {
map.addChild(previewPoint);
}
} else {
map.removeChild(previewPoint);
}
}
});
map.addChild(new MMapControls({position: 'top left'}).addChild(routeControl));
const getFeatures = (result: BaseRouteResponse, type: RouteOptions['type']): MMapFeature[] => {
if (type !== 'transit') {
const {geometry} = result.toRoute();
return [new mappable.MMapFeature({geometry, style: {stroke: getStroke(type), simplificationRate: 0}})];
}
return result.toSteps().map(
(step) =>
new mappable.MMapFeature({
geometry: step.geometry,
style: {stroke: getStroke(step.properties.mode as RouteOptions['type']), simplificationRate: 0}
})
);
};
}
</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>
<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="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="react, typescript" type="text/babel">
import {BaseRouteResponse, LngLat, MMapLocationRequest, RouteOptions} from '@mappable-world/mappable-types';
import {MMapRouteControlProps, WaypointsArray} from '@mappable-world/mappable-default-ui-theme';
import {FROM_POINT_STYLE, LOCATION, MARGIN, PREVIEW_POINT_STYLE, TO_POINT_STYLE, getStroke} from '../variables';
import {computeBoundsForPoints, TRUCK_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 @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, MMapFeature} = reactify.module(mappable);
const {MMapRouteControl, MMapDefaultMarker} = reactify.module(
await mappable.import('@mappable-world/mappable-default-ui-theme')
);
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('app')
);
function App() {
const [routeType, setRouteType] = React.useState<RouteOptions['type']>('driving');
const [routeResult, setRouteResult] = React.useState<BaseRouteResponse>();
const [showFeature, setShowFeature] = React.useState(false);
const [fromCoords, setFromCoords] = React.useState<LngLat | undefined>();
const [toCoords, setToCoords] = React.useState<LngLat | undefined>();
const [previewCoords, setPreviewCoords] = React.useState<LngLat | undefined>();
const [waypoints, setWaypoints] = React.useState<[LngLat, LngLat]>([LOCATION.center, null]);
const onRouteResult = React.useCallback((result: BaseRouteResponse, type: RouteOptions['type']) => {
setRouteType(type);
setRouteResult(result);
setShowFeature(true);
}, []);
const onUpdateWaypoints = React.useCallback((waypoints: WaypointsArray) => {
const [from, to] = waypoints;
setFromCoords(from?.geometry?.coordinates);
setToCoords(to?.geometry?.coordinates);
if (!from || !to) {
setShowFeature(false);
}
setPreviewCoords(undefined);
}, []);
const onBuildRouteError = React.useCallback(() => {
setShowFeature(false);
}, []);
const onMouseMoveOnMap = React.useCallback<MMapRouteControlProps['onMouseMoveOnMap']>(
(coordinates, index, lastCall) => {
setPreviewCoords(() => (lastCall ? undefined : coordinates));
},
[]
);
const onDragEndHandler = React.useCallback(
(coordinates: LngLat, type: 'from' | 'to') => {
if (type === 'from') {
setFromCoords(coordinates);
setWaypoints([coordinates, toCoords]);
} else {
setToCoords(coordinates);
setWaypoints([fromCoords, coordinates]);
}
},
[fromCoords, toCoords]
);
const features = React.useMemo(() => {
if (!routeResult) {
return null;
}
if (routeType !== 'transit') {
const {geometry} = routeResult.toRoute();
return [
<MMapFeature geometry={geometry} style={{stroke: getStroke(routeType), simplificationRate: 0}} />
];
}
return routeResult
.toSteps()
.map((step) => (
<MMapFeature
geometry={step.geometry}
style={{stroke: getStroke(step.properties.mode as RouteOptions['type']), simplificationRate: 0}}
/>
));
}, [routeResult, routeType]);
return (
<MMap location={reactify.useDefault(LOCATION)} margin={MARGIN} ref={(x) => (map = x)}>
<MMapDefaultSchemeLayer />
<MMapDefaultFeaturesLayer />
<MMapControls position="top left">
<MMapRouteControl
truckParameters={TRUCK_PARAMS}
waypoints={waypoints}
onRouteResult={onRouteResult}
onUpdateWaypoints={onUpdateWaypoints}
onBuildRouteError={onBuildRouteError}
onMouseMoveOnMap={onMouseMoveOnMap}
/>
</MMapControls>
{showFeature && features}
{fromCoords !== undefined && (
<MMapDefaultMarker
coordinates={fromCoords}
draggable
onDragEnd={(coordinates) => onDragEndHandler(coordinates, 'from')}
{...FROM_POINT_STYLE}
/>
)}
{toCoords !== undefined && (
<MMapDefaultMarker
coordinates={toCoords}
draggable
onDragEnd={(coordinates) => onDragEndHandler(coordinates, 'to')}
{...TO_POINT_STYLE}
/>
)}
{previewCoords !== undefined && (
<MMapDefaultMarker coordinates={previewCoords} {...PREVIEW_POINT_STYLE} />
)}
</MMap>
);
}
}
</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>
<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 {BaseRouteResponse, LngLat, MMapLocationRequest, RouteOptions} from '@mappable-world/mappable-types';
import {MMapRouteControlProps, WaypointsArray} from '@mappable-world/mappable-default-ui-theme';
import {FROM_POINT_STYLE, LOCATION, MARGIN, PREVIEW_POINT_STYLE, TO_POINT_STYLE, getStroke} from '../variables';
import {TRUCK_PARAMS} from './common';
window.map = null;
main();
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, MMapFeature} = vuefy.module(mappable);
const {MMapRouteControl, MMapDefaultMarker} = vuefy.module(await mappable.import('@mappable-world/mappable-default-ui-theme'));
const app = Vue.createApp({
components: {
MMap,
MMapDefaultSchemeLayer,
MMapDefaultFeaturesLayer,
MMapControls,
MMapFeature,
MMapRouteControl,
MMapDefaultMarker
},
setup() {
const location = Vue.ref<MMapLocationRequest>(LOCATION);
const routeType = Vue.ref<RouteOptions['type']>('driving');
const routeResult = Vue.shallowRef<BaseRouteResponse>();
const showFeature = Vue.ref(false);
const fromCoords = Vue.ref<LngLat | undefined>();
const toCoords = Vue.ref<LngLat | undefined>();
const previewCoords = Vue.ref<LngLat | undefined>();
const waypoints = Vue.ref<[LngLat, LngLat]>([LOCATION.center, null]);
const refMap = (ref: any) => {
window.map = ref?.entity;
};
const onRouteResult = (result: BaseRouteResponse, type: RouteOptions['type']) => {
routeType.value = type;
routeResult.value = result;
showFeature.value = true;
};
const onUpdateWaypoints = (waypoints: WaypointsArray) => {
const [from, to] = waypoints;
fromCoords.value = from?.geometry?.coordinates;
toCoords.value = to?.geometry?.coordinates;
if (!from || !to) {
showFeature.value = false;
}
previewCoords.value = undefined;
};
const onBuildRouteError = () => {
showFeature.value = false;
};
const onMouseMoveOnMap: MMapRouteControlProps['onMouseMoveOnMap'] = (coordinates, index, lastCall) => {
previewCoords.value = lastCall ? undefined : coordinates;
};
const onDragEndHandler = (coordinates: LngLat, type: 'from' | 'to') => {
if (type === 'from') {
waypoints.value = [coordinates, toCoords.value];
} else {
waypoints.value = [fromCoords.value, coordinates];
}
};
const features = Vue.computed(() => {
if (!routeResult) {
return null;
}
if (routeType.value !== 'transit') {
const {geometry} = routeResult.value.toRoute();
return [
{
geometry,
style: {stroke: getStroke(routeType.value), simplificationRate: 0}
}
];
}
return routeResult.value.toSteps().map((step) => ({
geometry: step.geometry,
style: {
stroke: getStroke(step.properties.mode as RouteOptions['type']),
simplificationRate: 0
}
}));
});
return {
LOCATION,
MARGIN,
FROM_POINT_STYLE,
PREVIEW_POINT_STYLE,
TO_POINT_STYLE,
TRUCK_PARAMS,
location,
routeType,
routeResult,
showFeature,
fromCoords,
toCoords,
previewCoords,
waypoints,
features,
onRouteResult,
onUpdateWaypoints,
onBuildRouteError,
onMouseMoveOnMap,
onDragEndHandler,
refMap
};
},
template: `
<MMap :location="location" :margin="MARGIN" :ref="refMap">
<MMapDefaultSchemeLayer />
<MMapDefaultFeaturesLayer />
<MMapControls position="top left">
<MMapRouteControl
:truckParameters="TRUCK_PARAMS"
:waypoints="waypoints"
:onRouteResult="onRouteResult"
:onUpdateWaypoints="onUpdateWaypoints"
:onBuildRouteError="onBuildRouteError"
:onMouseMoveOnMap="onMouseMoveOnMap" />
</MMapControls>
<template v-if="showFeature">
<MMapFeature v-for="feature in features"
:geometry="feature.geometry"
:style="feature.style" />
</template>
<MMapDefaultMarker
v-if="fromCoords !== undefined"
:coordinates="fromCoords"
draggable
:onDragEnd="(coordinates) => onDragEndHandler(coordinates, 'from')"
v-bind="FROM_POINT_STYLE" />
<MMapDefaultMarker
v-if="toCoords !== undefined"
:coordinates="toCoords"
draggable
:onDragEnd="(coordinates) => onDragEndHandler(coordinates, 'to')"
v-bind="TO_POINT_STYLE" />
<MMapDefaultMarker
v-if="previewCoords !== undefined"
:coordinates="previewCoords" v-bind="PREVIEW_POINT_STYLE" />
</MMap>`
});
app.mount('#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>
<link rel="stylesheet" href="./common.css" />
</head>
<body>
<div id="app"></div>
</body>
</html>
import {LngLat, LngLatBounds, TruckParameters} 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 TRUCK_PARAMS: TruckParameters = {
weight: 40,
maxWeight: 40,
axleWeight: 10,
payload: 20,
height: 4,
width: 2.5,
length: 16,
ecoClass: 4,
hasTrailer: true
};
import type {
LngLat,
LngLatBounds,
MMapCenterLocation,
MMapZoomLocation,
Margin,
RouteOptions,
Stroke,
TruckParameters
} from '@mappable-world/mappable-types';
export const LOCATION: MMapCenterLocation & MMapZoomLocation = {
center: [55.274247, 25.197303],
zoom: 12
};
export const MARGIN: Margin = [10, 10, 10, 10];
export const FROM_POINT_STYLE = Object.freeze({
size: 'normal',
color: {day: '#2E4CE5', night: '#D6FD63'},
iconName: 'fallback'
});
export const TO_POINT_STYLE = Object.freeze({
size: 'normal',
color: {day: '#313133', night: '#C8D2E6'},
iconName: 'fallback'
});
export const PREVIEW_POINT_STYLE = Object.freeze({
size: 'normal',
color: {day: '#2E4CE580', night: '#D6FD6380'},
iconName: 'fallback'
});
export const getStroke = (type: RouteOptions['type']): Stroke => {
if (type === 'walking') {
return [
{width: 4, color: '#7D90F0', dash: [4, 8]},
{width: 8, color: '#ffffff'}
];
}
return [
{width: 6, color: '#34D9AD'},
{width: 8, color: '#050D3366'}
];
};