Estilizar um polígono de limites

Perspectiva geral

Para estilizar o preenchimento e o traço de um polígono de limites, defina a propriedade style em uma camada de recursos para google.maps.FeatureStyleFunction, que pode ser usado ao definir atributos de cor, opacidade e espessura da linha.

Para estilizar um polígono, defina a propriedade style como google.maps.FeatureStyleFunction. É com a função de estilo que você define a lógica para estilizar polígonos individuais em uma camada de recursos. Quando featureLayer.style está configurado, a função de estilo é executada em todos os recursos na respectiva camada afetada. A função é aplicada assim que a propriedade de estilo é configurada. Em caso de atualização, é necessário redefinir a propriedade de estilo.

A função de estilo precisa sempre retornar resultados consistentes quando for aplicada aos recursos. Por exemplo, para colorir aleatoriamente um conjunto de atributos, a parte aleatória não pode ocorrer na função de estilo de recurso porque isso leva a resultados não intencionais.

Como essa função é executada em todos os recursos 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 recurso de localidade, siga estas etapas:

  1. Consulte Começar para criar um novo ID e estilo de mapa, caso ainda não tenha feito isso. Ative a camada de recursos Região administrativa.
  2. Receba uma referência à camada de recursos de região administrativa quando o mapa for inicializado.

    featureLayer = map.getFeatureLayer("LOCALITY");
  3. Crie uma definição de estilo do tipo google.maps.FeatureStyleFunction.

  4. Defina a propriedade style na camada de recursos 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-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;
      }
    };

Se o ID de lugar especificado não for encontrado ou não corresponder ao tipo de recurso 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 lugar para segmentar elementos

Para receber dados de regiões:

Use o visualizador de cobertura de região para consultar os limites do Google disponíveis para todas as regiões compatíveis.

A cobertura varia de acordo com a região. Consulte os detalhes em Cobertura dos limites do Google.

Os nomes geográficos estão disponíveis em muitas fontes, como o USGS Board on Geographic Names e o U.S. Gazetteer Files (links em inglês).

Exemplo 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>

Testar exemplo de código