Để 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. Lớp này 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 style.
Để 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. Để 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 sử dụng.
Để 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:
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.
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");
Tạo một định nghĩa kiểu thuộc loại google.maps.FeatureStyleFunction.
Đặ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-ignoreconstfeatureStyleOptions:google.maps.FeatureStyleOptions={strokeColor:'#810FCB',strokeOpacity:1.0,strokeWeight:3.0,fillColor:'#810FCB',fillOpacity:0.5};// Apply the style to a single boundary.//@ts-ignorefeatureLayer.style=(options:{feature:{placeId:string;};})=>{if(options.feature.placeId=='ChIJ0zQtYiWsVHkRk8lRoB1RNPo'){// Hana, HIreturnfeatureStyleOptions;}};
// Define a style with purple fill and border.//@ts-ignoreconstfeatureStyleOptions={strokeColor:"#810FCB",strokeOpacity:1.0,strokeWeight:3.0,fillColor:"#810FCB",fillOpacity:0.5,};// Apply the style to a single boundary.//@ts-ignorefeatureLayer.style=(options)=>{if(options.feature.placeId=="ChIJ0zQtYiWsVHkRk8lRoB1RNPo"){// Hana, HIreturnfeatureStyleOptions;}};
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:
Sử dụng Places API và Geocoding để tìm kiếm các khu vực theo tên và nhận mã địa điểm cho các khu vực trong phạm vi được chỉ định.
Nhận dữ liệu từ sự kiện nhấp. Thao tác này trả về Đối tượng tương ứng với một khu vực được nhấp vào, cho phép truy cập vào mã địa điểm, tên hiển thị và danh mục loại đối tượng.
letmap:google.maps.Map;//@ts-ignoreletfeatureLayer;asyncfunctioninitMap(){// Request needed libraries.const{Map}=awaitgoogle.maps.importLibrary("maps")asgoogle.maps.MapsLibrary;map=newMap(document.getElementById('map')asHTMLElement,{center:{lat:20.773,lng:-156.01},// Hana, HIzoom: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-ignorefeatureLayer=map.getFeatureLayer('LOCALITY');// Define a style with purple fill and border.//@ts-ignoreconstfeatureStyleOptions:google.maps.FeatureStyleOptions={strokeColor:'#810FCB',strokeOpacity:1.0,strokeWeight:3.0,fillColor:'#810FCB',fillOpacity:0.5};// Apply the style to a single boundary.//@ts-ignorefeatureLayer.style=(options:{feature:{placeId:string;};})=>{if(options.feature.placeId=='ChIJ0zQtYiWsVHkRk8lRoB1RNPo'){// Hana, HIreturnfeatureStyleOptions;}};}initMap();
letmap;//@ts-ignoreletfeatureLayer;asyncfunctioninitMap(){// Request needed libraries.const{Map}=awaitgoogle.maps.importLibrary("maps");map=newMap(document.getElementById("map"),{center:{lat:20.773,lng:-156.01},// Hana, HIzoom: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-ignorefeatureLayer=map.getFeatureLayer("LOCALITY");// Define a style with purple fill and border.//@ts-ignoreconstfeatureStyleOptions={strokeColor:"#810FCB",strokeOpacity:1.0,strokeWeight:3.0,fillColor:"#810FCB",fillOpacity:0.5,};// Apply the style to a single boundary.//@ts-ignorefeatureLayer.style=(options)=>{if(options.feature.placeId=="ChIJ0zQtYiWsVHkRk8lRoB1RNPo"){// Hana, HIreturnfeatureStyleOptions;}};}initMap();
/* * 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;}
[null,null,["Cập nhật lần gần đây nhất: 2025-08-31 UTC."],[[["\u003cp\u003eStyle boundary polygons using \u003ccode\u003eFeatureStyleOptions\u003c/code\u003e and a \u003ccode\u003egoogle.maps.FeatureStyleFunction\u003c/code\u003e to define fill and stroke attributes.\u003c/p\u003e\n"],["\u003cp\u003eApply styles to specific features within a layer by using a feature style function that contains conditional logic based on properties like \u003ccode\u003eplaceId\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eRemove styling from a layer by setting the \u003ccode\u003estyle\u003c/code\u003e property to \u003ccode\u003enull\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eOptimize rendering performance by enabling only necessary layers and setting \u003ccode\u003estyle\u003c/code\u003e to \u003ccode\u003enull\u003c/code\u003e for unused layers.\u003c/p\u003e\n"],["\u003cp\u003eUse Places APIs, Geocoding, or click events to retrieve place IDs for targeting specific features within boundary layers.\u003c/p\u003e\n"]]],["To style boundary polygons, define `FeatureStyleOptions` for attributes and set the `style` property on a feature layer to a `FeatureStyleFunction`. This function styles each feature in the layer; to update, reset the style property. For uniform styling, directly set `style` to `FeatureStyleOptions`. Optimize by enabling only needed layers and setting `style` to `null` when not in use. Use Places APIs or click events to get place IDs for styling specific regions, like a locality. Remove styling by setting `style` to `null`.\n"],null,["Select platform: [Android](/maps/documentation/android-sdk/dds-boundaries/style-polygon \"View this page for the Android platform docs.\") [iOS](/maps/documentation/ios-sdk/dds-boundaries/style-polygon \"View this page for the iOS platform docs.\") [JavaScript](/maps/documentation/javascript/dds-boundaries/style-polygon \"View this page for the JavaScript platform docs.\")\n\n\u003cbr /\u003e\n\nOverview\n\nTo style the fill and stroke for a boundary polygon, use `FeatureStyleOptions`\nto define style attributes, and set the `style` property on a feature layer to a\n`google.maps.FeatureStyleFunction`, which contains styling logic.\n\nThe following example map demonstrates highlighting the boundary polygon for a\nsingle region.\n\n\nApply style to boundary features by setting the `style` property to a\n`google.maps.FeatureStyleFunction`, which can contain styling logic. The style\nfunction is run over every feature in the affected feature layer, and is applied\nat the time you set the style property. To update it, you must set the style\nproperty again.\n\nTo uniformly style all features for a feature layer, set the `style` property to\na `google.maps.FeatureStyleOptions`. In this case, you don't need to use a\nfeature style function, since logic is not required.\n\nThe style function should always return consistent results when it is applied\nover features. For example, if you wanted to randomly color a set of features,\nthe random part should not take place in the feature style function, as that\nwould cause unintended results.\n\nBecause this function runs over every feature in a layer, optimization is\nimportant. To avoid impacting rendering times:\n\n- Enable only the layers you need.\n- Set `style` to `null` when a layer is no longer in use.\n\nTo style a polygon in the locality feature layer, take the following steps:\n\n1. If you haven't already done so, follow the steps in [Get Started](/maps/documentation/javascript/dds-boundaries/start) to create a new map ID and map style. Be sure to enable the **Locality** feature layer.\n2. Get a reference to the locality feature layer when the map initializes.\n\n ```javascript\n featureLayer = map.getFeatureLayer(\"LOCALITY\");\n ```\n3. Create a style definition of type `google.maps.FeatureStyleFunction`.\n\n4. Set the `style` property on the feature layer to the `FeatureStyleFunction`.\n The following example shows defining a function to apply a style only to the\n `google.maps.Feature` with a matching place ID:\n\n\n TypeScript \n\n ```typescript\n // Define a style with purple fill and border.\n //@ts-ignore\n const featureStyleOptions: google.maps.FeatureStyleOptions = {\n strokeColor: '#810FCB',\n strokeOpacity: 1.0,\n strokeWeight: 3.0,\n fillColor: '#810FCB',\n fillOpacity: 0.5\n };\n\n // Apply the style to a single boundary.\n //@ts-ignore\n featureLayer.style = (options: { feature: { placeId: string; }; }) =\u003e {\n if (options.feature.placeId == 'ChIJ0zQtYiWsVHkRk8lRoB1RNPo') { // Hana, HI\n return featureStyleOptions;\n }\n };https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/samples/boundaries-simple/index.ts#L32-L48\n ```\n | **Note:** Read the [guide](/maps/documentation/javascript/using-typescript) on using TypeScript and Google Maps.\n\n JavaScript \n\n ```javascript\n // Define a style with purple fill and border.\n //@ts-ignore\n const featureStyleOptions = {\n strokeColor: \"#810FCB\",\n strokeOpacity: 1.0,\n strokeWeight: 3.0,\n fillColor: \"#810FCB\",\n fillOpacity: 0.5,\n };\n\n // Apply the style to a single boundary.\n //@ts-ignore\n featureLayer.style = (options) =\u003e {\n if (options.feature.placeId == \"ChIJ0zQtYiWsVHkRk8lRoB1RNPo\") {\n // Hana, HI\n return featureStyleOptions;\n }\n };https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/boundaries-simple/docs/index.js#L29-L46\n ```\n\n \u003cbr /\u003e\n\nIf the specified place ID is not found, or does not\nmatch the selected feature type, the style is not applied. For example,\nattempting to style a `POSTAL_CODE` layer matching the place ID for \"New York\nCity\" would result in no style being applied.\n\nRemove styling from a layer\n\nTo remove styling from a layer, set the `style` to `null`: \n\n```javascript\nfeatureLayer.style = null;\n```\n\nLook up place IDs to target features\n\nTo get place IDs for regions:\n\n- [Use Places APIs and Geocoding](/maps/documentation/javascript/dds-boundaries/dds-use-maps-places-apis#text-search) to search for regions by name, and get place IDs for regions within specified bounds.\n- [Get data from click events](/maps/documentation/javascript/dds-boundaries/handle-events). This returns the Feature corresponding to a region clicked, which provides access to its place ID, display name, and feature type category.\n\nCoverage varies by region. See [Google boundaries coverage](/maps/documentation/javascript/dds-boundaries/coverage) for details.\n\nGeographic names are available from many sources, such as the\n[USGS Board on Geographic Names](https://edits.nationalmap.gov/apps/gaz-domestic/public/search/names),\nand the [U.S. Gazetteer Files](https://www.census.gov/geographies/reference-files/time-series/geo/gazetteer-files.html).\n\nComplete example code\n\n\nTypeScript \n\n```typescript\nlet map: google.maps.Map;\n//@ts-ignore\nlet featureLayer;\n\nasync function initMap() {\n // Request needed libraries.\n const { Map } = await google.maps.importLibrary(\"maps\") as google.maps.MapsLibrary;\n\n map = new Map(document.getElementById('map') as HTMLElement, {\n center: { lat: 20.773, lng: -156.01 }, // Hana, HI\n zoom: 12,\n // In the cloud console, configure this Map ID with a style that enables the\n // \"Locality\" feature layer.\n mapId: 'a3efe1c035bad51b', // \u003cYOUR_MAP_ID_HERE\u003e,\n });\n\n //@ts-ignore\n featureLayer = map.getFeatureLayer('LOCALITY');\n\n // Define a style with purple fill and border.\n //@ts-ignore\n const featureStyleOptions: google.maps.FeatureStyleOptions = {\n strokeColor: '#810FCB',\n strokeOpacity: 1.0,\n strokeWeight: 3.0,\n fillColor: '#810FCB',\n fillOpacity: 0.5\n };\n\n // Apply the style to a single boundary.\n //@ts-ignore\n featureLayer.style = (options: { feature: { placeId: string; }; }) =\u003e {\n if (options.feature.placeId == 'ChIJ0zQtYiWsVHkRk8lRoB1RNPo') { // Hana, HI\n return featureStyleOptions;\n }\n };\n\n}\n\ninitMap();https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/samples/boundaries-simple/index.ts#L12-L53\n```\n| **Note:** Read the [guide](/maps/documentation/javascript/using-typescript) on using TypeScript and Google Maps.\n\nJavaScript \n\n```javascript\nlet map;\n//@ts-ignore\nlet featureLayer;\n\nasync function initMap() {\n // Request needed libraries.\n const { Map } = await google.maps.importLibrary(\"maps\");\n\n map = new Map(document.getElementById(\"map\"), {\n center: { lat: 20.773, lng: -156.01 }, // Hana, HI\n zoom: 12,\n // In the cloud console, configure this Map ID with a style that enables the\n // \"Locality\" feature layer.\n mapId: \"a3efe1c035bad51b\", // \u003cYOUR_MAP_ID_HERE\u003e,\n });\n //@ts-ignore\n featureLayer = map.getFeatureLayer(\"LOCALITY\");\n\n // Define a style with purple fill and border.\n //@ts-ignore\n const featureStyleOptions = {\n strokeColor: \"#810FCB\",\n strokeOpacity: 1.0,\n strokeWeight: 3.0,\n fillColor: \"#810FCB\",\n fillOpacity: 0.5,\n };\n\n // Apply the style to a single boundary.\n //@ts-ignore\n featureLayer.style = (options) =\u003e {\n if (options.feature.placeId == \"ChIJ0zQtYiWsVHkRk8lRoB1RNPo\") {\n // Hana, HI\n return featureStyleOptions;\n }\n };\n}\n\ninitMap();https://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/boundaries-simple/docs/index.js#L10-L50\n```\n| **Note:** The JavaScript is compiled from the TypeScript snippet.\n\nCSS \n\n```css\n/* \n * Always set the map height explicitly to define the size of the div element\n * that contains the map. \n */\n#map {\n height: 100%;\n}\n\n/* \n * Optional: Makes the sample page fill the window. \n */\nhtml,\nbody {\n height: 100%;\n margin: 0;\n padding: 0;\n}\nhttps://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/boundaries-simple/docs/style.css#L7-L24\n```\n\nHTML \n\n```html\n\u003chtml\u003e\n \u003chead\u003e\n \u003ctitle\u003eBoundaries Simple\u003c/title\u003e\n\n \u003clink rel=\"stylesheet\" type=\"text/css\" href=\"./style.css\" /\u003e\n \u003cscript type=\"module\" src=\"./index.js\"\u003e\u003c/script\u003e\n \u003c/head\u003e\n \u003cbody\u003e\n \u003cdiv id=\"map\"\u003e\u003c/div\u003e\n\n \u003c!-- prettier-ignore --\u003e\n \u003cscript\u003e(g=\u003e{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=()=\u003eh||(h=new Promise(async(f,n)=\u003e{await (a=m.createElement(\"script\"));e.set(\"libraries\",[...r]+\"\");for(k in g)e.set(k.replace(/[A-Z]/g,t=\u003e\"_\"+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=()=\u003eh=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)=\u003er.add(f)&&u().then(()=\u003ed[l](f,...n))})\n ({key: \"AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg\", v: \"weekly\"});\u003c/script\u003e\n \u003c/body\u003e\n\u003c/html\u003ehttps://github.com/googlemaps/js-samples/blob/2683f7366fb27829401945d2a7e27d77ed2df8e5/dist/samples/boundaries-simple/docs/index.html#L8-L22\n```\n\nTry Sample \n[JSFiddle.net](https://jsfiddle.net/gh/get/library/pure/googlemaps/js-samples/tree/master/dist/samples/boundaries-simple/jsfiddle) [Google Cloud Shell](https://ssh.cloud.google.com/cloudshell/editor?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2Fgooglemaps%2Fjs-samples&cloudshell_git_branch=sample-boundaries-simple&cloudshell_tutorial=cloud_shell_instructions.md&cloudshell_workspace=.)\n\n\u003cbr /\u003e"]]