<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Brasil Choropleth</title>

  <link rel="stylesheet" href="./css/font-face.css">
  <link rel="stylesheet" href="./css/styles.css">
  <link rel="stylesheet" href="./css/loading.css">
</head>
<body>
  <header class="title">
    <h1>Brasil</h1>
    <h2>População 2018</h2>
  </header>

  <section class="choropleth">
    <div class="controls">
      <label class="controls-label">
        <input type="radio"
               name="kind"
               value="state"
               class="controls-input"
               autocomplete="off"
               checked />

        <i></i>
        <span class="controls-text">Estados</span>
      </label>

      <label class="controls-label">
        <input type="radio"
               name="kind"
               value="county"
               class="controls-input"
               autocomplete="off" />

        <i></i>
        <span class="controls-text">Municípios</span>
      </label>
    </div>

    <svg></svg>

    <span class="tooltip"></span>
    <div class="loading"></div>
  </section>

  <script src="https://d3js.org/d3.v5.js"></script>
  <script src="https://unpkg.com/topojson@3"></script>
  <script src="scripts.js" type="module" charset="utf-8"></script>
</body>
</html>
@font-face {
  font-family: 'Blow Brush';
  src: url('fonts/blowbrush.ttf') format('truetype'),
       url('fonts/blowbrush.otf') format('opentype');
}

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

body {
  height: 100vh;
  display: flex;
  background: #E7FFE7;
  background: #8DC6F3;
}

.title {
  position: absolute;
  left: 60px;
  bottom: 200px;
}

h1, h2 {
  font-family: 'Blow Brush';
  font-size: 90px;
  color: #FFDB4D;
}

h2 {
  font-size: 50px;
  color: #435E73;
}

.choropleth {
  width: 700px;
  height: 700px;
  margin: auto;
}

svg g {
  opacity: 1;
  visibility: visible;
  transition: opacity 2s, visibility 2s;
}

svg g.hide {
  opacity: 0;
  visibility: hidden;
}

.tooltip {
  position: absolute;
  color: #fff;
  padding: 10px;
  opacity: 0;
  display: flex;
  flex-direction: column;
  transition: all .4s;
  background: rgba(0, 0, 0, .4);
}

.controls-label {
  display: block;
  margin-bottom: 1.5em;
}

.controls-label > .controls-input {
  display: none;
}

.controls {
  position: absolute;
  left: 7vw;
}

.controls-label > i {
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin-right: 5px;
  vertical-align: middle;
  border: 2px solid #525a5d;
  box-shadow: inset 0 0 0 4px #8DC6F3;
  transition: 0.25s;
}

.controls-label > .controls-text {
  display: inline-block;
  padding-bottom: 3px;
  border-bottom: 2px dotted #525a5d;
  text-transform: uppercase;
  letter-spacing: 3px;
  font-size: 0.9em;
}

.controls-label > .controls-input:checked + i {
  background: #525a5d;
}

.controls-label:hover {
  cursor: pointer;
}

.loading,
.loading:after {
  border-radius: 50%;
  width: 50px;
  height: 50px;
  opacity: 0;
  visibility: hidden;
  transition: opacity .3s, visiblity .3s;
}

.loading {
  font-size: 10px;
  position: absolute;
  top: calc(50% - 35px);
  left: calc(50% - 35px);
  border: 4px solid rgba(0, 0, 0, 0.2);
  border-left: 4px solid #000;
  transform: translateZ(0);
  animation: load8 1.1s infinite linear;
}

.loading--show {
  opacity: 1;
  visibility: visible;
}

@keyframes load8 {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
import population from './data/states-population.js';
import statesCollection from './data/states.js';
import countiesPopulation from './data/counties-population.js';

const geoChart = {
  buildCount: 0,
  stateGeoJson: null,
  countyGeoJson: null,
  kind: 'state',
  loading: document.querySelector('.loading'),
  tooltip: d3.select(".tooltip"),

  init: function () {
    this.getStateGeoJson().then(json => {
      this.stateGeoJson = json;
      this.buildChoropleth();
    });
  },

  buildChoropleth: function () {
    const projection = d3.geoMercator().scale(870).center([-46, 351]),
          path = d3.geoPath().projection(projection),
          svg = d3.select('svg').style('width', '700px')
                                .style('height', '700px');

    const g = svg.append('g').lower().attr("class", this.kind);
    this.draw(path, g).then(() => this.toggleLoading(false));
  },

  draw: async function (path, g) {
    const isState =  this.kind === 'state';
    const kind = this.kind.replace(/^\w/, c => c.toUpperCase());
    const scale = {
      domain: isState ? [5, 30] : [30, 150],
      range: isState ? ["rgb(20, 97, 20)", "#ffff43"] : ["green", "yellow"],
      divisor: isState ? 1000000 : 1000
    }

    const color = d3.scaleLinear().domain(scale.domain).range(scale.range);
    this.initTooltip();

    g.selectAll('path')
     .data(this[`${this.kind}GeoJson`].features)
     .enter()
     .append('path')
     .attr('class', 'estado')
     .attr('d', path)
     .attr('stroke', '#000')
     .style('fill', geo => color(this[`get${kind}Population`](geo) / scale.divisor))
     .on("mouseenter", geo => this.updateTooltip(geo))
     .on("mouseout", geo => this.tooltip.style("opacity", 0))

    this.buildCount++;
  },

  getCountyPopulation: (geo) => {
    const county = countiesPopulation.find(county => {
      return county.ibge_code.toString() === geo.properties.id;
    });

    return county && county.population_2018;
  },

  getStatePopulation: (geo) => population[geo.id],

  getCountyGeoJson: async function () {
    const repo = 'https://raw.githubusercontent.com/tbrugz/',
          url = 'geodata-br/master/geojson/geojs-100-mun.json';

    this.toggleLoading(true);
    return fetch(repo + url).then(s => s.json()).then(response => response);
  },

  getStateGeoJson: async function () {
    this.toggleLoading(true);
    return topojson.feature(statesCollection, statesCollection.objects.estados);
  },

  toggleChart: function (e) {
    this.reset();
    this.kind = e.target.value;

    if (this.buildCount < 2) {
      this.getCountyGeoJson().then(json => {
        this.countyGeoJson = json;
        this.buildChoropleth();
      });
    }
  },

  toggleLoading: function (status) {
    const method = status ? 'add' : 'remove';

    this.loading.classList[method]('loading--show');
  },

  initTooltip() {
    this.tooltip.append('text').attr("class", "tooltip-name");
    this.tooltip.append('text').attr("class", "tooltip-pop");
    this.tooltip.on("mouseenter", geo => this.tooltip.style("opacity", 1));
    this.tooltip.on("mouseleave", geo => this.tooltip.style("opacity", 0));
  },

  updateTooltip(geo) {
    const kind = this.kind.replace(/^\w/, c => c.toUpperCase());
    const key = this.kind === 'state' ? 'nome' : 'name';
    let pop = parseInt(this[`get${kind}Population`](geo));

    if (!pop) return;

    pop = pop.toLocaleString('pt-BR');
    this.tooltip.select('text.tooltip-name').text(() => geo.properties[key]);
    this.tooltip.select('text.tooltip-pop').text(() => `População: ${pop}`);
    this.tooltip.style("top", (d3.event.pageY - 20) + "px")
            .    style("left", (d3.event.pageX + 20) + "px")
                .style("opacity", 1);
  },

  reset: function () {
    const g = document.querySelector('svg g.state');
    g.classList.toggle('hide');
  }
}

geoChart.init();

const controls = document.querySelectorAll('.controls-input');

controls.forEach(control => control.addEventListener('change', function(e) {
  return geoChart.toggleChart(e);
}));