เพิ่ม Google Maps ลงในหน้าเว็บ

คุณเพิ่ม Google Maps ลงในหน้าเว็บได้โดยใช้โค้ด HTML, CSS และ JavaScript หน้านี้แสดงวิธีเพิ่มแผนที่ลงในหน้าเว็บได้ 2 วิธี ได้แก่ การใช้องค์ประกอบ HTML ที่กำหนดเอง gmp-map และโดยการใช้องค์ประกอบ div

ภาพรวม

หากต้องการโหลดแผนที่ หน้าเว็บของคุณต้องทําสิ่งต่อไปนี้

  • โหลด Maps JavaScript API โดยใช้ Booter Loader ซึ่งเป็นที่ที่คีย์ API ของคุณมีการส่ง และคุณสามารถเพิ่มไปยังไฟล์ซอร์ส HTML หรือ JavaScript ได้
  • เพิ่มแผนที่ลงในหน้า HTML และเพิ่มรูปแบบ CSS ที่จำเป็น
  • โหลดไลบรารี maps และเริ่มต้นแผนที่

เพิ่มแผนที่โดยใช้องค์ประกอบ gmp-map

องค์ประกอบ gmp-map คือองค์ประกอบ HTML ที่กำหนดเองซึ่งสร้างขึ้นโดยใช้คอมโพเนนต์ของเว็บ หากต้องการเพิ่มแผนที่ลงในหน้าเว็บโดยใช้องค์ประกอบ gmp-map ให้ทำตามขั้นตอนต่อไปนี้

  1. ในหน้า HTML ให้เพิ่มองค์ประกอบ script ที่มี Bootstrap ที่กำหนดค่าด้วยคีย์ API ของคุณและตัวเลือกอื่นๆ ในตัวอย่าง Bootstrapped มีการละเว้นพารามิเตอร์ callback เพราะไม่จำเป็น

    <script async
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&loading=async&libraries=map,marker">
    
  2. ในหน้า HTML ให้เพิ่มองค์ประกอบ gmp-map ระบุพิกัดละติจูดและลองจิจูดสำหรับ center และค่าซูมสำหรับ zoom ในตัวอย่างนี้มีการระบุแอตทริบิวต์รูปแบบ height ด้วย

    <gmp-map
      center="37.4220656,-122.0840897"
      zoom="10"
      map-id="DEMO_MAP_ID"
      style="height: 400px"
    ></gmp-map>

กรอกโค้ดตัวอย่างแบบเต็ม

<html>
  <head>
    <title>Add a Map using HTML</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>
    <gmp-map
      center="37.4220656,-122.0840897"
      zoom="10"
      map-id="DEMO_MAP_ID"
      style="height: 400px"
    ></gmp-map>

    <!-- 
      The `defer` attribute causes the callback to execute after the full HTML
      document has been parsed. For non-blocking uses, avoiding race conditions,
      and consistent behavior across browsers, consider loading using Promises.
      See https://developers.google.com/maps/documentation/javascript/load-maps-js-api
      for more information.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=beta"
      defer
    ></script>
  </body>
</html>

เพิ่มแผนที่โดยใช้องค์ประกอบ div และ JavaScript

ระบบยังรองรับองค์ประกอบ div สำหรับการโหลดแผนที่ หากต้องการเพิ่มแผนที่ลงในหน้าเว็บโดยใช้องค์ประกอบ div ให้ทำตามขั้นตอนต่อไปนี้

  1. ในหน้า HTML ให้เพิ่มองค์ประกอบ script ที่มีตัวโหลด Bootstrap ที่กำหนดค่าด้วยคีย์ API ของคุณและตัวเลือกอื่นๆ หรือเพิ่มโค้ดตัวโหลด Boottrap ลงในไฟล์ TypeScript หรือ JavaScript โดยตรงโดยไม่ต้องใส่แท็ก script

    <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 ให้เพิ่มองค์ประกอบ div เพื่อให้มีแผนที่

    <div id="map"></div>
    
  3. ใน CSS ให้กำหนดความสูงของแผนที่เป็น 100%

    #map {
      height: 100%;
    }
    
  4. ในไฟล์ JavaScript ให้สร้างฟังก์ชันเพื่อโหลดไลบรารี maps และเริ่มต้นแผนที่ ระบุพิกัดละติจูดและลองจิจูดสำหรับ center และระดับการซูมที่จะใช้สำหรับ zoom

let map;

async function initMap() {
  const { Map } = await google.maps.importLibrary("maps");

  map = new Map(document.getElementById("map"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
}

initMap();

กรอกโค้ดตัวอย่างแบบเต็ม

TypeScript

let map: google.maps.Map;
async function initMap(): Promise<void> {
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
  map = new Map(document.getElementById("map") as HTMLElement, {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
}

initMap();

JavaScript

let map;

async function initMap() {
  const { Map } = await google.maps.importLibrary("maps");

  map = new Map(document.getElementById("map"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
}

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

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