เอกสาร MapScale
การแสดงผลข้อมูลบนแผนที่

รีสไตล์แผนที่กลางคืนด้วยสี accent และ layer group

รีสไตล์แผนที่จากสี accent สีเดียว ทั้งแสงนีออนบนถนน การสลับ palette และการเปิดปิด layer group แล้วทำแนวคิดเดียวกันด้วย @mapscale/gl

เริ่มต้น

สิ่งที่คุณจะสร้าง

แผนที่กรุงเทพฯ ยามค่ำคืนที่ใช้สี accent สีเดียวควบคุมแสงนีออนบนทางหลวง มี swatch ห้าสีที่เปลี่ยนสีทันที ปุ่มธีมสลับเป็น palette แบบสว่าง และ checkbox เปิดปิดทั้งกลุ่ม layer เส้นทางตัวอย่างแบบไม่ต้องใช้ key ด้านล่างสร้าง style เองบน archive ประเทศไทยสาธารณะ จึงรันได้โดยไม่ต้องมี key และไม่ต้อง build ส่วนวิธีที่ใช้ @mapscale/gl อยู่ในขั้นตอนที่ 5 ข้อมูลพื้นฐานของแผนที่เป็น © OpenStreetMap contributors

สิ่งที่คุณจะสร้าง
cd docs/mapscale/visualizations/night-city
python3 -m http.server 4105
# open http://localhost:4105/

เก็บสีไว้ใน palette และติดแท็ก layer เป็นกลุ่ม

ทุกสีเป็น $token ที่ resolve จากหนึ่งในสอง palette บวกสี accent หนึ่งสี และทุก layer มีแท็ก group ทำให้มีแหล่งความจริงเดียวที่ repaint ได้ตามต้องการ ขั้นตอนที่ 2 ถึง 4 สร้างเป็นสคริปต์เดียวต่อกันตามลำดับ หน้าเว็บด้านล่างคือส่วนเริ่มต้น

เก็บสีไว้ใน palette และติดแท็ก layer เป็นกลุ่ม
<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1" />
	<title>Night city</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>
	<div style="position:absolute;top:12px;left:12px;z-index:1;background:rgba(10,13,18,0.85);color:#cfe7ff;font:12px/1.6 ui-monospace,monospace;padding:8px 10px;border-radius:6px">
		<div id="swatches"></div>
		<div id="toggles"></div>
		<button id="theme" type="button">Switch to light</button>
	</div>
	<script>
maplibregl.addProtocol("pmtiles", new pmtiles.Protocol().tile)

// Every non-accent colour lives in one of two palettes, so the theme button
// is just "apply the other palette".
const PALETTES = {
	dark: {
		bg: "#05070b", land: "#080b11", water: "#04101c", waterway: "#0a2236",
		building: "#1c2436", minor: "#1a2230", secondary: "#2a3446", glowOpacity: 0.45,
	},
	light: {
		bg: "#f3f1ec", land: "#eceae3", water: "#bcd8ec", waterway: "#a8cbe3",
		building: "#d8d4cb", minor: "#ffffff", secondary: "#fbfaf6", glowOpacity: 0.28,
	},
}
const ACCENTS = ["#ff2bd6", "#00e5ff", "#a6ff00", "#ff9100", "#7c4dff"]
let accent = ACCENTS[0]
let theme = "dark"

// Layer definitions tagged with a group. Colours are "$tokens": "$water" means
// PALETTES[theme].water and "$accent" means the current accent.
const lines = ["==", "$type", "LineString"]
const w = (stops) => ({ base: 1.2, stops })
const road = (id, group, cls, color, width, extra = {}) => ({
	id, group, type: "line", "source-layer": "transportation",
	filter: ["all", lines, cls],
	layout: { "line-cap": "round", "line-join": "round" },
	paint: { "line-color": color, "line-width": w(width), ...extra },
})
const motorway = ["in", "class", "motorway", "trunk"]
const primary = ["==", "class", "primary"]

const DEFS = [
	{ id: "background", group: "land", type: "background", paint: { "background-color": "$bg" } },
	{ id: "landuse", group: "land", type: "fill", "source-layer": "landuse", paint: { "fill-color": "$land" } },
	{ id: "water", group: "water", type: "fill", "source-layer": "water", paint: { "fill-color": "$water" } },
	{
		id: "waterway", group: "water", type: "line", "source-layer": "waterway",
		paint: { "line-color": "$waterway", "line-width": w([[10, 0.5], [18, 5]]) },
	},
	{
		// The archive only carries buildings from about z13: zoom in to see them.
		id: "buildings", group: "buildings", type: "fill-extrusion", "source-layer": "building", minzoom: 12,
		paint: {
			"fill-extrusion-color": "$building",
			"fill-extrusion-height": ["coalesce", ["get", "render_height"], 8],
			"fill-extrusion-base": ["coalesce", ["get", "render_min_height"], 0],
			"fill-extrusion-opacity": 0.92,
		},
	},
	road("street-minor", "streets", ["in", "class", "minor", "service", "track"], "$minor", [[13, 0.4], [18, 7]]),
	road("street-secondary", "streets", ["in", "class", "secondary", "tertiary"], "$secondary", [[11, 0.5], [18, 10]]),
	// Step 3 adds the glowing highways here (DEFS.push(...)).
]
	</script>
</body>
</html>

เพิ่มแสงนีออน

แสงเรืองเป็นเส้นกว้าง ทึบต่ำ และเบลอมาก ซ้อนอยู่ใต้เส้นถนนที่คมชัด ทั้งสองใช้ $accent การเปลี่ยนสีเดียวจึงรีสไตล์ทั้งทางหลวง คือแสงเรือง เส้น และแกนกลางสีขาวบาง ๆ ที่ทำให้ดูเหมือนหลอดนีออน วางโค้ดนี้ตรงที่คอมเมนต์ใน DEFS ระบุไว้

เพิ่มแสงนีออน
DEFS.push(
	road("glow-primary", "highways", primary, "$accent", [[9, 3], [18, 28]], { "line-blur": 10, "line-opacity": "$glow" }),
	road("glow-motorway", "highways", motorway, "$accent", [[6, 4], [18, 44]], { "line-blur": 16, "line-opacity": "$glow" }),
	road("road-primary", "highways", primary, "$accent", [[9, 0.6], [18, 9]], { "line-opacity": 0.8 }),
	road("road-motorway", "highways", motorway, "$accent", [[6, 0.8], [18, 12]]),
	road("core-motorway", "highways", motorway, "$core", [[8, 0.2], [18, 3.5]], { "line-opacity": 0.85 })
)

Resolve token สร้างแผนที่ repaint และเปิดปิดกลุ่ม

GROUPS แมปชื่อกลุ่มไปยัง id ของ layer แนวคิดเดียวกับ MAP_LAYER_GROUPS ใน @mapscale/gl resolve() แปลง $token เป็นสีจริง และตัดแท็ก group ออกก่อนสร้าง style หากจะเปลี่ยน accent หรือธีมภายหลัง ให้ส่งสีของทุก token กลับเข้า setPaintProperty แทนการโหลด style ใหม่ checkbox ของกลุ่มใช้ setLayoutProperty กับ visibility

Resolve token สร้างแผนที่ repaint และเปิดปิดกลุ่ม
const GROUPS = {}
for (const d of DEFS) {
	if (d.id !== "background") (GROUPS[d.group] ??= []).push(d.id)
}

const resolve = (value, p) => {
	if (typeof value !== "string" || value[0] !== "$") return value
	const key = value.slice(1)
	if (key === "accent") return accent
	if (key === "core") return theme === "dark" ? "#ffffff" : accent
	if (key === "glow") return p.glowOpacity
	return p[key]
}
const resolvePaint = (paint, p) =>
	Object.fromEntries(Object.entries(paint).map(([k, v]) => [k, resolve(v, p)]))

// Strip our group tag (not valid style spec) and resolve colours.
const layers = DEFS.map(({ group, ...layer }) => ({
	...layer,
	...(layer.type === "background" ? {} : { source: "ms" }),
	paint: resolvePaint(layer.paint, PALETTES[theme]),
}))

const map = new maplibregl.Map({
	container: "map",
	center: [100.5018, 13.7563], // Bangkok
	zoom: 12,
	pitch: 45,
	bearing: -12,
	minZoom: 4,
	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,
	},
})

// Repaint without reloading the style.
function repaint() {
	const p = PALETTES[theme]
	for (const d of DEFS) {
		for (const [prop, value] of Object.entries(d.paint)) {
			if (typeof value === "string" && value[0] === "$") {
				map.setPaintProperty(d.id, prop, resolve(value, p))
			}
		}
	}
}

// One swatch per accent colour.
const swatches = document.getElementById("swatches")
for (const color of ACCENTS) {
	const b = document.createElement("button")
	b.type = "button"
	b.style.background = color
	b.title = color
	b.onclick = () => {
		accent = color
		repaint()
	}
	swatches.appendChild(b)
}

// One checkbox per group.
const toggles = document.getElementById("toggles")
for (const [group, ids] of Object.entries(GROUPS)) {
	const l = document.createElement("label")
	l.style.display = "block"
	const cb = document.createElement("input")
	cb.type = "checkbox"
	cb.checked = true
	cb.onchange = () => {
		for (const id of ids) map.setLayoutProperty(id, "visibility", cb.checked ? "visible" : "none")
	}
	l.append(cb, " " + group)
	toggles.appendChild(l)
}

// Theme button: re-apply the other palette.
const themeBtn = document.getElementById("theme")
themeBtn.onclick = () => {
	theme = theme === "dark" ? "light" : "dark"
	themeBtn.textContent = theme === "dark" ? "Switch to light" : "Switch to dark"
	repaint()
}

แนวคิดเดียวกันด้วย @mapscale/gl

ในแอปที่ใช้ bundler ฟังก์ชัน createMapStyle(lang, { accentColor, transformStyle }) จาก @mapscale/gl/style คืน style object ข้อควรรู้: accentColor เปลี่ยนเฉพาะค่า paint ที่เท่ากับค่าเริ่มต้น #0c4a4a ซึ่ง base style ที่ส่งมอบไม่ได้ใช้แล้ว ดังนั้นใช้เดี่ยว ๆ จะไม่เห็นผลอะไร ให้รีสไตล์จริงใน transformStyle ซึ่งเป็นฟังก์ชัน pure ที่ห้ามแก้ input id ของ layer ด้านล่าง (background, water, building, highway-*) มาจาก style ที่ส่งมอบ layer group มาจาก @mapscale/gl/layer-groups: MAP_LAYER_GROUPS มี key streets, transit, districts, buildings, water และ landuse resolveHiddenLayerIds แปลง visibility เป็น id ของ layer และ applyLayerVisibility(style, hiddenLayerIds) คืนสำเนาที่ซ่อน layer เหล่านั้น หากไม่ใช้ build style ที่โฮสต์ไว้รับพารามิเตอร์ accent และ hide ด้วย ส่วนนี้เป็น API ตามเอกสาร ตัวอย่างที่รันได้ใช้เส้นทางแบบไม่ต้องใช้ key ด้านบนแทน

แนวคิดเดียวกันด้วย @mapscale/gl
import { createMapStyle } from "@mapscale/gl/style"
import { applyLayerVisibility, DEFAULT_LAYER_VISIBILITY, resolveHiddenLayerIds } from "@mapscale/gl/layer-groups"

const ACCENT = "#ff2bd6"

// Pure: build new layer objects, never mutate the input.
const nightStyle = createMapStyle("en", {
	transformStyle: (style) => ({
		...style,
		layers: style.layers.map((layer) => {
			const sourceLayer = layer["source-layer"]
			if (layer.id === "background") return { ...layer, paint: { "background-color": "#05070b" } }
			if (layer.id === "water-pattern") return { ...layer, layout: { ...layer.layout, visibility: "none" } }
			if (layer.type === "fill" && sourceLayer === "water") return { ...layer, paint: { ...layer.paint, "fill-color": "#04101c" } }
			if (layer.type === "fill" && sourceLayer === "building") return { ...layer, paint: { ...layer.paint, "fill-color": "#1c2436" } }
			if (layer.type === "line" && sourceLayer === "transportation") {
				const isMajor = /motorway|trunk|primary/.test(layer.id)
				const color = layer.id.includes("casing") ? "#05070b" : isMajor ? ACCENT : "#1a2230"
				return { ...layer, paint: { ...layer.paint, "line-color": color } }
			}
			return layer
		}),
	}),
})

// Hide groups: here, hide buildings.
const hidden = resolveHiddenLayerIds({ ...DEFAULT_LAYER_VISIBILITY, buildings: false })
const withoutBuildings = applyLayerVisibility(nightStyle, hidden)

// No build step: the hosted style takes the same ideas as query parameters.
// https://api.mapscale.io/styles/v1/streets?lang=th&accent=RRGGBB&hide=<groups>&key=pk_test_your_key_here

ไปต่อที่ไหนดี

หน้าเว็บฉบับเต็มที่ไม่ต้องใช้ key และทดสอบแล้วคือ docs/mapscale/visualizations/night-city (มีป้ายชื่อถนนและทางรถไฟเพิ่มด้วย) ตึกมีอยู่ใน tile ตั้งแต่ประมาณ zoom 13 จึงต้องซูมเข้าไปจึงจะเห็นตึก 3D ลองเปลี่ยน palette ของ accent ทำแสงเรืองให้ยาวขึ้น หรือเพิ่มกลุ่มของคุณเอง ต้องแสดง © OpenStreetMap contributors บนแผนที่ที่คุณเผยแพร่เสมอ

On this page

ตั้งค่า Analytics