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 tô màu nền và nét vẽ cho đa giác ranh giới, hãy sử 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 chứa logic định kiểu.

Bản đồ mẫu sau minh hoạ việc đánh dấu đa giác ranh giới cho một một khu vực duy nhất.

Áp dụng kiểu cho các đối tượng địa lý 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. Phong cách hàm đượ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 tại thời điểm bạn đặt thuộc tính kiểu. Để cập nhật, bạn phải đặt kiểu lại thuộc tính này.

Để 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ì không yêu cầu logic.

Hàm kiểu phải luôn trả về kết quả nhất quán khi được áp dụng về 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 các đối tượng, phần ngẫu nhiên không nên diễn ra trong hàm kiểu tính năng, vì điều đó sẽ gây ra kết quả không mong muốn.

Do hàm này chạy trên mọi đối tượng trong một lớp, nên hoạt động tối ưu hoá 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. Hãy làm theo các bước trong phần Bắt đầu nếu bạn chưa thực hiện việc này. để tạo mã bản đồ mới và kiểu bản đồ. Hãy nhớ bật Thành phố lớp đối tượng.
  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 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 hoặc không tìm thấy mã địa điểm đã chỉ định phù hợp với loại đối tượng đã chọn, thì kiểu sẽ không được áp dụng. Ví dụ: cố gắng tạo kiểu cho một lớp POSTAL_CODE khớp với mã địa điểm cho "New York Thành phố" thì sẽ 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ó sẵn từ nhiều nguồn, chẳng hạn như Uỷ ban USGS về Tên địa lý, và Hoa Kỳ Tệp Gazetteer.

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

    <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