경계 다각형 스타일 지정

플랫폼 선택: iOS JavaScript

개요

경계 다각형의 채우기 및 획의 스타일을 지정하려면 FeatureStyleOptions를 사용하여 스타일 속성을 정의하고, 지형지물 레이어의 style 속성을 스타일 지정 로직을 포함하는 google.maps.FeatureStyleFunction으로 설정하세요.

다음 지도 예는 단일 지역의 경계 다각형을 강조 표시하는 방법을 보여줍니다.

style 속성을 스타일 지정 로직이 포함될 수 있는 google.maps.FeatureStyleFunction으로 설정하여 경계 지형지물에 스타일을 적용합니다. 영향을 받는 지형지물 레이어의 모든 지형지물에 대해 스타일 함수가 실행되고, 스타일 속성을 설정할 때 적용됩니다. 업데이트하려면 스타일 속성을 다시 설정해야 합니다.

지형지물 레이어에 있는 모든 지형지물의 스타일을 균일하게 지정하려면 style 속성을 google.maps.FeatureStyleOptions로 설정하세요. 이 경우 로직이 필요하지 않으므로 지형지물 스타일 함수를 사용할 필요가 없습니다.

스타일 함수는 지형지물에 적용될 때 항상 일관성 있는 결과를 반환해야 합니다. 예를 들어 여러 지형지물의 색상을 무작위로 지정할 경우, 지형지물 스타일 함수에 무작위 부분이 있으면 의도하지 않은 결과가 발생할 수 있으므로 무작위 부분이 없어야 합니다.

이 함수는 레이어의 모든 지형지물에 대해 실행되므로 최적화가 중요합니다. 렌더링 시간에 영향을 주지 않으려면 다음 안내를 따르세요.

  • 필요한 레이어만 사용 설정합니다.
  • 레이어가 더 이상 사용되지 않으면 stylenull로 설정합니다.

지역 지형지물 레이어에서 다각형에 스타일을 지정하려면 다음 단계를 따르세요.

  1. 새 지도 ID와 지도 스타일을 아직 만들지 않았으면 시작하기의 단계에 따라 만드세요. 지역 지형지물 레이어를 사용 설정해야 합니다.
  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 레이어의 스타일을 지정하려고 하면 스타일이 적용되지 않습니다.

레이어에서 스타일 지정 삭제

레이어에서 스타일 지정을 삭제하려면 stylenull로 설정하세요.

featureLayer.style = null;

장소 ID를 조회하여 지형지물 타겟팅

지역의 장소 ID를 가져오려면 다음 단계를 따르세요.

적용 범위는 지역에 따라 다릅니다. 자세한 내용은 Google 경계 적용 범위를 참고하세요.

지명은 USGS 지명위원회(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. 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>

샘플 사용해 보기