เอกสาร MapScale
แพลตฟอร์มและ SDK

ย้ายจาก Google Maps Platform มา MapScale

แปลงการเรียก Google Maps JavaScript API สำหรับแผนที่ marker autocomplete geocoding และเส้นทาง ไปใช้ MapScale และ MapLibre GL JS ในโปรเจกต์ที่ใช้ในประเทศไทย

ปานกลาง

สิ่งที่เปลี่ยน

MapScale แสดงผลด้วย MapLibre GL JS ซึ่งเป็นไลบรารีโอเพนซอร์ส และครอบคลุมประเทศไทย โปรดตรวจความเหมาะสมก่อนใช้กับพื้นที่อื่น พิกัดเปลี่ยนจากออบเจ็กต์ { lat, lng } เป็นอาร์เรย์ [longitude, latitude] Publishable key (pk_) ใช้ในเบราว์เซอร์และแอปกับ style, tile, autocomplete, place details และ static map ส่วน secret key (sk_) ใช้บนเซิร์ฟเวอร์เท่านั้นสำหรับ geocode, reverse, route, matrix และ isochrone การเรียกที่ต้องใช้ secret key จึงต้องย้ายจากโค้ดฝั่งเบราว์เซอร์ไปที่เซิร์ฟเวอร์ของคุณ

สิ่งที่เปลี่ยน
Google Maps JavaScript API            MapScale
new google.maps.Map(el, options)     new maplibregl.Map({ container, style, center, zoom })
{ lat, lng } objects                 [lng, lat] arrays (GeoJSON order)
google.maps.Marker                   maplibregl.Marker + maplibregl.Popup
Geocoder.geocode({ address })        GET /v1/geocode?q=        (secret key, server)
Places Autocomplete                  GET /v1/autocomplete?q=   (publishable key)
Place details                        GET /v1/place/{id}        (publishable key)
Geocoder.geocode({ location })       GET /v1/reverse?point=lng,lat   (secret key, server)
DirectionsService.route(...)         GET /v1/route?coordinates=lng,lat;lng,lat&profile=driving
travelMode DRIVING / WALKING         profile=driving / walking
travelMode BICYCLING                 profile=cycling

เปลี่ยนแผนที่

แทน constructor ของ Google map ด้วยแผนที่ MapLibre ที่โหลด style ของ MapScale โหลด maplibre-gl จาก npm หรือ CDN ตามคู่มือ Web JavaScript และจำกัด key ให้ใช้ได้เฉพาะ origin ของเว็บไซต์

เปลี่ยนแผนที่
// Before: Google Maps JavaScript API
const map = new google.maps.Map(document.getElementById("map"), {
	center: { lat: 13.7563, lng: 100.5018 },
	zoom: 11,
})

// After: MapScale style rendered by MapLibre GL JS
const key = "pk_test_your_key_here"
const map = new maplibregl.Map({
	container: "map",
	style: `https://api.mapscale.io/styles/v1/streets?key=${key}&lang=th`,
	center: [100.5018, 13.7563], // [lng, lat]
	zoom: 11,
})
map.addControl(new maplibregl.NavigationControl(), "top-right")

เปลี่ยน marker และ info window

Marker และ info window ของ Google เปลี่ยนเป็น marker ของ MapLibre พร้อม popup ใช้ setText สำหรับข้อความธรรมดา เพื่อไม่ให้ข้อความจากผู้ใช้ถูกตีความเป็น HTML

เปลี่ยน marker และ info window
// Before: Google Maps JavaScript API
const marker = new google.maps.Marker({
	position: { lat: 13.7563, lng: 100.5018 },
	map,
	title: "Bangkok",
})
const info = new google.maps.InfoWindow({ content: "Bangkok" })
marker.addListener("click", () => info.open({ map, anchor: marker }))

// After: MapLibre GL JS
const popup = new maplibregl.Popup().setText("Bangkok")
new maplibregl.Marker().setLngLat([100.5018, 13.7563]).setPopup(popup).addTo(map)

เปลี่ยน Places Autocomplete

Autocomplete และ place details ใช้ publishable key ได้ ช่องค้นหาจึงอยู่ในเบราว์เซอร์ต่อไปได้ ใช้ session_token เดียวตั้งแต่การพิมพ์ตัวแรกจนถึงสถานที่ที่เลือก

เปลี่ยน Places Autocomplete
// After: browser code with a publishable key. One session token covers the
// typing and the final place lookup.
const key = "pk_test_your_key_here"
const sessionToken = crypto.randomUUID()

async function suggest(text) {
	const params = new URLSearchParams({ q: text, lang: "th", session_token: sessionToken, key })
	const response = await fetch(`https://api.mapscale.io/v1/autocomplete?${params}`)
	if (!response.ok) throw new Error(`MapScale autocomplete failed: ${response.status}`)
	const { predictions } = await response.json()
	// Each prediction: place_id, description, structured_formatting.main_text / secondary_text
	return predictions
}

async function select(placeId) {
	const params = new URLSearchParams({ lang: "th", session_token: sessionToken, key })
	const response = await fetch(
		`https://api.mapscale.io/v1/place/${encodeURIComponent(placeId)}?${params}`
	)
	if (!response.ok) throw new Error(`MapScale place lookup failed: ${response.status}`)
	const place = await response.json() // latitude, longitude, formattedAddress, province, district ...
	map.flyTo({ center: [place.longitude, place.latitude], zoom: 16 })
}

เปลี่ยน Geocoder

Forward geocoding ต้องใช้ secret key จึงต้องเรียกจากเซิร์ฟเวอร์ แล้วส่งกลับเฉพาะข้อมูลที่หน้าเว็บต้องใช้ Reverse geocoding ใช้รูปแบบเดียวกันกับ GET /v1/reverse และพารามิเตอร์ point เรียงเป็น lng,lat

เปลี่ยน Geocoder
// Before: Google Maps JavaScript API Geocoder (browser)
// const { results } = await new google.maps.Geocoder().geocode({ address: "Siam Paragon" })
// const { lat, lng } = results[0].geometry.location

// After: your server, secret key from the environment (never ship sk_ to a browser)
const params = new URLSearchParams({ q: "Siam Paragon", lang: "th", limit: "5" })
const response = await fetch(`https://api.mapscale.io/v1/geocode?${params}`, {
	headers: { "X-MapScale-Key": process.env.MAPSCALE_SECRET_KEY },
})
if (!response.ok) throw new Error(`MapScale geocode failed: ${response.status}`)
const collection = await response.json() // GeoJSON FeatureCollection
const [lng, lat] = collection.features[0].geometry.coordinates
const address = collection.features[0].place_name
// Show collection.attribution wherever you display the result.

เปลี่ยน Directions

Route API รับจุดผ่านตั้งแต่สองจุดขึ้นไป และมีโปรไฟล์ driving, walking และ cycling ส่วนเส้นทางขนส่งสาธารณะไม่อยู่ใน route API ที่ระบุไว้ หากต้องใช้ให้คงแหล่งข้อมูลอื่นไว้ ใช้ POST /v1/matrix สำหรับเวลาเดินทางแบบหลายจุดต่อหลายจุด

เปลี่ยน Directions
// Before: Google Maps JavaScript API DirectionsService (browser)
// directionsService.route({ origin, destination, travelMode: "DRIVING" })

// After: your server calls /v1/route with a secret key and returns the geometry
const params = new URLSearchParams({
	coordinates: "100.5018,13.7563;100.5348,13.7466", // lng,lat;lng,lat
	profile: "driving", // or walking, cycling
	lang: "th",
})
const response = await fetch(`https://api.mapscale.io/v1/route?${params}`, {
	headers: { "X-MapScale-Key": process.env.MAPSCALE_SECRET_KEY },
})
if (!response.ok) throw new Error(`MapScale route failed: ${response.status}`)
const { routes } = await response.json()
const route = routes[0] // distance (meters), duration (seconds), geometry (GeoJSON LineString)

// In the browser, draw the geometry your server returned:
map.addSource("route", { type: "geojson", data: { type: "Feature", properties: {}, geometry: route.geometry } })
map.addLayer({
	id: "route",
	type: "line",
	source: "route",
	paint: { "line-color": "#1d4ed8", "line-width": 5 },
})

ตรวจสอบก่อนใช้งานจริง

แสดงข้อความ attribution ที่ได้จาก API และบนแผนที่ตามคู่มือ attribution เปรียบเทียบผลลัพธ์กับที่อยู่และเส้นทางของคุณเอง ไม่ควรสมมติว่าเหมือนกัน เปิดใช้ทั้งสองผู้ให้บริการหลัง feature flag จนกว่าจะผ่านการตรวจ แล้วจึงถอด script และ key ของ Google

On this page

ตั้งค่า Analytics