Se quiser estilizar o preenchimento e o traço de um polígono de limites, use FeatureStyleOptions para configurar os atributos de estilo e defina a propriedade style em uma camada de elementos como google.maps.FeatureStyleFunction, que contém a lógica de estilo.
O mapa de exemplo a seguir mostra como destacar o polígono de limites de uma única região.
Para aplicar o estilo aos elementos de limites, defina a propriedade style como google.maps.FeatureStyleFunction, que pode conter a lógica de estilo. A função é executada em todos os elementos na camada afetada e é aplicada ao definir a propriedade de estilo. Em caso de atualização, é necessário redefinir a propriedade.
Para aplicar um estilo de maneira uniforme à camada de elementos, defina a propriedade style como google.maps.FeatureStyleOptions. Nesse caso, você não precisa usar uma função de estilo dos elementos, já que a lógica não é necessária.
A função precisa sempre retornar resultados consistentes quando é aplicada aos elementos. Por exemplo, para colorir aleatoriamente um conjunto de elementos, a parte aleatória não pode ocorrer na função de estilo de elementos porque isso gera resultados indesejados.
Como essa função é executada em todos os elementos de uma camada, a otimização é importante. Para não afetar os tempos de renderização:
Ative somente as camadas de que precisa.
Defina style como null quando uma camada não estiver mais sendo usada.
Para estilizar um polígono na camada do elemento de região administrativa, siga estas etapas:
Consulte Começar para criar um novo ID e estilo de mapa, caso ainda não tenha feito isso. Ative a camada de elemento Região administrativa.
Receba uma referência à camada de elemento de região administrativa quando o mapa for inicializado.
featureLayer=map.getFeatureLayer("LOCALITY");
Crie uma definição de estilo do tipo google.maps.FeatureStyleFunction.
Defina a propriedade style na camada de elemento para FeatureStyleFunction.
O exemplo a seguir mostra como definir uma função para aplicar um estilo apenas ao google.maps.Feature com um ID de lugar correspondente:
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;}};
Se o ID de lugar especificado não for encontrado ou não corresponder ao tipo de elemento selecionado, o estilo não vai ser aplicado. Por exemplo, tentar definir o estilo de uma camada POSTAL_CODE correspondente ao ID de lugar de "Nova York" vai resultar em nenhum estilo aplicado.
Remover o estilo de uma camada
Para remover o estilo de uma camada, defina style como null:
featureLayer.style=null;
Pesquisar IDs de lugares para segmentar elementos
Para conferir os IDs de lugares das regiões:
Use as APIs Places e Geocoding para pesquisar regiões pelo nome e encontrar os IDs de lugares das áreas dentro dos limites especificados.
Use eventos de clique para encontrar dados. Isso retorna o elemento associado a uma região clicada, o que dá acesso ao ID de lugar, nome de exibição e categoria do tipo de elemento dela.
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,["Última atualização 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"]]