Bạn có thể thêm bản đồ Google vào một trang web bằng mã HTML, CSS và JavaScript. Trang này cho biết cách thêm bản đồ vào một trang web, sau đó truy cập vào phiên bản bản đồ theo phương thức lập trình.
- Thêm bản đồ bằng cách sử dụng phần tử
gmp-map - Thêm bản đồ bằng phần tử
divvà JavaScript - Đặt và nhận các thuộc tính trên thực thể bản đồ
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 của Maps bằng trình tải khởi động. Đây là nơi khoá API của bạn được truyền. Bạn có thể thêm mã này vào tệp nguồn HTML hoặc JavaScript.
- Thêm bản đồ vào trang HTML và thêm các kiểu CSS cần thiết.
- Tải thư viện
mapsvà khởi chạy bản đồ.
Thêm bản đồ bằng phần tử gmp-map
Phần tử gmp-map là cách tốt nhất để thêm bản đồ Google vào một trang web.
Đây 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 trang web bằng phần tử gmp-map, hãy làm theo các bước sau.
Thêm một phần tử
scriptchứa chương trình khởi động vào một trang HTML hoặc thêm phần tử đó vào một tệp nguồn JavaScript hoặc TypeScript mà không có phần tửscript. Định cấu hình quy trình khởi động bằng khoá API và mọi lựa chọn khác. Bạn có thể chọn nhập thư viện động hoặc tải tập lệnh trực tiếp. Ví dụ này minh hoạ cách thêm chương trình khởi động tải tập lệnh động vào một trang HTML:<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>
Trên trang HTML, hãy thêm một phần tử
gmp-map. Chỉ định toạ độ vĩ độ và kinh độ chocenter(bắt buộc), giá trị thu phóng chozoom(bắt buộc) vàmap-idnếu cần (bắt buộc đối với một số tính năng như Advanced Markers).
<gmp-map center="-34.397,150.644" zoom="8" mapId="DEMO_MAP_ID"> </gmp-map>
Mã ví dụ hoàn chỉnh
TypeScript
async function initMap(): Promise<void> { // Import the needed libraries. await google.maps.importLibrary('maps'); // Create the map. const mapElement = document.querySelector('gmp-map') as google.maps.MapElement; // Access the underlying map object. const innerMap = mapElement.innerMap; } initMap();
JavaScript
async function initMap() { // Import the needed libraries. await google.maps.importLibrary('maps'); // Create the map. const mapElement = document.querySelector('gmp-map'); // Access the underlying map object. const innerMap = mapElement.innerMap; } initMap();
CSS
/* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
HTML
<html>
<head>
<title>Simple Map</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
<!-- 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: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly" });</script>
</head>
<body>
<gmp-map center="-34.397,150.644" zoom="8" mapId="DEMO_MAP_ID">
</gmp-map>
</body>
</html>Thử dùng mẫu
Thêm bản đồ bằng phần tử div và JavaScript
Để thêm bản đồ vào trang web bằng phần tử div, hãy làm theo các bước sau.
Thêm một phần tử
scriptchứa chương trình khởi động vào một trang HTML hoặc thêm phần tử đó vào một tệp nguồn JavaScript hoặc TypeScript mà không có phần tửscript. Định cấu hình quy trình khởi động bằng khoá API và mọi lựa chọn khác. Bạn có thể chọn nhập thư viện động hoặc tải tập lệnh trực tiếp. Ví dụ này cho thấy cách thêm bootstrap động vào một trang HTML:<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>
Trên trang HTML, hãy thêm một phần tử
divđể chứa bản đồ.<div id="map"></div>
Trong CSS, hãy đặt chiều cao bản đồ thành 100%. Bạn phải có thuộc tính CSS
heightthì bản đồ mới xuất hiện.#map { height: 100%; }
Trong tệp JS hoặc TS, hãy tạo một hàm để tải thư viện
mapsvà khởi động bản đồ. Chỉ định toạ độ vĩ độ và kinh độ chocenter, cũng như mức thu phóng cần dùng chozoom. Nếu cần, hãy thêm mã bản đồ bằng cách sử dụng thuộc tínhmapId. Vì bản đồ sẽ mặc định là bản đồ raster, hãy yêu cầu bản đồ vectơ bằng cách chỉ định lựa chọn bản đồ "VECTOR"; nên dùng loại bản đồ vectơ để mang lại trải nghiệm tốt nhất cho người dùng, vì loại bản đồ này cải thiện độ trung thực về hình ảnh cũng như khả năng kiểm soát độ nghiêng và hướng trên bản đồ.TypeScript
let map: google.maps.Map; async function initMap(): Promise<void> { // Import the needed libraries const { Map, RenderingType } = (await google.maps.importLibrary( 'maps' )) as google.maps.MapsLibrary; // Create a new map from the div with id="map". map = new Map(document.getElementById('map') as HTMLElement, { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: "VECTOR", }); } initMap();
JavaScript
let map; async function initMap() { // Import the needed libraries const { Map, RenderingType } = (await google.maps.importLibrary('maps')); // Create a new map from the div with id="map". map = new Map(document.getElementById('map'), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: "VECTOR", }); } initMap();
Xem mã nguồn ví dụ hoàn chỉnh
TypeScript
let map: google.maps.Map; async function initMap(): Promise<void> { // Import the needed libraries const { Map, RenderingType } = (await google.maps.importLibrary( 'maps' )) as google.maps.MapsLibrary; // Create a new map from the div with id="map". map = new Map(document.getElementById('map') as HTMLElement, { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: "VECTOR", }); } initMap();
JavaScript
let map; async function initMap() { // Import the needed libraries const { Map, RenderingType } = (await google.maps.importLibrary('maps')); // Create a new map from the div with id="map". map = new Map(document.getElementById('map'), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: "VECTOR", }); } 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>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
<!-- 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: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly" });</script>
</body>
</head>
<body>
<div id="map"></div>
</body>
</html>Thử dùng mẫu
Đặt và nhận các thuộc tính trên thực thể bản đồ
Để tương tác với thực thể bản đồ, hãy chọn phần tử chứa. Đoạn mã để thực hiện việc này sẽ khác nhau, tuỳ thuộc vào việc bạn đã sử dụng phần tử gmp-map hay phần tử div.
Lấy một thực thể bản đồ từ phần tử gmp-map
Để lấy thực thể bản đồ khi dùng phần tử gmp-map, hãy dùng document.querySelector để truy xuất một thực thể mapElement, như minh hoạ ở đây.
const mapElement = document.querySelector('gmp-map') as google.maps.MapElement;
Sau đó, hãy đặt các thuộc tính trên thực thể mapElement:
mapElement.zoom = 8;
Lớp MapElement sử dụng lớp Map nội bộ; truy cập vào lớp Map bằng cách sử dụng thuộc tính MapElement.innerMap, như minh hoạ ở đây:
mapElement.innerMap.setOptions({
mapTypeControl: false,
});
Lấy một thực thể bản đồ từ phần tử div
Khi sử dụng phần tử div, hãy lấy thực thể bản đồ và đặt các lựa chọn tại thời điểm khởi tạo:
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
mapTypeControl: false,
});
Sau khi khởi tạo, hãy đặt các lựa chọn trên thực thể map như minh hoạ ở đây:
map.setOptions({
zoom: 8,
});