设置边界多边形的样式

请选择平台: iOS JavaScript

概览

若要为边界多边形设置填充和描边样式,可以使用 FeatureStyleOptions 来定义样式属性,并将地图项图层中的 style 属性设置为包含样式设置逻辑的 google.maps.FeatureStyleFunction

以下示例地图演示了如何突出显示单个区域的边界多边形。

如要将样式应用于边界地图项,请将 style 属性设置为可以包含样式设置逻辑的 google.maps.FeatureStyleFunction。样式函数会针对受影响地图项图层中的每个地图项运行,并在您设置样式属性时应用。如需更新样式,您必须重新设置样式属性。

若要为地图项图层中的所有地图项设置统一样式,可以将 style 属性设置为 google.maps.FeatureStyleOptions。在这种情况下,因为不需要用到逻辑,所以您无需使用地图项样式函数。

针对地图项应用样式函数时,样式函数应始终返回一致的结果。例如,如果要随机为一组地图项着色,不应针对随机部分应用地图项样式函数,否则会导致意外结果。

由于此函数会针对图层中的每个地图项运行,因此优化至关重要。为避免影响渲染次数,请执行以下操作:

  • 仅启用所需的图层。
  • 如果不再使用某个图层,请将 style 设置为 null

若要为市行政区地图项图层中的多边形设置样式,请按以下步骤操作:

  1. 按照开始使用中的步骤创建新的地图 ID 和地图样式(如果您尚未执行此操作)。请务必启用 Locality(市行政区)地图项图层。
  2. 在地图初始化时获取对市行政区地图项图层的引用。

    featureLayer = map.getFeatureLayer("LOCALITY");
  3. 创建 google.maps.FeatureStyleFunction 类型的样式定义。

  4. 将地图项图层上的 style 属性设置为 FeatureStyleFunction。如要将样式仅应用于具有匹配地点 ID 的 google.maps.Feature,请参照以下示例来定义函数:

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

如果指定的地点 ID 未找到,或与所选的地图项类型不匹配,系统将不会应用样式。例如,如果尝试为与“纽约市”的地点 ID 匹配的 POSTAL_CODE 图层设置样式,系统将不会应用任何样式。

移除图层的样式

如需移除图层的样式,请将 style 设置为 null

featureLayer.style = null;

查找地点 ID 以定位地图项

若要获取区域的地点 ID,请执行以下操作:

覆盖范围因区域而异。如需了解详情,请参阅 Google 边界覆盖范围

您可以从许多来源获取地理位置名称,例如 USGS Board on Geographic Names(美国地名委员会)和 U.S. Gazetteer Files(美国地名档案)。

完整示例代码

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>

试用示例