The Google Fusion Tables API v1 has been deprecated as of May 3rd, 2016. The API will continue to work until August 1st, 2017, and will shut down on that date. A migration guide is available outlining the steps to take to migrate to v2.

Fusion Tables API Example: Advanced Visualization


<!DOCTYPE html>
<!--
  Copyright 2011 Google Inc. All Rights Reserved.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<html>
  <head>
    <meta charset="UTF-8">

    <title>Fusion Tables API Example: Advanced Visualization</title>

    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript"
        src="http://maps.google.com/maps/api/js?sensor=false"></script>

    <link href="/apis/fusiontables/docs/samples/style/default.css"
        rel="stylesheet" type="text/css">
    <style type="text/css">
      #map-canvas {
        width: auto;
      }

      #visualization {
        float: right;
      }

      #legend {
        background: #FFF;
        margin: 10px;
        padding: 5px;
        width: 150px;
      }

      #legend p {
        font-weight: bold;
        margin-top: 3px;
      }

      #legend div {
        clear: both;
      }

      .color {
        height: 12px;
        width: 12px;
        margin-right: 3px;
        float: left;
        display: block;
      }

      .high {
        color: #F00;
      }

      .medium {
        color: #0F0;
      }

      .low {
        color: #00F;
      }

      .high, .medium, .low {
        font-weight: bold;
      }
    </style>

    <script type="text/javascript">
      google.load('visualization', '1', { packages: ['corechart'] });

      /**
       * Sector type mapped to a style rule.
       * @type {Object}
       * @const
       */
      var LAYER_STYLES = {
        'Residential': {
          'min': 0,
          'max': 10000,
          'colors': [
            '#f4cccc',
            '#ea9999',
            '#e06666',
            '#cc0000',
            '#990000'
          ]
        },
        'Non-Residential': {
          'min': 0,
          'max': 10000,
          'colors': [
            '#d0e0e3',
            '#a2c4c9',
            '#76a5af',
            '#45818e',
            '#134f5c'
          ]
        },
        'Total': {
          'min': 0,
          'max': 20000,
          'colors': [
            '#d9d2e9',
            '#b4a7d6',
            '#8e7cc3',
            '#674ea7',
            '#351c75'
          ]
        }
      }

      function initialize() {
        var sector = 'Residential';

        var map = new google.maps.Map(document.getElementById('map-canvas'), {
          center: new google.maps.LatLng(37.4, -119.8),
          zoom: 5,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          zoomControlOptions: {
            style: google.maps.ZoomControlStyle.SMALL
          },
        });

        var layer = new google.maps.FusionTablesLayer();
        updateLayerQuery(layer, sector);
        layer.setMap(map);

        createLegend(map, sector);
        styleLayerBySector(layer, sector);
        styleMap(map);
        drawVisualization('Alameda');

        google.maps.event.addListener(layer, 'click', function(e) {
          var county = e.row['County'].value;
          drawVisualization(county);

          var electricity = e.row['2010'].value;
          if (electricity > 5000) {
            e.infoWindowHtml = '<p class="high">High Usage!</p>';
          } else if (electricity > 2500) {
            e.infoWindowHtml = '<p class="medium">Medium Usage</p>';
          } else {
            e.infoWindowHtml = '<p class="low">Low Usage</p>';
          }
        });

        google.maps.event.addDomListener(document.getElementById('sector'),
            'change', function() {
              sector = this.value;
              updateLayerQuery(layer, sector);
              styleLayerBySector(layer, sector);
              updateLegend(sector);
            });

        google.maps.event.addDomListener(document.getElementById('county'),
            'change', function() {
              var county = this.value;
              updateLayerQuery(layer, sector, county);
              drawVisualization(county);
            });
      }

      function updateLayerQuery(layer, sector, county) {
        var where = "Sector = '" + sector + "'";
        if (county) {
          where += " AND County = '" + county + "'";
        }
        layer.setOptions({
          query: {
            select: 'geometry',
            from: '18fyPg1LvW3KB3N5DE_ub-MKicB0Nx7vkGn9kw4s',
            where: where
          }
        });
      }

      function createLegend(map, sector) {
        var legendWrapper = document.createElement('div');
        legendWrapper.id = 'legendWrapper';
        legendWrapper.index = 1;
        map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(
            legendWrapper);
        legendContent(legendWrapper, sector);
      }

      function legendContent(legendWrapper, sector) {
        var legend = document.createElement('div');
        legend.id = 'legend';

        var title = document.createElement('p');
        title.innerHTML = sector + ' Electricity Consumption';
        legend.appendChild(title);

        var layerStyle = LAYER_STYLES[sector];
        var colors = layerStyle.colors;
        var minNum = layerStyle.min;
        var maxNum = layerStyle.max;
        var step = (maxNum - minNum) / colors.length;
        for (var i = 0; i < colors.length; i++) {
          var legendItem = document.createElement('div');

          var color = document.createElement('div');
          color.setAttribute('class', 'color');
          color.style.backgroundColor = colors[i];
          legendItem.appendChild(color);

          var newMin = minNum + step * i;
          var newMax = newMin + step;
          var minMax = document.createElement('span');
          minMax.innerHTML = newMin + ' - ' + newMax;
          legendItem.appendChild(minMax);

          legend.appendChild(legendItem);
        }

        legendWrapper.appendChild(legend);
      }

      function updateLegend(sector) {
        var legendWrapper = document.getElementById('legendWrapper');
        var legend = document.getElementById('legend');
        legendWrapper.removeChild(legend);
        legendContent(legendWrapper, sector);
      }

      function styleLayerBySector(layer, sector) {
        var layerStyle = LAYER_STYLES[sector];
        var colors = layerStyle.colors;
        var minNum = layerStyle.min;
        var maxNum = layerStyle.max;
        var step = (maxNum - minNum) / colors.length;

        var styles = new Array();
        for (var i = 0; i < colors.length; i++) {
          var newMin = minNum + step * i;
          styles.push({
            where: generateWhere(newMin, sector),
            polygonOptions: {
              fillColor: colors[i],
              fillOpacity: 1
            }
          });
        }
        layer.set('styles', styles);
      }

      function generateWhere(minNum, sector) {
        var whereClause = new Array();
        whereClause.push("Sector = '");
        whereClause.push(sector);
        whereClause.push("' AND '2010' >= ");
        whereClause.push(minNum);
        return whereClause.join('');
      }

      function styleMap(map) {
        var style = [{
          featureType: 'all',
          stylers: [{
            saturation: -99
          }]
        }, {
          featureType: 'poi',
          stylers: [{
            visibility: 'off'
          }]
        }, {
          featureType: 'road',
          stylers: [{
            visibility: 'off'
          }]
        }];

        var styledMapType = new google.maps.StyledMapType(style, {
          map: map,
          name: 'Styled Map'
        });
        map.mapTypes.set('map-style', styledMapType);
        map.setMapTypeId('map-style');
      }

      function drawVisualization(county) {
        google.visualization.drawChart({
          containerId: "visualization",
          dataSourceUrl: "http://www.google.com/fusiontables/gvizdata?tq=",
          query: "SELECT Sector,'2006','2007','2008','2009','2010' " +
              "FROM 18fyPg1LvW3KB3N5DE_ub-MKicB0Nx7vkGn9kw4s WHERE County = '" + county + "'",
          chartType: "ColumnChart",
          options: {
            title: county,
            height: 400,
            width: 400
          }
        });
      }

      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="visualization"></div>
    <div id="map-canvas"></div>
    <form>
      <label>Sector </label>
      <select id="sector">
        <option value="Residential">Residential</option>
        <option value="Non-Residential">Non-Residential</option>
        <option value="Total">Total</option>
      </select>
      <label>County</label>
      <select id="county">
        <option value="Alameda">Alameda</option>
        <option value="Alpine">Alpine</option>
        <option value="Amador">Amador</option>
        <option value="Butte">Butte</option>
        <option value="Calaveras">Calaveras</option>
        <option value="Colusa">Colusa</option>
        <option value="Contra Costa">Contra Costa</option>
        <option value="Del Norte">Del Norte</option>
        <option value="El Dorado">El Dorado</option>
        <option value="Fresno">Fresno</option>
        <option value="Glenn">Glenn</option>
        <option value="Humboldt">Humboldt</option>
        <option value="Imperial">Imperial</option>
        <option value="Inyo">Inyo</option>
        <option value="Kern">Kern</option>
        <option value="Kings">Kings</option>
        <option value="Lake">Lake</option>
        <option value="Lassen">Lassen</option>
        <option value="Los Angeles">Los Angeles</option>
        <option value="Madera">Madera</option>
        <option value="Marin">Marin</option>
        <option value="Mariposa">Mariposa</option>
        <option value="Mendocino">Mendocino</option>
        <option value="Merced">Merced</option>
        <option value="Modoc">Modoc</option>
        <option value="Mono">Mono</option>
        <option value="Monterey">Monterey</option>
        <option value="Napa">Napa</option>
        <option value="Nevada">Nevada</option>
        <option value="Orange">Orange</option>
        <option value="Placer">Placer</option>
        <option value="Plumas">Plumas</option>
        <option value="Riverside">Riverside</option>
        <option value="Sacramento">Sacramento</option>
        <option value="San Benito">San Benito</option>
        <option value="San Bernardino">San Bernardino</option>
        <option value="San Diego">San Diego</option>
        <option value="San Francisco">San Francisco</option>
        <option value="San Joaquin">San Joaquin</option>
        <option value="San Luis Obispo">San Luis Obispo</option>
        <option value="San Mateo">San Mateo</option>
        <option value="Santa Barbara">Santa Barbara</option>
        <option value="Santa Clara">Santa Clara</option>
        <option value="Santa Cruz">Santa Cruz</option>
        <option value="Shasta">Shasta</option>
        <option value="Sierra">Sierra</option>
        <option value="Siskiyou">Siskiyou</option>
        <option value="Solano">Solano</option>
        <option value="Sonoma">Sonoma</option>
        <option value="Stanislaus">Stanislaus</option>
        <option value="Sutter">Sutter</option>
        <option value="Tehama">Tehama</option>
        <option value="Trinity">Trinity</option>
        <option value="Tulare">Tulare</option>
        <option value="Tuolumne">Tuolumne</option>
        <option value="Ventura">Ventura</option>
        <option value="Yolo">Yolo</option>
        <option value="Yuba">Yuba</option>
      </select>
    </form>
  </body>
</html>