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 một đa giác ranh giới, hãy dùng FeatureStyleOptions để xác định các thuộc tính kiểu và đặt thuộc tính style trên lớp đối tượng thành google.maps.FeatureStyleFunction, trong đó 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 đơn lẻ.

Áp dụng kiểu cho các tính năng ranh giới bằng cách đặt thuộc tính style thành google.maps.FeatureStyleFunction, trong đó có thể chứa logic định kiểu. Hàm định kiểu chạy trên mọi tính năng trong lớp đối tượ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, bạn phải đặt lại thuộc tính kiểu.

Để tạo kiểu đồng nhất cho tất cả các đối tượng cho 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 định kiểu phải luôn trả về kết quả nhất quán khi được áp dụng trên các tính năng. Ví dụ: nếu bạn muốn tô màu ngẫu nhiên một tập hợp tính năng, thì phần ngẫu nhiên sẽ không diễn ra trong hàm kiểu tính năng vì điều đó sẽ gây ra kết quả ngoài ý muốn.

Vì hàm này chạy trên mọi tính năng trong một lớp nên việc 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.

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

  1. Nếu bạn chưa làm như vậy, 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 đảm bảo bật lớp tính năng Thành phố.
  2. Lấy tham chiếu đến lớp đối tượng của địa phương khi bản đồ khởi chạy.

    featureLayer = map.getFeatureLayer("LOCALITY");
  3. Tạo định nghĩa kiểu thuộc 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 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 được 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 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 áp dụng kiểu nào.

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

Để nhận mã địa điểm cho các khu vực, hãy làm như sau:

Phạm vi bao phủ thay đổi tuỳ theo khu vực. Xem phạm vi bao phủ của Google để biết chi tiết.

Tên địa lý có sẵn từ nhiều nguồn, chẳng hạn như Uỷ ban USGS về tên địa lýU.S. Gazetteer Files (Tệp Công báo của Hoa Kỳ).

Hoàn tất đoạn mã ví dụ

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 },
    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ử mẫu