Style a boundary polygon

Select platform: iOS JavaScript

Overview

To style the fill and stroke for a boundary polygon, use FeatureStyleOptions to define style attributes, and set the style property on a feature layer to a google.maps.FeatureStyleFunction, which contains styling logic.

The following example map demonstrates highlighting the boundary polygon for a single region.

Apply style to boundary features by setting the style property to a google.maps.FeatureStyleFunction, which can contain styling logic. The style function is run over every feature in the affected feature layer, and is applied at the time you set the style property. To update it, you must set the style property again.

To uniformly style all features for a feature layer, set the style property to a google.maps.FeatureStyleOptions. In this case, you don't need to use a feature style function, since logic is not required.

The style function should always return consistent results when it is applied over features. For example, if you wanted to randomly color a set of features, the random part should not take place in the feature style function, as that would cause unintended results.

Because this function runs over every feature in a layer, optimization is important. To avoid impacting rendering times:

  • Enable only the layers you need.
  • Set style to null when a layer is no longer in use.

To style a polygon in the locality feature layer, take the following steps:

  1. If you haven't already done so, follow the steps in Get Started to create a new map ID and map style. Be sure to enable the Locality feature layer.
  2. Get a reference to the locality feature layer when the map initializes.

    featureLayer = map.getFeatureLayer("LOCALITY");
  3. Create a style definition of type google.maps.FeatureStyleFunction.

  4. Set the style property on the feature layer to the FeatureStyleFunction. The following example shows defining a function to apply a style only to the google.maps.Feature with a matching place ID:

    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;
      }
    };

If the specified place ID is not found, or does not match the selected feature type, the style is not applied. For example, attempting to style a POSTAL_CODE layer matching the place ID for "New York City" would result in no style being applied.

Remove styling from a layer

To remove styling from a layer, set the style to null:

featureLayer.style = null;

Look up place IDs to target features

To get place IDs for regions:

  • Use Places APIs and Geocoding to search for regions by name, and get place IDs for regions within specified bounds.
  • Get data from click events. This returns the Feature corresponding to a region clicked, which provides access to its place ID, display name, and feature type category.

Coverage varies by region. See Google boundaries coverage for details.

Geographic names are available from many sources, such as the USGS Board on Geographic Names, and the U.S. Gazetteer Files.

Complete example code

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 },
    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>
    <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>

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

Try Sample