เกริ่นนำ
บทแนะนำนี้จะแสดงวิธีเพิ่มแผนที่ Google อย่างง่ายโดยใช้เครื่องหมายลงในหน้าเว็บ ซึ่งเหมาะกับผู้ที่มีความรู้เบื้องต้นหรือระดับกลางเกี่ยวกับ HTML และ CSS และมีความรู้เรื่อง JavaScript เล็กน้อย
ด้านล่างนี้คือแผนที่ที่คุณจะสร้างโดยใช้บทแนะนำนี้ เครื่องหมายแสดงตำแหน่งอยู่ที่ Uluru (หรือที่เรียกว่าเอเยอร์ร็อค) ใน อุทยานแห่งชาติ Uluru-Kata Tjuta
เริ่มต้นใช้งาน
การสร้างแผนที่ Google ด้วยเครื่องหมายบนหน้าเว็บของคุณมีสามขั้นตอนดังนี้:
คุณต้องมีเว็บเบราว์เซอร์ เลือกเบราว์เซอร์ที่รู้จักกันดี เช่น 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>
style="height: 400px"
ขั้นตอนที่ 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
รายการเดียว คุณสามารถเพิ่มเนื้อหาใดก็ได้ที่ต้องการลงในหน้าเว็บ
ทำความเข้าใจโค้ด
โค้ดด้านล่างจะสร้างหน้า HTML ที่ประกอบด้วยส่วนหัวและส่วนเนื้อหา
<html> <head> </head> <body> </body> </html>
คุณสามารถเพิ่มส่วนหัวระดับที่ 3 เหนือแผนที่โดยใช้โค้ดด้านล่าง
<h3>My Google Maps Demo</h3>
รหัสด้านล่างนี้จะระบุพื้นที่ของหน้าเว็บสำหรับ Google Maps
<!--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
ให้มากกว่า 0px เพื่อให้แสดงแผนที่ได้ ในกรณีนี้ div
จะตั้งไว้ที่ความสูง 400 พิกเซลและความกว้าง 100% เพื่อแสดงตามความกว้างของหน้าเว็บ
ตัวโหลด 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>
โปรดดูขั้นตอนที่ 3: รับคีย์ API เพื่อดูวิธีการรับคีย์ 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
และ AdvancedMarkerView
เมื่อมีการเรียกใช้ฟังก์ชัน initMap()
ทำความเข้าใจโค้ด
โค้ดด้านล่างสร้างออบเจ็กต์ 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", });
ในโค้ดข้างต้น new Map()
จะสร้างวัตถุใหม่ใน Google Maps พร็อพเพอร์ตี้ center
จะบอก API ว่าต้องตั้งศูนย์กลางของแผนที่ไว้ที่ใด
เรียนรู้เพิ่มเติมเกี่ยวกับการรับพิกัดละติจูด/ลองจิจูด หรือการแปลงที่อยู่เป็นพิกัดทางภูมิศาสตร์
พร็อพเพอร์ตี้ zoom
ระบุระดับการซูมสำหรับแผนที่ ซูม: 0 คือการซูมที่ต่ำที่สุด
และแสดงทั้งโลก ตั้งค่าการซูมให้สูงขึ้นเพื่อซูมเข้า
ไปยัง Earth ในความละเอียดที่สูงขึ้น
โค้ดด้านล่างวางเครื่องหมายบนแผนที่ พร็อพเพอร์ตี้ 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 ในเบราว์เซอร์
- คลิกขวาตรงตำแหน่งบนแผนที่ที่คุณต้องการพิกัด
- เลือกที่นี่คือที่ไหนจากเมนูตามบริบทที่ปรากฏขึ้น แผนที่จะแสดงการ์ดที่ด้านล่างของหน้าจอ ค้นหาพิกัดละติจูดและลองจิจูดในแถวสุดท้ายของการ์ด
คุณสามารถแปลงที่อยู่เป็นพิกัดละติจูดและลองจิจูดโดยใช้บริการการระบุพิกัดทางภูมิศาสตร์ได้ คู่มือนักพัฒนาซอฟต์แวร์จะให้ข้อมูลโดยละเอียดเกี่ยวกับการเริ่มต้นใช้งานบริการการระบุพิกัดทางภูมิศาสตร์