Tạo kiểu một đa giác ranh giới

Chọn nền tảng: iOS JavaScript

Tổng quan

Để tạo kiểu cho màu nền và nét vẽ cho đa giác có ranh giới, hãy sử dụng FeatureStyleOptions để xác định các thuộc tính kiểu, đồng thời đặt thuộc tính style trên lớp đối tượng thành google.maps.FeatureStyleFunction chứa logic định kiểu.

Bản đồ mẫu sau đây minh hoạ việc làm nổi bật đa giác ranh giới cho một khu vực.

Áp dụng kiểu cho các đối tượng có ranh giới bằng cách đặt thuộc tính style thành google.maps.FeatureStyleFunction, có thể chứa logic định kiểu. Hàm kiểu được chạy trên mọi đối tượng trong lớp tính năng bị ảnh hưởng và được áp dụng tại thời điểm bạn đặt thuộc tính kiểu. Để cập nhật thuộc tính này, bạn phải thiết lập lại thuộc tính kiểu.

Để tạo kiểu thống nhất cho tất cả các đối tượng của một lớp đối tượng, hãy đặt thuộc tính style thành google.maps.FeatureStyleOptions. Trong trường hợp này, bạn không cần sử dụng hàm kiểu tính năng vì logic là không bắt buộc.

Hàm kiểu phải luôn trả về kết quả nhất quán khi được áp dụng thay vì các đối tượng. Ví dụ: nếu bạn muốn tô màu ngẫu nhiên một nhóm tính năng, phần ngẫu nhiên không nên diễn ra trong hàm kiểu tính năng, vì việc đó sẽ gây ra kết quả không mong muốn.

Vì hàm này chạy trên mọi tính năng trong một lớp, nên hoạt động tối ưu hoá là rất quan trọng. Cách tránh ảnh hưởng đến thời gian kết xuất:

  • Chỉ bật các lớp bạn cần.
  • Đặt style thành null khi một lớp không còn được sử dụng nữa.

Để tạo kiểu cho đa giác trong lớp đối tượng địa phương, hãy làm theo các bước sau:

  1. Nếu bạn chưa thực hiện, hãy làm theo các bước trong phần Bắt đầu để tạo mã bản đồ và kiểu bản đồ mới. Hãy nhớ bật lớp tính năng Thành phố.
  2. Lấy tham chiếu đến lớp đối tượng địa phương khi bản đồ khởi chạy.

    featureLayer = map.getFeatureLayer("LOCALITY");
  3. Tạo định nghĩa kiểu cho kiểu google.maps.FeatureStyleFunction.

  4. Đặt thuộc tính style trên lớp đối tượng thành FeatureStyleFunction. Ví dụ sau đây cho thấy việc xác định một hàm để chỉ áp dụng một kiểu cho google.maps.Feature có mã địa điểm trùng khớp:

    TypeScript

    // Define a style with purple fill and border.
    //@ts-ignore
    const featureStyleOptions: google.maps.FeatureStyleOptions = {
      strokeColor: '#810FCB',
      strokeOpacity: 1.0,
      strokeWeight: 3.0,
      fillColor: '#810FCB',
      fillOpacity: 0.5
    };
    
    // Apply the style to a single boundary.
    //@ts-ignore
    featureLayer.style = (options: { feature: { placeId: string; }; }) => {
      if (options.feature.placeId == 'ChIJ0zQtYiWsVHkRk8lRoB1RNPo') { // Hana, HI
        return featureStyleOptions;
      }
    };

    JavaScript

    // Define a style with purple fill and border.
    //@ts-ignore
    const featureStyleOptions = {
      strokeColor: "#810FCB",
      strokeOpacity: 1.0,
      strokeWeight: 3.0,
      fillColor: "#810FCB",
      fillOpacity: 0.5,
    };
    
    // Apply the style to a single boundary.
    //@ts-ignore
    featureLayer.style = (options) => {
      if (options.feature.placeId == "ChIJ0zQtYiWsVHkRk8lRoB1RNPo") {
        // Hana, HI
        return featureStyleOptions;
      }
    };

Nếu không tìm thấy mã địa điểm đã chỉ định hoặc không khớp với loại đối tượng đã chọn, thì kiểu sẽ không được áp dụng. Ví dụ: việc cố gắng tạo kiểu cho một lớp POSTAL_CODE khớp với mã địa điểm cho "Thành phố New York" sẽ dẫn đến việc không có kiểu nào được áp dụng.

Xoá kiểu khỏi lớp

Để xoá kiểu khỏi một lớp, hãy đặt style thành null:

featureLayer.style = null;

Tra cứu mã địa điểm để nhắm đến các đối tượng địa lý

Cách tải mã địa điểm cho các khu vực:

Phạm vi áp dụng thay đổi tuỳ theo khu vực. Xem bài viết Phạm vi bao phủ ranh giới của Google để biết chi tiết.

Tên địa lý có từ nhiều nguồn, chẳng hạn như Uỷ ban USGS về tên địa lýU.S. Gazetteer Files (Hội đồng quản trị của USGS về tên địa lý).

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

TypeScript

let map: google.maps.Map;
//@ts-ignore
let featureLayer;

async function initMap() {
  // Request needed libraries.
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;

  map = new Map(document.getElementById('map') as HTMLElement, {
    center: { lat: 20.773, lng: -156.01 }, // Hana, HI
    zoom: 12,
    // In the cloud console, configure this Map ID with a style that enables the
    // "Locality" feature layer.
    mapId: 'a3efe1c035bad51b', // <YOUR_MAP_ID_HERE>,
  });

  //@ts-ignore
  featureLayer = map.getFeatureLayer('LOCALITY');

  // Define a style with purple fill and border.
  //@ts-ignore
  const featureStyleOptions: google.maps.FeatureStyleOptions = {
    strokeColor: '#810FCB',
    strokeOpacity: 1.0,
    strokeWeight: 3.0,
    fillColor: '#810FCB',
    fillOpacity: 0.5
  };

  // Apply the style to a single boundary.
  //@ts-ignore
  featureLayer.style = (options: { feature: { placeId: string; }; }) => {
    if (options.feature.placeId == 'ChIJ0zQtYiWsVHkRk8lRoB1RNPo') { // Hana, HI
      return featureStyleOptions;
    }
  };

}

initMap();

JavaScript

let map;
//@ts-ignore
let featureLayer;

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

  map = new Map(document.getElementById("map"), {
    center: { lat: 20.773, lng: -156.01 }, // Hana, HI
    zoom: 12,
    // In the cloud console, configure this Map ID with a style that enables the
    // "Locality" feature layer.
    mapId: "a3efe1c035bad51b", // <YOUR_MAP_ID_HERE>,
  });
  //@ts-ignore
  featureLayer = map.getFeatureLayer("LOCALITY");

  // Define a style with purple fill and border.
  //@ts-ignore
  const featureStyleOptions = {
    strokeColor: "#810FCB",
    strokeOpacity: 1.0,
    strokeWeight: 3.0,
    fillColor: "#810FCB",
    fillOpacity: 0.5,
  };

  // Apply the style to a single boundary.
  //@ts-ignore
  featureLayer.style = (options) => {
    if (options.feature.placeId == "ChIJ0zQtYiWsVHkRk8lRoB1RNPo") {
      // Hana, HI
      return featureStyleOptions;
    }
  };
}

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>Boundaries Simple</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