คุณสามารถเพิ่มแผนที่ของ Google ลงในหน้าเว็บได้โดยใช้โค้ด HTML, CSS และ JavaScript หน้านี้แสดงวิธีเพิ่มแผนที่ลงในหน้าเว็บ แล้วเข้าถึงอินสแตนซ์ของแผนที่แบบเป็นโปรแกรม
- เพิ่มแผนที่โดยใช้องค์ประกอบ
gmp-map - เพิ่มแผนที่โดยใช้องค์ประกอบ
divและ JavaScript - ตั้งค่าและรับพร็อพเพอร์ตี้ในอินสแตนซ์ของแผนที่
ภาพรวม
หากต้องการโหลดแผนที่ หน้าเว็บต้องทำสิ่งต่อไปนี้
- โหลด Maps JavaScript API โดยใช้ตัวโหลด Bootstrap ซึ่งเป็นตำแหน่งที่จะส่งคีย์ API คุณสามารถเพิ่มคีย์ API ลงในไฟล์ซอร์ส HTML หรือ JavaScript ก็ได้
- เพิ่มแผนที่ลงในหน้า HTML และเพิ่มสไตล์ CSS ที่จำเป็น
- โหลดไลบรารี
mapsและเริ่มต้นแผนที่
เพิ่มแผนที่โดยใช้องค์ประกอบ gmp-map
องค์ประกอบ gmp-map เป็นวิธีที่แนะนำในการเพิ่มแผนที่ของ Google ลงในหน้าเว็บ
โดยเป็นองค์ประกอบ HTML ที่กำหนดเองซึ่งสร้างขึ้นโดยใช้คอมโพเนนต์เว็บ หากต้องการเพิ่มแผนที่ลงในหน้าเว็บโดยใช้องค์ประกอบ gmp-map ให้ทำตามขั้นตอนต่อไปนี้
เพิ่มองค์ประกอบ
scriptที่มี Bootstrap ลงในหน้า HTML หรือเพิ่มลงในไฟล์ซอร์ส JavaScript หรือ TypeScript โดยไม่มีองค์ประกอบscriptกำหนดค่า Bootstrap ด้วยคีย์ API และตัวเลือกอื่นๆ คุณสามารถเลือกนำเข้าไลบรารีแบบไดนามิกหรือโหลดสคริปต์โดยตรงก็ได้ ตัวอย่างนี้แสดงการเพิ่ม Bootstrap สำหรับการโหลดสคริปต์แบบไดนามิกไปยังหน้า HTML<script> (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({ key: "YOUR_API_KEY", v: "weekly", // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.). // Add other bootstrap parameters as needed, using camel case. }); </script>
ดูข้อมูลเพิ่มเติมเกี่ยวกับการโหลด Google Maps JavaScript API
เพิ่มองค์ประกอบ
gmp-mapในหน้า HTML ระบุพิกัดละติจูดและลองจิจูดสำหรับcenter(ต้องระบุ) ค่าซูมสำหรับzoom(ต้องระบุ) และmap-idหากจำเป็น (ต้องระบุสำหรับฟีเจอร์บางอย่าง เช่น เครื่องหมายขั้นสูง)
<gmp-map center="-34.397,150.644" zoom="8" mapId="DEMO_MAP_ID"> </gmp-map>
โค้ดตัวอย่างที่สมบูรณ์
TypeScript
async function initMap(): Promise<void> { // Import the needed libraries. await google.maps.importLibrary('maps'); // Create the map. const mapElement = document.querySelector('gmp-map') as google.maps.MapElement; // Access the underlying map object. const innerMap = mapElement.innerMap; } initMap();
JavaScript
async function initMap() { // Import the needed libraries. await google.maps.importLibrary('maps'); // Create the map. const mapElement = document.querySelector('gmp-map'); // Access the underlying map object. const innerMap = mapElement.innerMap; } initMap();
CSS
/* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
HTML
<html>
<head>
<title>Simple Map</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
<!-- prettier-ignore -->
<script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
({key: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly" });</script>
</head>
<body>
<gmp-map center="-34.397,150.644" zoom="8" mapId="DEMO_MAP_ID">
</gmp-map>
</body>
</html>ลองใช้ตัวอย่าง
เพิ่มแผนที่โดยใช้องค์ประกอบ div และ JavaScript
หากต้องการเพิ่มแผนที่ลงในหน้าเว็บโดยใช้องค์ประกอบ div ให้ทำตามขั้นตอนต่อไปนี้
เพิ่มองค์ประกอบ
scriptที่มี Bootstrap ลงในหน้า HTML หรือเพิ่มลงในไฟล์ซอร์ส JavaScript หรือ TypeScript โดยไม่มีองค์ประกอบscriptกำหนดค่า Bootstrap ด้วยคีย์ API และตัวเลือกอื่นๆ คุณสามารถเลือกนำเข้าไลบรารีแบบไดนามิกหรือโหลดสคริปต์โดยตรงก็ได้ ตัวอย่างนี้แสดงการเพิ่ม Bootstrap แบบไดนามิกไปยังหน้า HTML<script> (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({ key: "YOUR_API_KEY", v: "weekly", // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.). // Add other bootstrap parameters as needed, using camel case. }); </script>
ดูข้อมูลเพิ่มเติมเกี่ยวกับการโหลด Google Maps JavaScript API
เพิ่มองค์ประกอบ
divในหน้า HTML เพื่อให้มีแผนที่<div id="map"></div>
ตั้งค่าความสูงของแผนที่เป็น 100% ใน CSS ต้องระบุแอตทริบิวต์
heightของ CSS เพื่อให้แผนที่แสดง#map { height: 100%; }
สร้างฟังก์ชันเพื่อโหลดไลบรารี
mapsและเริ่มต้นแผนที่ในไฟล์ JS หรือ TS ระบุพิกัดละติจูดและลองจิจูดสำหรับcenterและระดับการซูมที่จะใช้สำหรับzoomหากจำเป็น ให้เพิ่มรหัสแผนที่โดยใช้พร็อพเพอร์ตี้mapIdเนื่องจากแผนที่จะแสดงผลแบบแรสเตอร์โดยค่าเริ่มต้น ให้ขอแผนที่เวกเตอร์โดยระบุตัวเลือกแผนที่ "VECTOR" เราขอแนะนำให้ใช้แผนที่เวกเตอร์เพื่อให้ผู้ใช้ได้รับประสบการณ์ที่ดีที่สุด เนื่องจากแผนที่เวกเตอร์ให้ความแม่นยำของภาพที่ดียิ่งขึ้น รวมถึงความสามารถในการควบคุมการเอียงและทิศทางบนแผนที่TypeScript
let map: google.maps.Map; async function initMap(): Promise<void> { // Import the needed libraries const { Map, RenderingType } = (await google.maps.importLibrary( 'maps' )) as google.maps.MapsLibrary; // Create a new map from the div with id="map". map = new Map(document.getElementById('map') as HTMLElement, { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: "VECTOR", }); } initMap();
JavaScript
let map; async function initMap() { // Import the needed libraries const { Map, RenderingType } = (await google.maps.importLibrary('maps')); // Create a new map from the div with id="map". map = new Map(document.getElementById('map'), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: "VECTOR", }); } initMap();
ดูซอร์สโค้ดตัวอย่างที่สมบูรณ์
TypeScript
let map: google.maps.Map; async function initMap(): Promise<void> { // Import the needed libraries const { Map, RenderingType } = (await google.maps.importLibrary( 'maps' )) as google.maps.MapsLibrary; // Create a new map from the div with id="map". map = new Map(document.getElementById('map') as HTMLElement, { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: "VECTOR", }); } initMap();
JavaScript
let map; async function initMap() { // Import the needed libraries const { Map, RenderingType } = (await google.maps.importLibrary('maps')); // Create a new map from the div with id="map". map = new Map(document.getElementById('map'), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: "VECTOR", }); } initMap();
CSS
/* * Always set the map height explicitly to define the size of the div element * that contains the map. */ #map { height: 100%; } /* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
HTML
<html>
<head>
<title>Simple Map</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
<!-- prettier-ignore -->
<script>(g => { var h, a, k, p = "The Google Maps JavaScript API", c = "google", l = "importLibrary", q = "__ib__", m = document, b = window; b = b[c] || (b[c] = {}); var d = b.maps || (b.maps = {}), r = new Set, e = new URLSearchParams, u = () => h || (h = new Promise(async (f, n) => { await (a = m.createElement("script")); e.set("libraries", [...r] + ""); for (k in g) e.set(k.replace(/[A-Z]/g, t => "_" + t[0].toLowerCase()), g[k]); e.set("callback", c + ".maps." + q); a.src = `https://maps.${c}apis.com/maps/api/js?` + e; d[q] = f; a.onerror = () => h = n(Error(p + " could not load.")); a.nonce = m.querySelector("script[nonce]")?.nonce || ""; m.head.append(a) })); d[l] ? console.warn(p + " only loads once. Ignoring:", g) : d[l] = (f, ...n) => r.add(f) && u().then(() => d[l](f, ...n)) })
({ key: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly" });</script>
</body>
</head>
<body>
<div id="map"></div>
</body>
</html>ลองใช้ตัวอย่าง
ตั้งค่าและรับพร็อพเพอร์ตี้ในอินสแตนซ์ของแผนที่
หากต้องการโต้ตอบกับอินสแตนซ์ของแผนที่ ให้เลือกองค์ประกอบที่มีแผนที่ โค้ดที่ใช้จะแตกต่างกันไปตามว่าคุณใช้องค์ประกอบ gmp-map หรือองค์ประกอบ div
รับอินสแตนซ์ของแผนที่จากองค์ประกอบ gmp-map
หากต้องการรับอินสแตนซ์ของแผนที่เมื่อใช้องค์ประกอบ gmp-map ให้ใช้
document.querySelector เพื่อดึงอินสแตนซ์ mapElement
ดังที่แสดงไว้ที่นี่
const mapElement = document.querySelector('gmp-map') as google.maps.MapElement;
จากนั้นตั้งค่าพร็อพเพอร์ตี้ในอินสแตนซ์ mapElement ดังนี้
mapElement.zoom = 8;
คลาส MapElement ใช้คลาส Map ภายใน เข้าถึงคลาส Map
โดยใช้พร็อพเพอร์ตี้ MapElement.innerMap ดังที่แสดงไว้ที่นี่
mapElement.innerMap.setOptions({
mapTypeControl: false,
});
รับอินสแตนซ์ของแผนที่จากองค์ประกอบ div
เมื่อใช้องค์ประกอบ div ให้รับอินสแตนซ์ของแผนที่และตั้งค่าตัวเลือกในเวลาเริ่มต้น
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
mapTypeControl: false,
});
หลังจากเริ่มต้นแล้ว ให้ตั้งค่าตัวเลือกในอินสแตนซ์ map ดังที่แสดงไว้ที่นี่
map.setOptions({
zoom: 8,
});