เพิ่ม Google Maps ที่มีเครื่องหมายในเว็บไซต์ของคุณ

เกริ่นนำ

บทแนะนำนี้จะแสดงวิธีเพิ่ม Google Maps อย่างง่ายด้วยเครื่องหมายลงในหน้าเว็บ เหมาะสำหรับผู้ที่มีความรู้เรื่อง HTML และ CSS ระดับเริ่มต้นหรือระดับกลาง และมีความรู้เล็กน้อยเกี่ยวกับ JavaScript

แผนที่ด้านล่างเป็นแผนที่ที่คุณจะสร้างโดยใช้บทแนะนำนี้ หมุดตั้งอยู่ที่ Uluru (หรือที่เรียกว่าเอเยอร์ร็อค) ใน อุทยานแห่งชาติ Uluru-Kata Tjuta


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>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <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>

ลองใช้ตัวอย่าง

เริ่มต้นใช้งาน

การสร้าง Google แผนที่พร้อมด้วยเครื่องหมายบนหน้าเว็บมี 3 ขั้นตอน:

  1. สร้างหน้า HTML
  2. เพิ่มแผนที่ที่มีเครื่องหมาย
  3. รับคีย์ API

คุณต้องมีเว็บเบราว์เซอร์ เลือกเบราว์เซอร์ที่เป็นที่รู้จัก เช่น Google Chrome (แนะนำ), Firefox, Safari หรือ Edge โดยอิงตามแพลตฟอร์มที่คุณใช้ จากรายการเบราว์เซอร์ที่รองรับ

ขั้นตอนที่ 1: สร้างหน้า HTML

ต่อไปนี้คือโค้ดสำหรับหน้าเว็บ HTML พื้นฐาน

<!doctype html>
<!--
 @license
 Copyright 2019 Google LLC. All Rights Reserved.
 SPDX-License-Identifier: Apache-2.0
-->
<html>
  <head>
    <title>Add Map</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <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 ของคุณเอง

ขั้นตอนที่ 2: เพิ่มแผนที่ที่มีเครื่องหมาย

ส่วนนี้จะแสดงวิธีโหลด 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 คือการซูมต่ำสุดที่แสดงทั้งโลก ตั้งค่าการซูมให้สูงขึ้นเพื่อซูมเข้าบนพื้นโลกด้วยความละเอียดที่สูงขึ้น

โค้ดด้านล่างจะวางเครื่องหมายบนแผนที่ พร็อพเพอร์ตี้ 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",
});

ดูข้อมูลเพิ่มเติมเกี่ยวกับเครื่องหมาย

ขั้นตอนที่ 3: รับคีย์ API

ส่วนนี้จะอธิบายวิธีตรวจสอบสิทธิ์แอปของคุณกับ Maps JavaScript API โดยใช้คีย์ API ของคุณเอง

ทำตามขั้นตอนต่อไปนี้เพื่อรับคีย์ API

  1. ไปที่ คอนโซล Google Cloud

  2. สร้างหรือเลือกโปรเจ็กต์

  3. คลิกต่อไปเพื่อเปิดใช้ API และบริการที่เกี่ยวข้อง

  4. ในหน้าข้อมูลเข้าสู่ระบบ ให้รับคีย์ API (และตั้งค่าข้อจำกัดของคีย์ API) หมายเหตุ: หากคุณมีคีย์ API ที่ไม่จำกัดหรือมีคีย์ที่มีข้อจำกัดของเบราว์เซอร์อยู่แล้ว ก็ใช้คีย์นั้นได้

  5. หากต้องการป้องกันการขโมยโควต้าและรักษาความปลอดภัยของคีย์ API โปรดดูที่ การใช้คีย์ API

  6. เปิดใช้การเรียกเก็บเงิน ดูข้อมูลเพิ่มเติมได้ที่การใช้งานและการเรียกเก็บเงิน

  7. คัดลอกโค้ดทั้งหมดของบทแนะนำนี้จากหน้านี้ไปยังเครื่องมือแก้ไขข้อความ

  8. แทนที่ค่าพารามิเตอร์ key ใน URL ด้วยคีย์ API ของคุณเอง (ซึ่งเป็นคีย์ API ที่เพิ่งได้รับ)

    <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>
    
  9. บันทึกไฟล์นี้ด้วยชื่อที่ลงท้ายด้วย .html เช่น index.html

  10. โหลดไฟล์ HTML ในเว็บเบราว์เซอร์โดยลากไฟล์จากเดสก์ท็อปไปไว้ในเบราว์เซอร์ หรือดับเบิลคลิกไฟล์ที่ใช้ได้กับระบบปฏิบัติการส่วนใหญ่

เคล็ดลับและการแก้ปัญหา

  • คุณสามารถปรับแต่งตัวเลือกต่างๆ เช่น รูปแบบและคุณสมบัติ เพื่อปรับแต่งแผนที่ได้ สำหรับข้อมูลเพิ่มเติมเกี่ยวกับการปรับแต่งแผนที่ โปรดอ่านคำแนะนำเกี่ยวกับการจัดรูปแบบและการวาดบนแผนที่
  • ใช้คอนโซลเครื่องมือสำหรับนักพัฒนาซอฟต์แวร์ในเว็บเบราว์เซอร์เพื่อทดสอบและเรียกใช้โค้ด อ่านรายงานข้อผิดพลาด และแก้ไขปัญหาเกี่ยวกับโค้ด
  • ใช้แป้นพิมพ์ลัดต่อไปนี้เพื่อเปิดคอนโซลใน Chrome
    Command+Option+J (ใน Mac) หรือ Control+Shift+J (ใน Windows)
  • ทำตามขั้นตอนด้านล่างเพื่อรับพิกัดละติจูดและลองจิจูดของสถานที่บน Google Maps

    1. เปิด Google Maps ในเบราว์เซอร์
    2. คลิกขวาตรงตำแหน่งที่ต้องการบนแผนที่ที่คุณต้องการพิกัด
    3. เลือกที่นี่คือที่ไหนจากเมนูตามบริบทที่ปรากฏขึ้น แผนที่จะแสดงการ์ดที่ด้านล่างของหน้าจอ ค้นหาพิกัดละติจูดและลองจิจูดในแถวสุดท้ายของบัตร
  • คุณสามารถแปลงที่อยู่เป็นพิกัดละติจูดและลองจิจูดโดยใช้บริการระบุพิกัดทางภูมิศาสตร์ คู่มือนักพัฒนาซอฟต์แวร์จะให้ข้อมูลโดยละเอียดเกี่ยวกับการเริ่มต้นใช้งานบริการการเข้ารหัสพิกัดภูมิศาสตร์