เส้นทางที่ดูเหมือนออกแบบมาแล้ว
casing และเส้น accent เส้นทางสำรองแบบประ marker แบบวงกลม fitBounds และ animation วาดเส้นเข้ามาสำหรับเส้นทาง
เริ่มต้น
สิ่งที่คุณจะสร้าง
เส้นทางขับรถจากสยามไปอารีย์ที่ดูเหมือนผ่านการออกแบบ ไม่ใช่แค่วางเส้น คือมี casing สีเกือบดำใต้เส้น accent สีฟ้าไซยานที่ปลายมน มีเส้นทางสำรองสีอำพันแบบประ มี marker จุดเริ่มและจุดสิ้นสุด กล้องที่จัดกรอบให้เห็นทั้งสองเส้นทาง และเส้นที่วาดตัวเองเข้ามา ไฟล์เส้นทางเป็นเส้นทางขับรถจริง (GeoJSON LineString รูปแบบเดียวกับที่ route API ส่งกลับ) จึงต้องเปิดผ่าน http ข้อมูลพื้นฐานของแผนที่เป็น © OpenStreetMap contributors
cd docs/mapscale/visualizations/designed-route
python3 -m http.server 4103
# open http://localhost:4103/สร้างหน้าเว็บและทำให้แผนที่พื้นหลังเงียบ
เส้นทางจะดูเหมือนออกแบบก็ต่อเมื่อแผนที่พื้นหลังเงียบอยู่ข้างใต้ ถนนจึงใช้สีเทาเกือบดำ attribution ของ source ใส่เครดิต OpenStreetMap ไว้แล้ว
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>A route that looks designed</title>
<style>
html,
body,
#map {
height: 100%;
margin: 0;
}
</style>
<link rel="stylesheet" href="https://unpkg.com/maplibre-gl@5/dist/maplibre-gl.css" />
<script src="https://unpkg.com/maplibre-gl@5/dist/maplibre-gl.js"></script>
<script src="https://unpkg.com/pmtiles@4/dist/pmtiles.js"></script>
</head>
<body>
<div id="map"></div>
<script>
maplibregl.addProtocol("pmtiles", new pmtiles.Protocol().tile)
const map = new maplibregl.Map({
container: "map",
center: [100.54, 13.76],
zoom: 12,
style: {
version: 8,
glyphs: "https://maps.thaipropertiesnetwork.com/{fontstack}/{range}.pbf",
sources: {
ms: {
type: "vector",
url: "pmtiles://https://maps.thaipropertiesnetwork.com/thailand-v2.pmtiles",
attribution: "© OpenStreetMap contributors · MapScale",
},
},
layers: [
{ id: "background", type: "background", paint: { "background-color": "#0a0d12" } },
{ id: "landuse", type: "fill", source: "ms", "source-layer": "landuse", paint: { "fill-color": "#0e1219" } },
{ id: "water", type: "fill", source: "ms", "source-layer": "water", paint: { "fill-color": "#0c141f" } },
{
id: "roads",
type: "line",
source: "ms",
"source-layer": "transportation",
filter: ["==", "$type", "LineString"],
paint: { "line-color": "#1b232e", "line-width": { base: 1.2, stops: [[11, 0.5], [18, 10]] } },
},
],
},
})
// drawTo() from step 5 goes here, before the load handler.
map.on("load", async () => {
// Steps 3 to 5 go here.
})
</script>
</body>
</html>โหลดเส้นทางเข้า GeoJSON source
แต่ละไฟล์เป็น GeoJSON Feature ที่มี geometry แบบ LineString lineMetrics: true ทำให้ MapLibre คำนวณ line-progress ตามความยาวเส้น ซึ่ง animation วาดเข้ามาต้องใช้ เส้นทางสำรองแบบประเพิ่มก่อน เพื่อให้อยู่ใต้เส้นทางหลัก บางและเงียบ
const [main, other] = await Promise.all([
fetch("data/siam-to-ari.geojson").then((r) => r.json()),
fetch("data/siam-to-chatuchak.geojson").then((r) => r.json()),
])
map.addSource("route", { type: "geojson", data: main, lineMetrics: true })
map.addSource("alt", { type: "geojson", data: other })
map.addLayer({
id: "alt-line",
type: "line",
source: "alt",
layout: { "line-cap": "butt", "line-join": "round" },
paint: { "line-color": "#ffb454", "line-width": 3, "line-opacity": 0.8, "line-dasharray": [2, 2] },
})เพิ่ม casing เส้น accent และ marker
casing กว้างกว่าและเกือบดำ ช่วยตัดเส้นทางออกจากถนนที่วิ่งตาม ทำให้อ่านง่ายบนถนนสีใกล้กัน ปลายและมุมมนช่วยไม่ให้เส้นแตกเป็นท่อนที่ทุกจุดหักเลี้ยว marker จุดเริ่มและจุดสิ้นสุดเป็น circle layer (ไม่ใช้ DOM ไม่ใช้รูป) วงแหวนสีขาวรอบจุดสีดูเป็นสถานที่ ไม่ใช่แค่จุดหักเลี้ยว
const round = { "line-cap": "round", "line-join": "round" }
map.addLayer({
id: "route-casing",
type: "line",
source: "route",
layout: round,
paint: { "line-color": "#05070a", "line-width": 11, "line-opacity": 0.92 },
})
map.addLayer({
id: "route-line",
type: "line",
source: "route",
layout: round,
paint: { "line-color": "#35e0ff", "line-width": 4.5 },
})
const coords = main.geometry.coordinates
const end = (kind, i, color) => ({
type: "Feature",
properties: { kind, color },
geometry: { type: "Point", coordinates: coords[i] },
})
map.addSource("ends", {
type: "geojson",
data: {
type: "FeatureCollection",
features: [end("start", 0, "#ffffff"), end("end", coords.length - 1, "#35e0ff")],
},
})
map.addLayer({
id: "ends",
type: "circle",
source: "ends",
paint: {
"circle-radius": 7,
"circle-color": ["get", "color"],
"circle-stroke-color": "#05070a",
"circle-stroke-width": 3,
},
})จัดกรอบให้เห็นทั้งสองเส้นทางและวาดเส้นเข้ามา
fitBounds รับ [[west, south], [east, north]] ให้ขยาย LngLatBounds ทีละจุดและใส่ padding เพื่อไม่ให้เส้นทางชน overlay การวาดเข้ามาทำโดยขยับ stop ของ line-gradient จาก 0 ถึง 1 gradient คือสีจนถึงความคืบหน้า p แล้วโปร่งใสหลังจากนั้น และ line-progress วิ่ง 0 ถึง 1 ตามเส้น ทำ animation ทั้งเส้น accent และ casing แล้วเอา gradient ออกเพื่อให้ paint ปกติทำงานต่อ
// Define once, before the load handler. Stops must be strictly ascending, hence the clamp.
function drawTo(color, clear, p) {
const q = Math.min(Math.max(p, 0.001), 0.998)
return ["interpolate", ["linear"], ["line-progress"], 0, color, q, color, q + 0.001, clear, 1, clear]
}
// Inside the load handler, after the layers:
const bounds = new maplibregl.LngLatBounds()
for (const c of coords) bounds.extend(c)
for (const c of other.geometry.coordinates) bounds.extend(c)
map.fitBounds(bounds, { padding: { top: 90, bottom: 60, left: 60, right: 60 }, duration: 0 })
const t0 = performance.now()
const total = 2500 // ms
const tick = (now) => {
const p = Math.min((now - t0) / total, 1)
const e = 1 - (1 - p) ** 3 // ease-out cubic
if (p < 1) {
map.setPaintProperty("route-line", "line-gradient", drawTo("rgba(53,224,255,1)", "rgba(53,224,255,0)", e))
map.setPaintProperty("route-casing", "line-gradient", drawTo("rgba(5,7,10,0.92)", "rgba(5,7,10,0)", e))
requestAnimationFrame(tick)
} else {
map.setPaintProperty("route-line", "line-gradient", undefined)
map.setPaintProperty("route-casing", "line-gradient", undefined)
}
}
requestAnimationFrame(tick)ดึงเส้นทางจริงและไปต่อที่ไหนดี
ถ้าจะใช้ API จริงแทนไฟล์ ให้สร้าง key ที่ mapscale.io แล้วเรียก route endpoint โดย coordinates เป็น lng,lat;lng,lat และ profile เป็น driving หรือ walking (cycling จะได้ 400) รองรับการยืนยันตัวตนด้วย query parameter ?key= (ใช้ header x-api-key หรือ Bearer token ได้เช่นกัน) ผลลัพธ์เป็น { code: "Ok", routes: [{ distance (เมตร), duration (วินาที), geometry: GeoJSON LineString }] } จึงนำ geometry ใส่ route source ได้ทันที หน้าเว็บฉบับเต็มที่ทดสอบแล้วคือ docs/mapscale/visualizations/designed-route ต้องแสดง © OpenStreetMap contributors ไว้เสมอ
const url =
"https://api.mapscale.io/v1/route" +
"?coordinates=100.53391,13.74601;100.54447,13.77969" +
"&profile=driving&key=pk_test_your_key_here"
const resp = await fetch(url)
if (!resp.ok) throw new Error("route request failed")
const res = await resp.json()
const route = res.routes[0]
map.getSource("route").setData({ type: "Feature", properties: {}, geometry: route.geometry })