Định kiểu cho đa giác ranh giới

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

Tổng quan

Để tạo kiểu cho phần tô và đường viền của 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 một lớp đối tượng thành google.maps.FeatureStyleFunction, chứa logic tạo kiểu.

Bản đồ ví dụ sau đây minh hoạ cách làm nổi bật đa giác ranh giới cho một khu vực duy nhất.

Áp dụng kiểu cho các đối tượng ranh giới bằng cách đặt thuộc tính style thành google.maps.FeatureStyleFunction. 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 đối tượng bị ảnh hưởng và được áp dụng vào 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 của một lớp đối tượng, hãy đặt thuộc tính style thành một google.maps.FeatureStyleOptions. Trong trường hợp này, bạn không cần sử dụng hàm kiểu đối tượng vì không cần logic.

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

Vì hàm này chạy trên mọi đối tượ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 hiển thị:

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

Để tạo kiểu cho một đ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. Nhớ bật lớp đối tượng Địa phương.
  2. Lấy thông tin tham chiếu đến lớp đối tượng địa phương khi bản đồ khởi tạo.

    featureLayer = map.getFeatureLayer("LOCALITY");
  3. Tạo một định nghĩa kiểu thuộc loại 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 cách 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 đã chỉ định hoặc mã này 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ụ: nếu bạn cố gắng tạo kiểu cho một lớp POSTAL_CODE khớp với mã địa điểm của "Thành phố New York", thì sẽ không có kiểu nào được áp dụng.

Xoá kiểu khỏi một 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

Cách lấy mã địa điểm cho các khu vực:

Phạm vi phủ sóng tuỳ theo khu vực. Hãy xem Phạm vi ranh giới của Google để biết thông tin chi tiết.

Tên địa lý có sẵn từ nhiều nguồn, chẳng hạn như Ban tên địa lý của USGSTệp danh bạ địa lý của Hoa Kỳ.

Mã ví dụ 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>

    <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>

Dùng thử mẫu