กำลังโหลดตัวอย่างแผนที่...
ตัวอย่างการคำนวณเส้นทางเดินรถ แสดงระยะทาง ระยะเวลาเดินทาง และวาดเส้น Polyline บนแผนที่ผ่าน OSRM Routing API
<!doctype html>
<html lang="en">
<head>
<title>CalculateRoute</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="stylesheet"
href="https://unpkg.com/maplibre-gl@5.16.0/dist/maplibre-gl.css"
/>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Kanit:wght@300;400;500;600&display=swap"
rel="stylesheet"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"
/>
<script src="https://unpkg.com/maplibre-gl@5.16.0/dist/maplibre-gl.js"></script>
<style>
body {
margin: 0;
padding: 0;
font-family: "Kanit", sans-serif;
}
html,
body,
#map {
height: 100%;
}
.route-form {
max-width: 800px;
margin: auto;
padding: 16px;
border-radius: 12px;
background: #fff;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}
.route-form h3 {
margin-bottom: 16px;
font-size: 18px;
}
.route-info {
position: absolute;
bottom: 10px;
right: 100px;
margin-top: 16px;
padding: 12px;
background: #f8fafc;
border-radius: 8px;
display: flex;
gap: 20px;
justify-content: space-between;
font-size: 14px;
}
.route-info strong {
color: #334155;
}
.coord-grid {
grid-template-columns: 1fr auto 1fr;
gap: 12px;
align-items: center;
margin-bottom: 20px;
}
.coord-box {
display: flex;
flex-direction: column;
gap: 8px;
}
.coord-box .title {
font-weight: 100;
font-size: 14px;
}
.coord-box input {
padding: 8px 10px;
border: 1px solid #ddd;
border-radius: 6px;
font-family: "kanit", sans-serif;
}
.route-drawer {
position: absolute;
top: 0;
left: 0;
width: 180px;
padding: 20px;
overflow-y: auto;
transform: translateX(-100%);
transition: transform 0.3s ease;
z-index: 20;
}
.route-drawer.open {
transform: translateX(0);
}
.drawer-backdrop {
position: absolute;
inset: 0;
opacity: 0;
visibility: hidden;
transition: 0.3s;
z-index: 15;
}
.drawer-backdrop.show {
opacity: 1;
visibility: visible;
}
.drawer-toggle {
position: absolute;
top: 20px;
left: 20px;
z-index: 25;
background: #2564eb;
color: white;
border: none;
padding: 10px 14px;
border-radius: 8px;
cursor: pointer;
font-weight: 500;
box-shadow: 0 6px 15px rgba(0, 0, 0, 0.25);
}
@media (max-width: 600px) {
.coord-grid {
grid-template-columns: 1fr;
}
.route-form {
width: 90%;
left: 5%;
}
}
.route-drawer-title {
text-align: center;
margin-bottom: 10px;
background-color: white;
padding: 4px;
border-radius: 12px;
font-size: 14px;
font-weight: 100;
}
.btn-calculate-route {
width: 100%;
padding: 6px;
border-radius: 8px;
border: 1px solid #f5f5f5;
background: #2564eb;
color: white;
cursor: pointer;
font-weight: 500;
box-shadow: 0 6px 15px rgba(0, 0, 0, 0.25);
font-family: "kanit", sans-serif;
}
.drawer-toggle.hidden,
.spinner.hidden {
display: none;
}
.hidden {
display: none;
}
.spinner {
width: 16px;
height: 16px;
border: 2px solid #fff;
border-top: 2px solid transparent;
border-radius: 50%;
display: inline-block;
margin-left: 8px;
animation: spin 0.8s linear infinite;
vertical-align: middle;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
</style>
</head>
<body>
<button class="drawer-toggle hidden" onclick="openDrawer()">
☰ เส้นทาง
</button>
<div class="drawer-backdrop show" onclick="closeDrawer()"></div>
<div class="route-drawer open" id="drawer">
<div class="route-drawer-title">
<i class="fa-regular fa-compass"></i>
<span style="margin-left: 6px">คู่พิกัดเริ่มต้นแลสิ้นสุด </span>
</div>
<!-- เอา form เดิมทั้งหมดมาใส่ตรงนี้ -->
<div class="route-form">
<div class="coord-grid">
<!-- Start -->
<div class="coord-box">
<div class="title">พิกัดเริ่มต้น</div>
<input id="lon_start" type="text" placeholder="ลองจิจูด" />
<input id="lat_start" type="text" placeholder="ละติจูด" />
</div>
<!-- End -->
<div class="coord-box" style="margin-top: 10px">
<div class="title">พิกัดสิ้นสุด</div>
<input id="lon_end" type="text" placeholder="ลองจิจูด" />
<input id="lat_end" type="text" placeholder="ละติจูด" />
</div>
</div>
<button
id="btnRoute"
class="btn-calculate-route"
onclick="calculateRoute()"
>
<span id="btnText">คำนวณเส้นทาง</span>
<span id="btnLoading" class="spinner hidden"></span>
</button>
</div>
</div>
<div id="map"></div>
<div id="route-info" class="route-info" style="display: none">
<div>
<strong>ระยะทาง:</strong>
<span id="distance"></span>
</div>
<div>
<strong>ระยะเวลา:</strong>
<span id="duration"></span>
</div>
</div>
<script>
const key = "api key";
const map = new maplibregl.Map({
container: "map",
style: {
version: 8,
sources: {
osm: {
type: "raster",
tiles: [
`https://maptile.onegeo.co.th/tile/{z}/{x}/{y}.png?ApiKey=${key}`,
],
tileSize: 512,
},
},
layers: [
{
id: "osm",
type: "raster",
source: "osm",
},
],
},
center: [100.5018, 13.7563],
zoom: 8,
});
function calculateRoute() {
const btn = document.getElementById("btnRoute");
const btnText = document.getElementById("btnText");
const btnLoading = document.getElementById("btnLoading");
const lonStart = document.getElementById("lon_start").value;
const latStart = document.getElementById("lat_start").value;
const lonEnd = document.getElementById("lon_end").value;
const latEnd = document.getElementById("lat_end").value;
const coordinates = `${lonStart},${latStart};${lonEnd},${latEnd}`;
const url = `https://map-osrm.onegeo.co.th/route/v1/car/${coordinates}?overview=full&steps=true&ApiKey=${key}`;
btn.disabled = true;
btnText.textContent = "กำลังคำนวณ...";
btnLoading.classList.remove("hidden");
fetch(url)
.then((res) => res.json())
.then((data) => {
drawRoute(data);
})
.catch((err) => {
alert("ไม่สามารถคํานวณเส้นทางได้");
console.error(err);
})
.finally(() => {
btn.disabled = false;
btnText.textContent = "คำนวณเส้นทาง";
btnLoading.classList.add("hidden");
});
}
function formatDistance(meters) {
return meters > 1000
? (meters / 1000).toFixed(2) + " กม."
: meters.toFixed(0) + " ม.";
}
function formatDuration(seconds) {
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
if (h > 0) return `${h} ชม. ${m} นาที`;
return `${m} นาที`;
}
function drawRoute(data) {
const route = data.routes[0].geometry;
// ลบ route เก่า
if (map.getSource("route")) {
map.removeLayer("route");
map.removeSource("route");
}
map.addSource("route", {
type: "geojson",
data: {
type: "Feature",
geometry: route,
},
});
map.addLayer({
id: "route",
type: "line",
source: "route",
paint: {
"line-color": "#2563eb",
"line-width": 4,
},
});
// แสดง distance / duration
const distance = data.routes[0].distance;
const duration = data.routes[0].duration;
document.getElementById("distance").innerText =
formatDistance(distance);
document.getElementById("duration").innerText =
formatDuration(duration);
document.getElementById("route-info").style.display = "flex";
fitMapToRoute(route.coordinates);
addMarkers(data.waypoints[0].location, data.waypoints[1].location);
}
function fitMapToRoute(coords) {
const bounds = coords.reduce(
(b, c) => b.extend(c),
new maplibregl.LngLatBounds(coords[0], coords[0]),
);
map.fitBounds(bounds, {
padding: 40,
duration: 800,
});
}
let startMarker, endMarker;
function addMarkers(start, end) {
if (startMarker) startMarker.remove();
if (endMarker) endMarker.remove();
startMarker = new maplibregl.Marker({ color: "green" })
.setLngLat(start)
.addTo(map);
endMarker = new maplibregl.Marker({ color: "red" })
.setLngLat(end)
.addTo(map);
}
function openDrawer() {
document.getElementById("drawer").classList.add("open");
document.querySelector(".drawer-backdrop").classList.add("show");
// ซ่อนปุ่ม
document.querySelector(".drawer-toggle").style.display = "none";
}
function closeDrawer() {
document.getElementById("drawer").classList.remove("open");
document.querySelector(".drawer-backdrop").classList.remove("show");
// แสดงปุ่มกลับมา
document.querySelector(".drawer-toggle").style.display = "block";
}
</script>
</body>
</html>