Cómo aplicar diseño a un polígono de límite

Selecciona la plataforma: iOS JavaScript

Descripción general

Si deseas aplicar diseño al relleno y el trazo de un polígono de límite, utiliza FeatureStyleOptions para definir los atributos de diseño y establece la propiedad style en una capa de componentes con una función google.maps.FeatureStyleFunction que contenga la lógica de diseño.

El siguiente mapa de ejemplo muestra cómo se destaca el polígono de límite de una región única.

Para aplicar diseño a componentes de límite, puedes establecer la propiedad style con una función google.maps.FeatureStyleFunction que contenga la lógica de diseño. La función de diseño se ejecuta para cada componente que forma parte de la capa de componentes utilizada y se aplica en el momento en que especificas la propiedad de diseño. Para actualizar esa función, tienes que establecer la propiedad de diseño nuevamente.

Si quieres uniformar el diseño de todos los componentes incluidos en una capa, establece la propiedad style en google.maps.FeatureStyleOptions. En este caso, no necesitas utilizar una función de diseño de componentes, ya que no se requiere ninguna lógica.

La función de diseño siempre debe mostrar resultados coherentes cuando se aplica a los componentes. Por ejemplo, si deseas colorear de forma aleatoria un conjunto de componentes, la aleatoriedad no debe ocurrir en la función de diseño de los componentes, ya que esto generaría resultados no deseados.

Dado que esta función se ejecuta en todos los componentes 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 en null cuando una capa ya no esté en uso.

Para definir el diseño de un polígono en la capa del componente de localidad, sigue estos pasos:

  1. Si aún no lo hiciste, sigue los pasos que se indican en Cómo comenzar para crear un ID y un diseño de mapa nuevos. Asegúrate de habilitar la capa del componente Localidad.
  2. Obtén una referencia a la capa del componente de localidad cuando se inicialice el mapa.

    featureLayer = map.getFeatureLayer("LOCALITY");
  3. Crea una definición de diseño del tipo google.maps.FeatureStyleFunction.

  4. Establece FeatureStyleFunction como la propiedad style en la capa del componente. En el siguiente ejemplo, se muestra cómo definir una función para aplicar un diseño solo a google.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 diseño no se aplica. Por ejemplo, si intentas aplicar un diseño a una capa POSTAL_CODE que coincide con el ID de lugar de "Ciudad de Nueva York", no se aplicará ningún diseño.

Cómo quitar el diseño aplicado a una capa

Para quitar el diseño aplicado a una capa, establece style en null:

featureLayer.style = null;

Cómo buscar los IDs de lugar para vincularlos con los componentes

Para obtener los IDs de lugar correspondientes a regiones, haz lo siguiente:

La cobertura varía según la región. Para obtener más detalles, consulta Cobertura de 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;

async function initMap() {
  // Request needed libraries.
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;

  map = new 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;
    }
  };

}

initMap();

JavaScript

let map;
//@ts-ignore
let featureLayer;

async function initMap() {
  // Request needed libraries.
  const { Map } = await google.maps.importLibrary("maps");

  map = new Map(document.getElementById("map"), {
    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 = {
    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;
    }
  };
}

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>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <div id="map"></div>

    <!-- prettier-ignore -->
    <script>(g=>{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=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)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: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"});</script>
  </body>
</html>

Prueba la muestra