Data Layer: Dynamic Styling

by Wolf

HTML

<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCOW7b0eVJzLBlTz1eY9XP04VJ48C_uaMQ&callback=initMap">
</script>

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

JavaScript

var map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {lat: -28, lng: 137}
  });

  // Load GeoJSON.
  map.data.loadGeoJson('https://storage.googleapis.com/mapsdevsite/json/google.json');

  // Color each letter gray. Change the color when the isColorful property
  // is set to true.
  map.data.setStyle(function(feature) {
    let color = 'gray';
    if (feature.getProperty('isColorful')) {
      color = feature.getProperty('color');
    }
    return /** @type {!google.maps.Data.StyleOptions} */({
      fillColor: color,
      strokeColor: color,
      strokeWeight: 2
    });
  });

  // When the user clicks, toggle 'isColorful', changing the colorfulness of the letters.
  map.data.addListener('click', function(event) {
  	let isColorful = event.feature.getProperty('isColorful');
    let color = 'purple';
    event.feature.setProperty('isColorful', !isColorful);
    if (!isColorful) {
    	color = event.feature.getProperty('color');
    }
    map.data.overrideStyle(event.feature, {
    	fillColor: color,
      strokeColor: color,
    });
  });

  // When the user hovers, tempt them to click by outlining the letters, and making them purple.
  // Call revertStyle() to remove all overrides. This will use the style rules
  // defined in the function passed to setStyle()
  map.data.addListener('mouseover', function(event) {
    let mouseoverColor = 'purple';
    map.data.revertStyle();
    if (event.feature.getProperty('isColorful')) {
			mouseoverColor = event.feature.getProperty('color');
    }
    map.data.overrideStyle(event.feature, {
    	strokeWeight: 4,
      fillColor: mouseoverColor,
      strokeColor: mouseoverColor,
    });
  });

  map.data.addListener('mouseout', function(event) {
    map.data.revertStyle();
  });
}