Nhúng các ô bản đồ nhiệt vào một trang web

Hướng dẫn này sẽ chỉ cho bạn cách hiển thị ô điểm bản đồ nhiệt của API Phấn hoa trong một trang web bằng cách sử dụng HTML, CSS và JavaScript. Dưới đây là bản đồ bạn sẽ tạo bằng cách sử dụng hướng dẫn này:

Bắt đầu

Dưới đây là những bước mà chúng ta sẽ đề cập đến để tạo một trang web bằng các ô bản đồ nhiệt của APIPhấn hoa:

  1. Tải khoá API
  2. Tạo trang web bằng HTML
  3. Định cấu hình kiểu bằng CSS
  4. Dữ liệu trong API Tìm nạp phấn hoa bằng JavaScript

Để tạo trang web, bạn cần có một trình duyệt web hỗ trợ JavaScript. Hãy xem phần Hỗ trợ trình duyệt để biết danh sách đầy đủ các trình duyệt được hỗ trợ.

Bước 1: Lấy khoá API

Phần này giải thích cách xác thực ứng dụng với API Thăm dò bằng cách sử dụng khoá API của riêng bạn.

Hãy làm theo các bước sau để nhận khoá API:

  1. Truy cập vào Bảng điều khiển Google Cloud.

  2. Tạo hoặc chọn một dự án.

  3. Nhấp vào Tiếp tục để bật API và mọi dịch vụ liên quan.

  4. Trên trang Thông tin xác thực, hãy lấy khoá API và đặt các hạn chế đối với khoá API.

  5. Để ngăn chặn hành vi đánh cắp hạn mức và bảo mật khoá API, hãy xem phần Sử dụng khoá API.

  6. Bật tính năng thanh toán. Hãy xem bài viết Mức sử dụng và thanh toán để biết thêm thông tin.

Giờ thì bạn đã có thể sử dụng khoá API.

Bước 2: Tạo trang web bằng HTML

Dưới đây là mã cho trang web HTML cơ bản:

<html>
  <head>
    <title>Pollen heatmaps around the world</title>
    <style>
      /* Configure CSS here. */
    </style>
  </head>
  <body>
    <!-- Add JavaScript functions and button containers here. -->
  </body>
</html>

Để tải bản đồ trên trang web của bạn, hãy thêm thẻ script chứa trình tải khởi động cho APIPhấn hoa và bao gồm khoá API:

  <script
    src="https://maps.googleapis.com/maps/api/js?callback=initMap&v=weekly&key=YOUR_API_KEY&language=en" defer>
  </script>

Bước 3: Định cấu hình kiểu bằng CSS

Tiếp theo, sử dụng CSS để định cấu hình giao diện của bản đồ trên trang web của bạn.

  <style>
    /*
    * Always set the map height explicitly to define the size of the div element
    * that contains the map.
    */
    #map {
      height: 600px;
    }
    #container{
      position:absolute;
      display:inline-block;
      z-index:10;
      margin-left:50%;
      transform:translateX(-50%);
      bottom:40px;
    }
  </style>

Bạn cũng có thể sử dụng CSS để định cấu hình các nút hiển thị các dữ liệu khác nhau của API Cuộc thăm dò ý kiến (TREE, GRASS hoặc WEED):

  <style>
    button{
    width:100px;
    height:34px; 
    /*top:50px;*/
    display:inline-block;
    position:relative;
    text-align:center;
    border:none;
    box-shadow: 0px 0px 4px 0px rgba(0,0,0,0.29);
    color:#FFF;
    font-weight:400;
    border-radius:4px;
    margin-left:4px;
    font-family:"Google Sans","Roboto","Arial";
    line-height:1em;
  }
    #tree{background:#009c1a}
    #grass{background:#22b600}
    #weed{background:#26cc00}
    button:active{background:#999999 !important;}
  </style>

Sử dụng phần tử <div> để tạo vùng chứa cho các nút và bản đồ:

  <div id="container">
        <button type="button" id="tree">TREE</button>
        <button type="button" id="grass">GRASS</button>
        <button type="button" id="weed">WEED</button>
  </div>
  <div id="map"></div>

Bước 4: Tìm nạp dữ liệu API Phấn hoa bằng JavaScript

Sử dụng JavaScript để tìm nạp dữ liệu API Phấn hoa và hiển thị dữ liệu đó trên một bản đồ tương tác:

  function getNormalizedCoord(coord, zoom) {
    const y = coord.y;
    let x = coord.x;
    // Define the tile range in one direction. The range is dependent on zoom level:
    // 0 = 1 tile, 1 = 2 tiles, 2 = 4 tiles, 3 = 8 tiles, etc.
    const tileRange = 1 << zoom;

    // don't repeat across y-axis (vertically)
    if (y < 0 || y >= tileRange) {
      return null;
    }

    // repeat across x-axis
    if (x < 0 || x >= tileRange) {
      x = ((x % tileRange) + tileRange) % tileRange;
    }
    return { x: x, y: y };
  }

  let pollen = "TREE_UPI"
  class PollenMapType {
    tileSize;
    alt = null;
    maxZoom = 16;
    minZoom = 3;
    name = null;
    projection = null;
    radius = 6378137;
    constructor(tileSize) {
      this.tileSize = tileSize;
    }

    getTile(coord, zoom, ownerDocument) {
      const img = ownerDocument.createElement("img");
      const mapType = pollen;
      const normalizedCoord = getNormalizedCoord(coord, zoom);

      const x = coord.x;
      const y = coord.y;
      const key = "YOUR_API_KEY";
      img.style.opacity = 0.8;
      img.src = `https://pollen.googleapis.com/v1/mapTypes/${mapType}/heatmapTiles/${zoom}/${x}/${y}?key=${key}`;
      return img;
    }
    releaseTile(tile) {}
  }

Cuối cùng, hãy sử dụng JavaScript để khởi chạy bản đồ và hiển thị dữ liệu API Phấn hoa dựa trên các nút đã chọn:

  function initMap() {
    const myLatLng = { lat: 40.3769, lng: -80.5417 };
    const map = new google.maps.Map(document.getElementById("map"), {
      mapId: "ffcdd6091fa9fb03",
      zoom: 0,
      center: myLatLng,
      maxZoom: 16,
      minZoom: 3,
      restriction: {
        latLngBounds: {north: 80, south: -80, west: -180, east: 180},
        strictBounds: true,
      },
      streetViewControl: false,
    });
    const pollenMapType = new PollenMapType(new google.maps.Size(256, 256));
    map.overlayMapTypes.insertAt(0, pollenMapType);
    
    document.querySelector("#tree").addEventListener("click", function(){
        pollen ="TREE_UPI"
        map.overlayMapTypes.removeAt(0);
        const pollenMapType = new PollenMapType(new google.maps.Size(256, 256));
        map.overlayMapTypes.insertAt(0, pollenMapType);
    })
    document.querySelector("#grass").addEventListener("click", function(){
        pollen ="GRASS_UPI"
        map.overlayMapTypes.removeAt(0);
        const pollenMapType = new PollenMapType(new google.maps.Size(256, 256));
        map.overlayMapTypes.insertAt(0, pollenMapType);
    })
      document.querySelector("#weed").addEventListener("click", function(){
        pollen ="WEED_UPI"
        map.overlayMapTypes.removeAt(0);
        const pollenMapType = new PollenMapType(new google.maps.Size(256, 256));
        map.overlayMapTypes.insertAt(0, pollenMapType);
    })
  }