Routing Service
This example demonstrates how to display routing information on a map using the Routing service. Click on any location on the map to set waypoints and calculate the route between them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://cdn.smartmaps.cloud/packages/smartmaps/routing/umd/routing.min.js"></script>
<script src="https://cdn.smartmaps.cloud/packages/smartmaps/smartmaps-gl/v2/umd/smartmaps-gl.min.js"></script>
<style>
body {
margin: 0;
padding: 0;
}
html,
body,
#map {
height: 100%;
}
#reset-button {
position: absolute;
top: 3%;
left: 50%;
z-index: 1;
transform: translateX(-50%);
background-color: #18345c;
color: white;
border: none;
padding: 10px 20px;
cursor: pointer;
border-radius: 4px;
}
#reset-button:hover {
background-color: #0a5fa0;
}
</style>
</head>
<body>
<button id="reset-button">Reset Waypoints</button>
<div id="map"></div>
<script>
const apiKey = 'INSERT API-KEY';
const map = new smartmapsgl.Map({
apiKey: apiKey,
container: 'map',
center: { lat: 49.02164948779226, lng: 8.439330018049352 },
zoom: 10,
style: smartmapsgl.MapStyle.LIGHT
});
const routing = new smartmaps.routingService.Routing(apiKey);
let waypoints = [];
let markers = [];
function removeMarkers() {
markers.forEach((marker) => marker.remove());
markers = [];
}
function removeRoute() {
if (map.getLayer('route')) {
map.removeLayer('route');
}
if (map.getSource('route')) {
map.removeSource('route');
}
}
function resetWaypoints() {
waypoints = [];
removeMarkers();
removeRoute();
}
document.getElementById('reset-button').addEventListener('click', resetWaypoints);
map.on('click', async (event) => {
const waypoint = {
longitude: event.lngLat.lng,
latitude: event.lngLat.lat
};
const marker = new smartmapsgl.Marker().setLngLat(event.lngLat).addTo(map);
markers.push(marker);
waypoints.push(waypoint);
const result = await routing.calcRoute(waypoints);
const route = result.features[0];
removeRoute();
map.addSource('route', {
type: 'geojson',
data: route
});
map.addLayer({
id: 'route',
type: 'line',
source: 'route',
layout: {
'line-join': 'round',
'line-cap': 'round'
},
paint: {
'line-color': '#0A5FA0',
'line-width': 8
}
});
});
</script>
</body>
</html>