Thêm Google Maps vào trang web

Bạn có thể thêm bản đồ Google vào trang web bằng cách sử dụng mã HTML, CSS và JavaScript. Trang này cho biết cách thêm bản đồ vào trang web theo hai cách: bằng cách sử dụng phần tử HTML tuỳ chỉnh gmp-map và phần tử div.

Tổng quan

Để tải bản đồ, trang web của bạn phải thực hiện những việc sau:

  • Tải API JavaScript cho Maps bằng trình tải khởi động. Đây là nơi khoá API được chuyển và bạn có thể thêm vào tệp nguồn HTML hoặc JavaScript.
  • Thêm bản đồ vào trang HTML và thêm kiểu CSS cần thiết.
  • Tải thư viện maps và khởi chạy bản đồ.

Thêm bản đồ bằng phần tử gmp-map

Phần tử gmp-map là một phần tử HTML tuỳ chỉnh được tạo bằng các thành phần web. Để thêm bản đồ vào một trang web bằng phần tử gmp-map, hãy làm theo các bước sau.

  1. Trên trang HTML, hãy thêm phần tử script chứa quy trình khởi động đã định cấu hình bằng khoá API và mọi tuỳ chọn khác. Trong ví dụ sau đây về quy trình khởi động, tham số callback đã bị bỏ qua vì không cần thiết.

    <script
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&loading=async&libraries=maps&v=beta" defer>
    </script>
    

  2. Trên trang HTML, hãy thêm phần tử gmp-map. Chỉ định vĩ độ và kinh độ cho center cùng giá trị thu phóng cho zoom. Trong ví dụ này, thuộc tính kiểu height cũng được chỉ định.

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

Đoạn mã mẫu hoàn chỉnh

<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 script 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&libraries=maps&v=beta"
      defer
    ></script>
  </body>
</html>

Thêm bản đồ bằng phần tử div và JavaScript

Phần tử div vẫn được hỗ trợ để tải bản đồ. Để thêm bản đồ vào trang web bằng phần tử div, hãy làm theo các bước sau.

  1. Trên trang HTML, hãy thêm phần tử script chứa trình tải tự động khởi động được định cấu hình bằng khoá API và mọi tuỳ chọn khác. Ngoài ra, hãy thêm trực tiếp mã trình tải khởi động vào tệp TypeScript hoặc JavaScript, trừ các thẻ 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. Trên trang HTML, hãy thêm phần tử div để chứa bản đồ.

    <div id="map"></div>
    
  3. Trong CSS, hãy đặt chiều cao của bản đồ thành 100%.

    #map {
      height: 100%;
    }
    
  4. Trong tệp JavaScript, hãy tạo một hàm để tải thư viện maps và khởi động bản đồ. Chỉ định vĩ độ và kinh độ cho center cũng như mức thu phóng để sử dụng cho 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();

Đoạn mã mẫu hoàn chỉnh

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>

Thử dùng mẫu