Pour appliquer un style de remplissage et de trait à un polygone de limite, utilisez FeatureStyleOptions pour définir les attributs de style, et définissez la propriété style d'un calque d'éléments sur une google.maps.FeatureStyleFunction, qui contient la logique d'application de style.
L'exemple de carte suivant illustre la mise en surbrillance d'un polygone de limite pour une région.
Appliquez un style aux éléments cartographiques de limite en définissant la propriété style sur une google.maps.FeatureStyleFunction, qui peut contenir une logique d'application de style. La fonction de style est exécutée sur chaque élément cartographique du calque d'éléments concerné, et elle est appliquée au moment où vous définissez la propriété de style. Pour la modifier, vous devez définir à nouveau la propriété de style.
Pour appliquer un style uniforme à tous les éléments d'un calque d'éléments, définissez la propriété style sur des google.maps.FeatureStyleOptions. Dans ce cas, vous n'avez pas besoin d'utiliser une fonction de style d'éléments cartographiques, puisqu'aucune logique n'est requise.
La fonction de style doit toujours renvoyer des résultats cohérents lorsqu'elle est appliquée sur des éléments cartographiques. Par exemple, si vous souhaitez colorer un ensemble d'éléments de manière aléatoire, la partie aléatoire ne doit pas se situer dans la fonction de style d'éléments cartographiques, car cela générerait des résultats indésirables.
Étant donné que cette fonction s'exécute sur chaque élément d'un calque, il est important de l'optimiser. Pour éviter d'affecter les délais d'affichage :
Activez uniquement les calques dont vous avez besoin.
Définissez style sur null lorsqu'un calque n'est plus utilisé.
Pour appliquer un style à un polygone dans le calque d'éléments de la localité :
Si ce n'est pas déjà fait, suivez les étapes de la section Commencer pour créer un ID et un style de carte. N'oubliez pas d'activer le calque d'éléments Localité.
Obtenez une référence au calque d'éléments de la localité lors de l'initialisation de la carte.
featureLayer=map.getFeatureLayer("LOCALITY");
Créez une définition de style de type google.maps.FeatureStyleFunction.
Définissez la propriété style sur le calque d'éléments sur FeatureStyleFunction.
L'exemple suivant montre comment définir une fonction pour n'appliquer un style qu'à google.maps.Feature avec un ID de lieu correspondant :
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;}};
Si l'ID de lieu est introuvable ou qu'il ne correspond pas au type d'élément sélectionné, le style ne sera pas appliqué. Par exemple, si vous tentez d'appliquer un style à un calque POSTAL_CODE correspondant à l'ID de lieu de "New York", aucun style ne sera appliqué.
Supprimer le style d'un calque
Pour supprimer le style d'un calque, définissez le style sur null :
featureLayer.style=null;
Rechercher des ID de lieu pour cibler des éléments cartographiques
Obtenez les données concernant les événements de clic. Cette opération renvoie l'élément cartographique correspondant à une région sur laquelle l'utilisateur a cliqué, ce qui vous permet d'accéder à son ID de lieu, son nom à afficher et sa catégorie de type d'élément.
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;}
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/08/31 (UTC).
[null,null,["Dernière mise à jour le 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"]]