Para utilizar un diseño basado en datos para los límites, debes crear un ID de mapa que use el mapa de vectores de JavaScript. Luego, debes crear un nuevo diseño de mapa, seleccionar las capas de componentes de límite y asociar el diseño con tu ID de mapa.
Crea un ID de mapa
Para crear un ID de mapa nuevo, sigue los pasos que se indican en Personalización de Cloud. Configura el tipo de mapa como JavaScript y selecciona la opción Vector. Marca las opciones Inclinación y Rotación para habilitar la inclinación y la rotación en el mapa. Si el uso de la inclinación o la orientación afecta negativamente el funcionamiento de tu app, deja sin marcar las opciones Inclinación y Rotación para que los usuarios no puedan ajustar estos parámetros.
En la Consola de APIs de Google, puedes seleccionar las capas de componentes que deseas mostrar. Esto determina qué tipos de límites aparecerán en el mapa (por ejemplo, localidades, estados, etcétera).
Haz clic en el menú desplegable Capas de componentes para agregar o quitar capas.
Haz clic en Guardar para guardar los cambios y que estén disponibles en tus mapas.
Actualiza el código de inicialización del mapa
Para realizar esta acción, necesitas el ID de mapa que acabas de crear. Puedes encontrarlo en la página Administración de mapas.
Para cargar la API de Maps JavaScript, agrega el cargador de arranque intercalado al código de tu aplicación, como se muestra en el siguiente fragmento:
<script> (g=>{varh,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});vard=b.maps||(b.maps={}),r=newSet,e=newURLSearchParams,u=()=>h||(h=newPromise(async(f,n)=>{await(a=m.createElement("script"));e.set("libraries",[...r]+"");for(king)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:"YOUR_API_KEY",v:"weekly",// Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).// Add other bootstrap parameters as needed, using camel case.}); </script>
Cuando crees una instancia del mapa con la propiedad mapId, proporciona un ID de mapa. Debería ser el ID de mapa que configuraste utilizando un diseño de mapa con capas de componentes habilitadas.
map=newgoogle.maps.Map(document.getElementById('map'),{center:{lat:-34.397,lng:150.644},zoom:8,mapId:'MAP_ID'// A map ID using a style with one or more feature layers enabled.});
Para obtener una referencia a una capa de componentes del mapa, llama a map.getFeatureLayer() cuando se inicialice el mapa:
functioninitMap(){map=newgoogle.maps.Map(document.getElementById("map"),{center:{lat:20.773,lng:-156.01},zoom:12,mapId:'MAP_ID',});// Add a feature layer for localities.localityLayer=map.getFeatureLayer('LOCALITY');...}
Verifica las capabilities del mapa
El diseño de límites basado en datos requiere capabilities que están habilitadas en la Consola de APIs de Google y asociadas a un ID de mapa. Dado que los IDs de mapa son efímeros y están sujetos a cambios, puedes llamar a map.getMapCapabilities() para verificar si una capability determinada (por ejemplo, el diseño basado en datos) está disponible antes de llamarla. Esta verificación es opcional.
En el siguiente ejemplo, se muestra cómo agregar un objeto de escucha para suscribirse a los cambios de las capabilities del mapa:
// subscribe to changesmap.addListener('mapcapabilities_changed',()=>{constmapCapabilities=map.getMapCapabilities();if(!mapCapabilities.isDataDrivenStylingAvailable){// Data-driven styling is *not* available, add a fallback.// Existing feature layers are also unavailable.}});
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Falta la información que necesito","missingTheInformationINeed","thumb-down"],["Muy complicado o demasiados pasos","tooComplicatedTooManySteps","thumb-down"],["Desactualizado","outOfDate","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Problema con las muestras o los códigos","samplesCodeIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-08-27 (UTC)"],[[["\u003cp\u003eData-driven styling for boundaries requires a JavaScript vector map with a custom style associated with a map ID.\u003c/p\u003e\n"],["\u003cp\u003eYou can select specific boundary feature layers (like localities or states) to display in the Google API Console to optimize performance.\u003c/p\u003e\n"],["\u003cp\u003eInitialize your map with the designated map ID and API key, ensuring they are linked to the same Google Cloud project.\u003c/p\u003e\n"],["\u003cp\u003eUtilize \u003ccode\u003emap.getFeatureLayer()\u003c/code\u003e to access and interact with specific feature layers on your map.\u003c/p\u003e\n"],["\u003cp\u003eVerify the availability of data-driven styling by using \u003ccode\u003emap.getMapCapabilities()\u003c/code\u003e before implementation.\u003c/p\u003e\n"]]],["To utilize data-driven styling for boundaries, first, create a JavaScript vector map ID in the Google API Console. Next, create a new map style and associate it with the map ID, selecting the desired boundary feature layers. Then, update your map initialization code with the new map ID. Ensure your map ID and API key are linked to the same project. Finally, use `map.getFeatureLayer()` to reference feature layers and `map.getMapCapabilities()` to check styling availability.\n"],null,["Select platform: [Android](/maps/documentation/android-sdk/dds-boundaries/start \"View this page for the Android platform docs.\") [iOS](/maps/documentation/ios-sdk/dds-boundaries/start \"View this page for the iOS platform docs.\") [JavaScript](/maps/documentation/javascript/dds-boundaries/start \"View this page for the JavaScript platform docs.\")\n\n\u003cbr /\u003e\n\nTo use data-driven styling for boundaries you must create a map ID that uses the\nJavaScript vector map. Next, you must create a new map style, select the\nboundary feature layers, and associate the style with your map ID.\n\nCreate a map ID\n\nTo create a new [map ID](/maps/documentation/get-map-id), follow the steps in\n[Cloud customization](/maps/documentation/javascript/cloud-customization).\nSet the Map type to **JavaScript** , and select the **Vector** option.\nCheck **Tilt** and **Rotation** to enable tilt and rotation on the map. If\nthe use of tilt or heading adversely affects your app, leave **Tilt** and\n**Rotation** un-checked so users cannot adjust them.\n\nCreate a new map style\n\nTo create a new map style, follow the instructions in\n[Manage map styles](/maps/documentation/javascript/cloud-customization/map-styles-leg)\nto create the style, and\n[associate the style with the map ID you just created](/maps/documentation/javascript/cloud-customization/map-styles-leg#associate-style-with-map-id).\n| **Experimental:** This feature can only be set for light map styles. When you link a light map style that has this feature enabled to a [map\n| ID](../map-ids/mapid-over), the enabled layers are also available for the dark map style.\n\nSelect feature layers\n\nIn the Google API Console you can select which feature layers to display. This\ndetermines which kinds of boundaries will appear on the map (for example\nlocalities, states, and so on).\n| **Important:** For optimal performance, only select the layers you need.\n\nTo manage feature layers\n\n1. In the Google API Console, [go to the Map Styles page](https://console.cloud.google.com/project/_/google/maps-apis/studio/styles).\n2. Select a project if prompted.\n3. Select a map style.\n4. Click the **Feature layers** drop-down to add or remove layers.\n5. Click **Save** to save your changes and make them available to your maps.\n\nUpdate your map initialization code\n\nThis requires the map ID you just created. It can be found on your [Maps\nManagement](https://console.cloud.google.com/google/maps-apis/studio/maps) page.\n| **Important:** Your map ID and API key must be associated with the same Google Cloud console project. Likewise, the map ID must be associated with a map style with one or more feature layers enabled.\n\n1. Load the Maps JavaScript API by adding the inline bootstrap loader to your application code, as shown in the following snippet:\n\n```javascript\n\u003cscript\u003e\n (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: \"YOUR_API_KEY\",\n v: \"weekly\",\n // Use the 'v' parameter to indicate the /maps/documentation/javascript/versions to use (weekly, beta, alpha, etc.).\n // Add other /maps/documentation/javascript/load-maps-js-api#required_parameters as needed, using camel case.\n });\n\u003c/script\u003e\n```\n| **Note:** As the developer of a Maps JavaScript API application it is your responsibility to verify that your application complies with local laws by verifying that the correct region localization is applied for the country in which the application is hosted.\n\n1. Provide a map ID when you instantiate the map using the `mapId` property.\n This should be the map ID that you configured using a map style with feature\n layers enabled.\n\n ```javascript\n map = new\n google.maps.Map(document.getElementById('map'), {\n center: {lat: -34.397, lng: 150.644},\n zoom: 8,\n mapId: '\u003cvar translate=\"no\"\u003eMAP_ID\u003c/var\u003e' // A map ID using a style with one or more feature layers enabled.\n });\n ```\n\nLearn more about [loading the Maps JavaScript API](/maps/documentation/javascript/load-maps-js-api).\n\nAdd feature layers to a map\n\nTo get a reference to a feature layer on your map, call `map.getFeatureLayer()`\nwhen the map initializes: \n\n```javascript\nfunction initMap() {\n map = new google.maps.Map(document.getElementById(\"map\"), {\n center: { lat: 20.773, lng: -156.01 },\n zoom: 12,\n mapId: 'MAP_ID',\n });\n\n // Add a feature layer for localities.\n localityLayer = map.getFeatureLayer('LOCALITY');\n ...\n}\n```\n\nCheck map capabilities\n\nData-driven styling for boundaries requires capabilities which are enabled in the\nGoogle API Console, and associated with a map ID. Because map IDs are ephemeral\nand subject to change, you can call `map.getMapCapabilities()`\nto verify whether a certain capability (for example data-driven styling) is\navailable prior to calling it. This check is optional.\n\nThe following example shows adding a listener to subscribe to map capability\nchanges: \n\n```javascript\n// subscribe to changes\nmap.addListener('mapcapabilities_changed', () =\u003e {\n const mapCapabilities = map.getMapCapabilities();\n\n if (!mapCapabilities.isDataDrivenStylingAvailable) {\n // Data-driven styling is *not* available, add a fallback.\n // Existing feature layers are also unavailable.\n }\n});\n```\n\nNext steps\n\n- [Style a boundary polygon](/maps/documentation/javascript/dds-boundaries/style-polygon)\n- [Make a choropleth map](/maps/documentation/javascript/dds-boundaries/choropleth-map)\n- [Handle mouse events](/maps/documentation/javascript/dds-boundaries/handle-events)\n- [Get a place ID for a region](/maps/documentation/javascript/dds-boundaries/dds-use-maps-places-apis#use_to_find_a_region)\n- [Use the Geocoding and Places APIs with data-driven styling for boundaries](/maps/documentation/javascript/dds-boundaries/dds-use-maps-places-apis)"]]