Style point data features

This example shows an approach to styling point geometry based data features. It is based on the following dataset: 2018 Squirrel Census Fur Color Map

Read the documentation.

TypeScript

const mapElement = document.querySelector('gmp-map')!;
let innerMap: google.maps.Map;
function setStyle(params: { feature: google.maps.Feature }) {
    // Get the dataset feature, so we can work with all of its attributes.
    const datasetFeature = params.feature as google.maps.DatasetFeature;
    // Get all of the needed dataset attributes.
    const furColors =
        datasetFeature.datasetAttributes.CombinationofPrimaryandHighlightColor;

    // Apply styles. Fill is primary fur color, stroke is secondary fur color.
    switch (furColors) {
        case 'Black+':
            return {
                fillColor: 'black',
                pointRadius: 8,
            };
            break;
        case 'Cinnamon+':
            return {
                fillColor: '#8b0000',
                pointRadius: 8,
            };
            break;
        case 'Cinnamon+Gray':
            return {
                fillColor: '#8b0000',
                strokeColor: 'gray',
                pointRadius: 6,
            };
            break;
        case 'Cinnamon+White':
            return {
                fillColor: '#8b0000',
                strokeColor: 'white',
                pointRadius: 6,
            };
            break;
        case 'Gray+':
            return {
                fillColor: 'gray',
                pointRadius: 8,
            };
            break;
        case 'Gray+Cinnamon':
            return {
                fillColor: 'gray',
                strokeColor: '#8b0000',
                pointRadius: 6,
            };
            break;
        case 'Gray+Cinnamon, White':
            return {
                fillColor: 'silver',
                strokeColor: '#8b0000',
                pointRadius: 6,
            };
            break;
        case 'Gray+White':
            return {
                fillColor: 'gray',
                strokeColor: 'white',
                pointRadius: 6,
            };
            break;
        default: // Color not defined.
            return {
                fillColor: 'yellow',
                pointRadius: 8,
            };
            break;
    }
}

async function init() {
    // Request needed libraries.
    const [{ event }] = await Promise.all([
        google.maps.importLibrary('core'),
        google.maps.importLibrary('maps'),
    ]);

    // Get the inner map.
    innerMap = mapElement.innerMap;

    event.addListenerOnce(innerMap, 'idle', () => {
        // Add the data legend.
        makeLegend();
    });

    // Dataset ID for squirrel dataset.
    const datasetId = 'a99635b0-5e73-4b2a-8ae3-cb40f4b7f47e';
    const datasetLayer = innerMap.getDatasetFeatureLayer(datasetId);
    datasetLayer.style = setStyle;
}

// Creates a legend for the map.
function makeLegend() {
    const colors = {
        black: ['black'],
        cinnamon: ['#8b0000'],
        'cinnamon + gray': ['#8b0000', 'gray'],
        'cinnamon + white': ['#8b0000', 'white'],
        gray: ['gray'],
        'gray + cinnamon': ['gray', '#8b0000'],
        'gray + cinnamon + white': ['silver', '#8b0000'],
        'gray + white': ['gray', 'white'],
        'no color data': ['yellow'],
    };

    const legend = document.getElementById('legend');
    legend!.id = 'legend';
    const title = document.createElement('div');
    title.innerText = 'Fur Colors';
    title.classList.add('title');
    legend!.appendChild(title);

    for (const color of Object.keys(colors) as Iterable<keyof typeof colors>) {
        const wrapper = document.createElement('div');
        wrapper.id = 'container';
        const box = document.createElement('div');
        box.style.backgroundColor = colors[color][0];
        if (colors[color][1]) {
            box.style.borderColor = colors[color][1];
        } else {
            box.style.borderColor = colors[color][0];
        }
        box.classList.add('box');
        const txt = document.createElement('div');
        txt.classList.add('legend');
        txt.innerText = color;
        wrapper.appendChild(box);
        wrapper.appendChild(txt);
        legend!.appendChild(wrapper);
    }
}

void init();

JavaScript

const mapElement = document.querySelector('gmp-map');
let innerMap;
function setStyle(params) {
    // Get the dataset feature, so we can work with all of its attributes.
    const datasetFeature = params.feature;
    // Get all of the needed dataset attributes.
    const furColors =
        datasetFeature.datasetAttributes.CombinationofPrimaryandHighlightColor;

    // Apply styles. Fill is primary fur color, stroke is secondary fur color.
    switch (furColors) {
        case 'Black+':
            return {
                fillColor: 'black',
                pointRadius: 8,
            };
            break;
        case 'Cinnamon+':
            return {
                fillColor: '#8b0000',
                pointRadius: 8,
            };
            break;
        case 'Cinnamon+Gray':
            return {
                fillColor: '#8b0000',
                strokeColor: 'gray',
                pointRadius: 6,
            };
            break;
        case 'Cinnamon+White':
            return {
                fillColor: '#8b0000',
                strokeColor: 'white',
                pointRadius: 6,
            };
            break;
        case 'Gray+':
            return {
                fillColor: 'gray',
                pointRadius: 8,
            };
            break;
        case 'Gray+Cinnamon':
            return {
                fillColor: 'gray',
                strokeColor: '#8b0000',
                pointRadius: 6,
            };
            break;
        case 'Gray+Cinnamon, White':
            return {
                fillColor: 'silver',
                strokeColor: '#8b0000',
                pointRadius: 6,
            };
            break;
        case 'Gray+White':
            return {
                fillColor: 'gray',
                strokeColor: 'white',
                pointRadius: 6,
            };
            break;
        default: // Color not defined.
            return {
                fillColor: 'yellow',
                pointRadius: 8,
            };
            break;
    }
}

async function init() {
    // Request needed libraries.
    const [{ event }] = await Promise.all([
        google.maps.importLibrary('core'),
        google.maps.importLibrary('maps'),
    ]);

    // Get the inner map.
    innerMap = mapElement.innerMap;

    event.addListenerOnce(innerMap, 'idle', () => {
        // Add the data legend.
        makeLegend();
    });

    // Dataset ID for squirrel dataset.
    const datasetId = 'a99635b0-5e73-4b2a-8ae3-cb40f4b7f47e';
    const datasetLayer = innerMap.getDatasetFeatureLayer(datasetId);
    datasetLayer.style = setStyle;
}

// Creates a legend for the map.
function makeLegend() {
    const colors = {
        black: ['black'],
        cinnamon: ['#8b0000'],
        'cinnamon + gray': ['#8b0000', 'gray'],
        'cinnamon + white': ['#8b0000', 'white'],
        gray: ['gray'],
        'gray + cinnamon': ['gray', '#8b0000'],
        'gray + cinnamon + white': ['silver', '#8b0000'],
        'gray + white': ['gray', 'white'],
        'no color data': ['yellow'],
    };

    const legend = document.getElementById('legend');
    legend.id = 'legend';
    const title = document.createElement('div');
    title.innerText = 'Fur Colors';
    title.classList.add('title');
    legend.appendChild(title);

    for (const color of Object.keys(colors)) {
        const wrapper = document.createElement('div');
        wrapper.id = 'container';
        const box = document.createElement('div');
        box.style.backgroundColor = colors[color][0];
        if (colors[color][1]) {
            box.style.borderColor = colors[color][1];
        } else {
            box.style.borderColor = colors[color][0];
        }
        box.classList.add('box');
        const txt = document.createElement('div');
        txt.classList.add('legend');
        txt.innerText = color;
        wrapper.appendChild(box);
        wrapper.appendChild(txt);
        legend.appendChild(wrapper);
    }
}

void init();

CSS

/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body {
    height: 100%;
    margin: 0;
    padding: 0;
}

#attributionLabel {
    background-color: rgba(255, 255, 255, 0.8);
    font-family: 'Roboto', 'Arial', sans-serif;
    font-size: 10px;
    padding: 2px;
    margin: 2px;
}

#legend,
#dataset,
#counter {
    background-color: #e5e5e5;
    width: 15em;

    margin-left: 1em;
    border-radius: 8px;
    font-family: Roboto, sans-serif;
    overflow: hidden;
}

#dataset select {
    border-radius: 0;
    padding: 0.1em;
    border: 1px solid black;
    width: auto;
    margin: 0.5em 1em;
}

.title {
    padding: 0.5em 1em;
    font-weight: bold;
    font-size: 1.5em;
    margin-bottom: 0.5em;
    background-color: rgb(66, 133, 244);
    color: white;
    width: 100%;
}

.button {
    font-size: 1.2em;
    margin: 1em;
    background-color: rgb(66, 133, 244);
    color: white;
    padding: 0.5em;
    border-radius: 8px;
}

#legend #container {
    margin: 0.5em;
    display: flex;
}

#legend div .box {
    display: flex;
    width: 1em;
    height: 1em;
    border-radius: 50%;
    border: 2px solid;
}

#legend div .legend {
    display: flex;
    padding: 0.3em;
}

HTML

<html>
    <head>
        <title>Style a point data feature</title>

        <link rel="stylesheet" type="text/css" href="./style.css" />
        <script type="module" src="./index.js"></script>
        <script>
            // prettier-ignore
            (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: "GOOGLE_MAPS_API_KEY"
            });
        </script>
    </head>
    <body>
        <gmp-map
            map-id="5cd2c9ca1cf05670"
            center="40.780101, -73.967780"
            zoom="17"
            map-type-control="false"
            street-view-control="false"
            fullscreen-control="false">
            <div id="legend" slot="control-inline-start-block-start"></div>
            <div id="attributionLabel" slot="control-block-end-inline-start">
                Data source: NYC Open Data
            </div>
        </gmp-map>
    </body>
</html>

Clone Sample

Git and Node.js are required to run this sample locally. Follow these instructions to install Node.js and NPM. You will also need a Google Maps API key.

The following commands clone the repository, install dependencies, and copy the environment file.

  git clone https://github.com/googlemaps-samples/js-api-samples.git
  cd js-api-samples
  npm i
  cp .env.template .env

Once you copy the environment file, make sure to open the .env file and replace <Insert your own development API key here> with your actual API key before starting the sample.

  cd samples/dds-datasets-point
  npm start