บทนำ
บทแนะนำนี้จะแสดงวิธีเพิ่ม Google Maps แบบง่ายๆ พร้อมเครื่องหมายลงในหน้าเว็บ เหมาะสำหรับผู้ที่มีความรู้ระดับเริ่มต้นหรือระดับกลางเกี่ยวกับ HTML และ CSS รวมถึงมีความรู้เกี่ยวกับ JavaScript เล็กน้อย
ด้านล่างนี้คือแผนที่ที่คุณจะสร้างโดยใช้บทแนะนำนี้ เครื่องหมายนี้อยู่ที่อุลูรู (หรือที่รู้จักกันในชื่อแอร์ส ร็อก) ในอุทยานแห่งชาติอุลูรู-คาตา ทจูตา
เริ่มต้นใช้งาน
การสร้างแผนที่ Google ที่มีเครื่องหมายในหน้าเว็บมี 3 ขั้นตอนดังนี้
คุณต้องมีเว็บเบราว์เซอร์ เลือกเบราว์เซอร์ที่รู้จักกันดี เช่น Google Chrome (แนะนำ), Firefox, Safari หรือ Edge โดยอิงตามแพลตฟอร์มของคุณจากรายการเบราว์เซอร์ที่รองรับ
ขั้นตอนที่ 1: รับคีย์ API
ส่วนนี้อธิบายวิธีตรวจสอบสิทธิ์แอปกับ Maps JavaScript API โดยใช้คีย์ API ของคุณเอง
ทำตามขั้นตอนต่อไปนี้เพื่อรับคีย์ API
ไปที่ คอนโซล Google Cloud
สร้างหรือเลือกโปรเจ็กต์
คลิกต่อไปเพื่อเปิดใช้ API และบริการที่เกี่ยวข้อง
ในหน้าข้อมูลเข้าสู่ระบบ ให้รับคีย์ API (และตั้งค่าข้อจำกัดของคีย์ API) หมายเหตุ: หากมีคีย์ API ที่ไม่มีข้อจำกัดอยู่แล้ว หรือคีย์ที่มีข้อจำกัดของเบราว์เซอร์ คุณก็ใช้คีย์นั้นได้
ดูการใช้คีย์ API เพื่อป้องกันการขโมยโควต้าและรักษาคีย์ API ให้ปลอดภัย
เปิดใช้การเรียกเก็บเงิน ดูข้อมูลเพิ่มเติมได้ที่การใช้งานและการเรียกเก็บเงิน
เมื่อได้คีย์ API แล้ว ให้เพิ่มคีย์ลงในข้อมูลโค้ดต่อไปนี้โดยคลิก "YOUR_API_KEY" คัดลอกและวางแท็กสคริปต์ Bootloader เพื่อใช้ใน หน้าเว็บของคุณเอง
<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>
ขั้นตอนที่ 2: สร้างหน้า HTML
โค้ดสำหรับหน้าเว็บ HTML พื้นฐานมีดังนี้
<!doctype html> <!-- @license Copyright 2019 Google LLC. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 --> <html> <head> <title>Add Map</title> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <h3>My Google Maps Demo</h3> <!--The div element for the map --> <div id="map"></div> <!-- 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: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"});</script> </body> </html>
โปรดทราบว่าหน้านี้เป็นหน้าเว็บพื้นฐานที่มีระดับส่วนหัว 3 (h3
) และองค์ประกอบ div
เดียว คุณสามารถเพิ่มเนื้อหาใดก็ได้ที่คุณชอบในหน้าเว็บ
ทำความเข้าใจโค้ด
ในตัวอย่างนี้ เรามีสิ่งต่อไปนี้
- ประกาศแอปพลิเคชันเป็น HTML5 โดยใช้การประกาศ
!DOCTYPE html
- สร้างองค์ประกอบ div ชื่อ "map" เพื่อเก็บแผนที่
- โหลด Maps JavaScript API โดยใช้โปรแกรมโหลด Bootstrap
ประกาศแอปพลิเคชันเป็น HTML5
เราขอแนะนำให้คุณประกาศ DOCTYPE
ที่ถูกต้องภายในเว็บแอปพลิเคชัน ในตัวอย่างที่นี่ เราได้ประกาศแอปพลิเคชันเป็น HTML5 โดยใช้ HTML5 อย่างง่าย DOCTYPE
ดังที่แสดงด้านล่าง
<!DOCTYPE html>
เบราว์เซอร์ส่วนใหญ่ในปัจจุบันจะแสดงเนื้อหาที่ประกาศด้วย DOCTYPE
ใน "โหมดมาตรฐาน" ซึ่งหมายความว่าแอปพลิเคชันของคุณควรเป็นไปตาม ข้อกำหนดของเบราว์เซอร์ต่างๆ มากขึ้น นอกจากนี้ DOCTYPE
ยังออกแบบมาให้ลดระดับลงอย่างราบรื่นด้วย เบราว์เซอร์ที่ไม่เข้าใจจะเพิกเฉยต่อแท็กนี้ และใช้ "โหมดประหลาด" เพื่อ แสดงเนื้อหา
โปรดทราบว่า CSS บางรายการที่ใช้ได้ในโหมดประหลาดจะใช้ไม่ได้ใน โหมดมาตรฐาน กล่าวคือ ขนาดที่เป็นเปอร์เซ็นต์ทั้งหมดต้องสืบทอดมาจากองค์ประกอบบล็อกระดับบนสุด และหากองค์ประกอบระดับบนสุดเหล่านั้นไม่ระบุขนาด ระบบจะถือว่ามีขนาด 0 x 0 พิกเซล ด้วยเหตุนี้ เราจึงระบุstyle
คำประกาศต่อไปนี้
<style> #map { height: 100%; } html, body { height: 100%; margin: 0; padding: 0; } </style>
สร้างองค์ประกอบ div
เราต้องจองพื้นที่สำหรับแผนที่เพื่อให้แสดงในหน้าเว็บได้ โดยทั่วไป เราจะทำเช่นนี้ด้วยการสร้างองค์ประกอบ div
ที่มีชื่อและรับการอ้างอิงถึงองค์ประกอบนี้ใน Document Object Model (DOM) ของเบราว์เซอร์
โค้ดด้านล่างจะกำหนดพื้นที่ของหน้าเว็บสำหรับแผนที่ Google
<!--The div element for the map --> <div id="map"></div>
ในขั้นตอนนี้ของบทแนะนำ div
จะปรากฏเป็นเพียงบล็อกสีเทา เนื่องจาก คุณยังไม่ได้เพิ่มแผนที่ โค้ดด้านล่างอธิบาย CSS ที่กำหนด ขนาดและสีของ div
/* Set the size of the div element that contains the map */ #map { height: 400px; /* The height is 400 pixels */ width: 100%; /* The width is the width of the web page */ }
ในโค้ดด้านบน องค์ประกอบ style
จะกำหนดขนาด div
สำหรับแผนที่ กำหนด div
ความกว้างและความสูงให้มากกว่า 0 พิกเซลเพื่อให้แผนที่แสดง ในกรณีนี้ div
จะตั้งค่าความสูงเป็น 400 พิกเซล และความกว้างเป็น 100% เพื่อแสดง ความกว้างของหน้าเว็บ โปรดทราบว่าโดยปกติแล้ว div จะใช้ความกว้างจากองค์ประกอบที่บรรจุอยู่ และ div ที่ว่างเปล่ามักจะมีความสูงเป็น 0 ด้วยเหตุนี้ คุณจึงต้องกำหนดความสูงใน div
เสมอ
โหลด Maps JavaScript API
โปรแกรมโหลด Bootstrap จะเตรียม Maps JavaScript API สำหรับการโหลด (ระบบจะไม่โหลดไลบรารีจนกว่าจะมีการเรียกใช้ importLibrary()
)
<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>
ดูวิธีการรับคีย์ API ของคุณเองได้ที่ขั้นตอนที่ 3: รับคีย์ API
ขั้นตอนที่ 3: เพิ่มแผนที่ที่มีเครื่องหมาย
ส่วนนี้จะแสดงวิธีโหลด Maps JavaScript API ลงในหน้าเว็บ และวิธีเขียน JavaScript ของคุณเองที่ใช้ API เพื่อเพิ่มแผนที่พร้อมเครื่องหมาย
TypeScript
// Initialize and add the map let map; async function initMap(): Promise<void> { // The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary; const { AdvancedMarkerElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary; // The map, centered at Uluru map = new Map( document.getElementById('map') as HTMLElement, { zoom: 4, center: position, mapId: 'DEMO_MAP_ID', } ); // The marker, positioned at Uluru const marker = new AdvancedMarkerElement({ map: map, position: position, title: 'Uluru' }); } initMap();
JavaScript
// Initialize and add the map let map; async function initMap() { // The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps"); const { AdvancedMarkerElement } = await google.maps.importLibrary("marker"); // The map, centered at Uluru map = new Map(document.getElementById("map"), { zoom: 4, center: position, mapId: "DEMO_MAP_ID", }); // The marker, positioned at Uluru const marker = new AdvancedMarkerElement({ map: map, position: position, title: "Uluru", }); } initMap();
ในโค้ดด้านบน ระบบจะโหลดไลบรารี Map
และ AdvancedMarkerElement
เมื่อมีการเรียกใช้ฟังก์ชัน initMap()
ทำความเข้าใจโค้ด
ในขั้นตอนนี้ของบทแนะนำ เราได้ทำสิ่งต่อไปนี้แล้ว
- กำหนดฟังก์ชัน JavaScript ที่สร้างแผนที่ใน div
- สร้าง
AdvancedMarkerElement
เพื่อเพิ่มเครื่องหมายลงในแผนที่
เพิ่มแผนที่
โค้ดด้านล่างสร้างออบเจ็กต์ Google Maps ใหม่ และเพิ่มพร็อพเพอร์ตี้ลงใน แผนที่ ซึ่งรวมถึงจุดกึ่งกลางและระดับการซูม ดูเอกสารประกอบสำหรับ ตัวเลือกพร็อพเพอร์ตี้อื่นๆ
TypeScript
// The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary; const { AdvancedMarkerElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary; // The map, centered at Uluru map = new Map( document.getElementById('map') as HTMLElement, { zoom: 4, center: position, mapId: 'DEMO_MAP_ID', } );
JavaScript
// The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps"); const { AdvancedMarkerElement } = await google.maps.importLibrary("marker"); // The map, centered at Uluru map = new Map(document.getElementById("map"), { zoom: 4, center: position, mapId: "DEMO_MAP_ID", });
ทุกแผนที่ต้องมีตัวเลือก 2 รายการ ได้แก่ center
และ zoom
ในโค้ดด้านบน new Map()
จะสร้างออบเจ็กต์ Google Maps ใหม่ พร็อพเพอร์ตี้ center
จะบอก API ว่าควรจัดกึ่งกลางแผนที่ที่ใด
พร็อพเพอร์ตี้ zoom
จะระบุระดับการซูมสำหรับแผนที่ ระดับการซูม: 0 คือระดับการซูมต่ำสุดและแสดงทั้งโลก ตั้งค่าการซูมให้สูงขึ้นเพื่อซูมเข้าสู่ โลกที่ความละเอียดสูงขึ้น
การนำเสนอแผนที่ทั้งโลกเป็นรูปภาพเดียวอาจต้องใช้ แผนที่ขนาดใหญ่มาก หรือแผนที่ขนาดเล็กที่มีความละเอียดต่ำมาก ด้วยเหตุนี้ รูปภาพแผนที่ ใน Google Maps และ Maps JavaScript API จึงแบ่งออกเป็น "ไทล์" ของแผนที่ และ "ระดับการซูม" ที่ระดับการซูมต่ำ ชุดไทล์แผนที่ขนาดเล็กจะครอบคลุมพื้นที่กว้าง ส่วนที่ระดับการซูมสูง ไทล์จะมีความละเอียดสูงขึ้นและครอบคลุมพื้นที่ เล็กลง ระดับความละเอียดโดยประมาณที่คุณคาดว่าจะเห็นในแต่ละระดับการซูมมีดังนี้
- 1: โลก
- 5: แผ่นดินหรือทวีป
- 10: เมือง
- 15: ถนน
- 20: สิ่งปลูกสร้าง
รูปภาพ 3 รูปต่อไปนี้แสดงตำแหน่งเดียวกันในโตเกียวที่ระดับการซูม 0, 7 และ 18
เพิ่มเครื่องหมาย
โค้ดด้านล่างจะวางเครื่องหมายบนแผนที่ พร็อพเพอร์ตี้ position
จะกำหนด ตำแหน่งของเครื่องหมาย
TypeScript
// The marker, positioned at Uluru const marker = new AdvancedMarkerElement({ map: map, position: position, title: 'Uluru' });
JavaScript
// The marker, positioned at Uluru const marker = new AdvancedMarkerElement({ map: map, position: position, title: "Uluru", });
โค้ดตัวอย่างที่สมบูรณ์
ดูโค้ดตัวอย่างที่สมบูรณ์ได้ที่นี่
TypeScript
// Initialize and add the map let map; async function initMap(): Promise<void> { // The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary; const { AdvancedMarkerElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary; // The map, centered at Uluru map = new Map( document.getElementById('map') as HTMLElement, { zoom: 4, center: position, mapId: 'DEMO_MAP_ID', } ); // The marker, positioned at Uluru const marker = new AdvancedMarkerElement({ map: map, position: position, title: 'Uluru' }); } initMap();
JavaScript
// Initialize and add the map let map; async function initMap() { // The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps"); const { AdvancedMarkerElement } = await google.maps.importLibrary("marker"); // The map, centered at Uluru map = new Map(document.getElementById("map"), { zoom: 4, center: position, mapId: "DEMO_MAP_ID", }); // The marker, positioned at Uluru const marker = new AdvancedMarkerElement({ map: map, position: position, title: "Uluru", }); } 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>Add Map</title> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <h3>My Google Maps Demo</h3> <!--The div element for the map --> <div id="map"></div> <!-- 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: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"});</script> </body> </html>
ลองใช้ตัวอย่าง
ดูข้อมูลเพิ่มเติมเกี่ยวกับเครื่องหมาย
เคล็ดลับและการแก้ปัญหา
- ดูข้อมูลเพิ่มเติมเกี่ยวกับการรับพิกัดละติจูด/ลองจิจูด หรือการแปลงที่อยู่เป็นพิกัดทางภูมิศาสตร์
- คุณสามารถปรับแต่งตัวเลือกต่างๆ เช่น สไตล์และพร็อพเพอร์ตี้ เพื่อปรับแต่งแผนที่ ดูข้อมูลเพิ่มเติมเกี่ยวกับการปรับแต่งแผนที่ได้ที่คำแนะนำเกี่ยวกับการจัดรูปแบบและการวาดบนแผนที่
- ใช้คอนโซลเครื่องมือสำหรับนักพัฒนาซอฟต์แวร์ในเว็บเบราว์เซอร์เพื่อทดสอบและเรียกใช้โค้ด อ่านรายงานข้อผิดพลาด และแก้ปัญหาเกี่ยวกับโค้ด
- ใช้แป้นพิมพ์ลัดต่อไปนี้เพื่อเปิดคอนโซลใน Chrome
Command+Option+J (ใน Mac) หรือ Control+Shift+J (ใน Windows) ทำตามขั้นตอนด้านล่างเพื่อดูพิกัดละติจูดและ ลองจิจูดของสถานที่ใน Google Maps
- เปิด Google Maps ในเบราว์เซอร์
- คลิกขวาที่ตำแหน่งที่แน่นอนบนแผนที่ที่คุณต้องการ พิกัด
- เลือกมีอะไรที่นี่จากเมนูตามบริบทที่ปรากฏขึ้น แผนที่จะแสดงการ์ดที่ด้านล่างของหน้าจอ ค้นหาพิกัดละติจูด และลองจิจูดในแถวสุดท้ายของการ์ด
คุณแปลงที่อยู่เป็นพิกัดละติจูดและลองจิจูดได้โดยใช้ บริการ Geocoding คู่มือนักพัฒนาแอปมีข้อมูลโดยละเอียดเกี่ยวกับการเริ่มต้นใช้งานบริการ Geocoding