Descripción general
Para definir el estilo del relleno y el trazo de un polígono de límite, debes establecer la propiedad style
de una capa de elemento como una función google.maps.FeatureStyleFunction
, la cual puedes usar para definir atributos de estilo con respecto al color, la opacidad y el grosor de línea.
Si deseas definir el estilo de un polígono, configura la propiedad style
como google.maps.FeatureStyleFunction
. La función de estilo te permite definir la lógica con la que se diseñarán los polígonos individuales en una capa de elemento. Cuando se configura featureLayer.style
, la función de estilo se ejecuta en cada elemento de la capa de elemento afectada. La función se aplica en el momento en que configuras la propiedad de estilo. Para actualizarlo, debes configurar nuevamente la propiedad de estilo.
La función de estilo siempre debe mostrar resultados coherentes cuando se aplica a los elementos. Por ejemplo, si deseas colorear de forma aleatoria un conjunto de elementos, la aleatoriedad no debe ocurrir en la función de estilo de los elementos, ya que esto generaría resultados no deseados.
Dado que esta función se ejecuta en todos los elementos de una capa, la optimización es importante. Para evitar que se vean afectados los tiempos de renderización, haz lo siguiente:
- Habilita solo las capas necesarias.
- Establece
style
ennull
cuando una capa ya no esté en uso.
Para definir el estilo de un polígono en la capa del elemento localidad, sigue estos pasos:
- Si aún no lo hiciste, sigue los pasos que se indican en Cómo comenzar para crear un ID y un estilo de mapa nuevos. Asegúrate de habilitar la capa de elemento Localidad.
Obtén una referencia a la capa de elemento de localidad cuando se inicialice el mapa.
featureLayer = map.getFeatureLayer("LOCALITY");
Crea una definición de estilo del tipo
google.maps.FeatureStyleFunction
.Establece la propiedad
style
de la capa de elemento enFeatureStyleFunction
. En el siguiente ejemplo, se muestra cómo definir una función para aplicar un estilo solo agoogle.maps.Feature
con un ID de lugar coincidente: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; } };
Si no se encuentra el ID de lugar especificado o no coincide con el tipo de componente seleccionado, el estilo no se aplica. Por ejemplo, si intentas aplicar un estilo a una capa POSTAL_CODE
que coincide con el ID de lugar de "Ciudad de Nueva York", no se aplicará ningún estilo.
Cómo quitar el estilo aplicado a una capa
Para quitar el estilo aplicado una capa, establece style
en null
:
featureLayer.style = null;
Cómo buscar los IDs de lugar para llegar a los componentes
Para obtener los datos de la región:
- Realiza una solicitud de búsqueda de región para buscar regiones.
- Obtén datos de eventos de clic (devuelve el componente correspondiente a una región en la que se hizo clic y proporciona acceso a su ID de lugar, nombre visible y categoría del tipo de componente).
Usa el Visor de cobertura regional para ver los límites de Google disponibles en todas las regiones compatibles.
La cobertura varía según la región. Para obtener más detalles, consulta Cobertura de los límites de Google.
Los nombres geográficos se pueden obtener de muchas fuentes, como la Junta de Nombres Geográficos de USGS (USGS Board on Geographic Names) y los Archivos de Gazetteer de EE.UU. (U.S. Gazetteer Files).
Ejemplo de código completo
TypeScript
let map: google.maps.Map; //@ts-ignore let featureLayer; function initMap() { map = new google.maps.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; } }; } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
let map; //@ts-ignore let featureLayer; function initMap() { map = new google.maps.Map(document.getElementById("map"), { center: { lat: 20.773, lng: -156.01 }, 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; } }; } window.initMap = 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> <!-- The `defer` attribute causes the callback to execute after the full HTML document has been parsed. For non-blocking uses, avoiding race conditions, and consistent behavior across browsers, consider loading using Promises. See https://developers.google.com/maps/documentation/javascript/load-maps-js-api for more information. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=beta" defer ></script> </body> </html>