yashghelani yashghelani - 4 months ago 22
HTML Question

Google Chart is not displaying

I'm trying to create a feature in which when you select a region from a dropdown list and request rainfall data for it, you'll get a Google Chart for that data.

But, it's not working.

Can you check what the problem is?

Sorry in advance for the ugly code. I'm a newbie to JS. I've commented the code though to help understand it better.

Thanks :)

Here is the fiddle.

Here is the HTML -

<!-- Some text -->
<div class="text">
Select a region below to know the annual rainfall in that region.
</div>

<!-- Create dropdown list -->
<div>
<select class="region">
<option selected="selected" disabled>Select a region</option>
<option>Andaman &amp; Nicobar Islands</option>
<option>Arunachal Pradesh</option>
<option>Assam, Meghalaya</option>
<option>Bihar</option>
<option>Chattisgarh</option>
<option>Coastal Karnataka</option>
<option>Coastal Andhra Pradesh</option>
<option>East Rajasthan</option>
<option>East Madhya Pradesh</option>
<option>East Uttar Pradesh</option>
<option>Gangetic West Bengal</option>
<option>Gujarat Region, Dadra &amp; Nagar Haveli</option>
<option>Haryana, Delhi, Chandigarh</option>
<option>Himachal Pradesh</option>
<option>Jammu, Kashmir</option>
<option>Jharkhand</option>
<option>Kerala</option>
<option>Kokan, Goa</option>
<option>Lakshadweep</option>
<option>Madhya Maharashtra</option>
<option>Maratwada</option>
<option>Nagaland, Manipur, Mizoram, Tripura</option>
<option>North Interior Karnataka</option>
<option>Orissa</option>
<option>Punjab</option>
<option>Rayalseema</option>
<option>Saurashtra, Kutch, Diu</option>
<option>South Interior Karnataka</option>
<option>Sub-Himalayan, West Bengal, Sikkim</option>
<option>Tamil Nadu, Pondicherry</option>
<option>Telengana</option>
<option>Uttaranchal</option>
<option>Vidarbha</option>
<option>West Madhya Pradesh</option>
<option>West Rajasthan</option>
<option>West Uttar Pradesh</option>
</select>
</div>

<!-- Create button to request data -->
<div>
<button type="button">Get data!</button>
</div>

<!-- Div in which the chart will be drawn -->
<div id="chart">
</div>


Here is the JS -

// Get region text
var region = jQuery(".region").find(":selected").text();

//Create button variable
var button = jQuery("button");

//Detect change in region selection and store the selected region in the variable
jQuery(".region").change(function() {
region = jQuery(".region").find(":selected").text();
});

//When the data is requested (button is pressed)
button.click(function() {
google.charts.load('current', {
'packages': ['corechart']
});

google.charts.setOnLoadCallback(drawChart);

//Drawing the chart
function drawChart() {
var query;

//Tests to check which region is selected
if (region == "Andaman & Nicobar Islands") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:B");
} else if (region == "Arunachal Pradesh") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:C");
} else if (region == "Assam, Meghalaya") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:D");
} else if (region == "Bihar") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:E");
} else if (region == "Chattisgarh") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:F");
} else if (region == "Coastal Karnataka") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:G");
} else if (region == "Coastal Andhra Pradesh") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:H");
} else if (region == "East Rajasthan") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:I");
} else if (region == "East Madhya Pradesh") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:J");
} else if (region == "East Uttar Pradesh") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:K");
} else if (region == "Gangetic West Bengal") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:L");
} else if (region == "Gujarat Region, Dadra & Nagar Haveli") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:M");
} else if (region == "Haryana, Delhi, Chandigarh") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:N");
} else if (region == "Himachal Pradesh") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:O");
} else if (region == "Jammu, Kashmir") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:P");
} else if (region == "Jharkhand") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:Q");
} else if (region == "Kerala") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:R");
} else if (region == "Kokan, Goa") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:S");
} else if (region == "Lakshadweep") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:T");
} else if (region == "Madhya Maharashtra") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:U");
} else if (region == "Maratwada") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:V");
} else if (region == "Nagaland, Manipur, Mizoram, Tripura") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:W");
} else if (region == "North Interior Karnataka") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:X");
} else if (region == "Orissa") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:Y");
} else if (region == "Punjab") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:Z");
} else if (region == "Rayalseema") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:AA");
} else if (region == "Saurashtra, Kutch, Diu") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:AB");
} else if (region == "South Interior Karnataka") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:AC");
} else if (region == "Sub-Himalayan, West Bengal, Sikkim") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:AD");
} else if (region == "Tamil Nadu, Pondicherry") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:AE");
} else if (region == "Telengana") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:AF");
} else if (region == "Uttaranchal") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:AG");
} else if (region == "Vidarbha") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:AH");
} else if (region == "West Madhya Pradesh") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:AI");
} else if (region == "West Rajasthan") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:AJ");
} else if (region == "West Uttar Pradesh") {
query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&range=A:AK");
}

query.send(handleQueryResponse);
};

function handleQueryResponse(response) {
var data = response.getDataTable();
var chartAreaHeight = data.getNumberOfRows() * 10;
var chartHeight = chartAreaHeight + 70;
var options = {
annotations: {
textStyle: {
fontSize: 10
}
},
legend: "none",
vAxis: {
title: "Year",
format: "0"
},
hAxis: {
title: "Rainfall (in mm)"
},
height: chartHeight,
chartArea: {
height: chartAreaHeight,
top: "100",
right: "100",
bottom: "100",
left: "100"
}
};

//Tests to check which region is selected
if (region == "Andaman & Nicobar Islands") {
options = {
title = "Andaman & Nicobar Islands"
}
} else if (region == "Arunachal Pradesh") {
options = {
title = "Arunachal Pradesh"
}
} else if (region == "Assam, Meghalaya") {
options = {
title = "Assam, Meghalaya"
}
} else if (region == "Bihar") {
options = {
title = "Bihar"
}
} else if (region == "Chattisgarh") {
options = {
title = "Chattisgarh"
}
} else if (region == "Coastal Karnataka") {
options = {
title = "Coastal Karnataka"
}
} else if (region == "Coastal Andhra Pradesh") {
options = {
title = "Coastal Andhra Pradesh"
}
} else if (region == "East Rajasthan") {
options = {
title = "East Rajasthan"
}
} else if (region == "East Madhya Pradesh") {
options = {
title = "East Madhya Pradesh"
}
} else if (region == "East Uttar Pradesh") {
options = {
title = "East Uttar Pradesh"
}
} else if (region == "Gangetic West Bengal") {
options = {
title = "Gangetic West Bengal"
}
} else if (region == "Gujarat Region, Dadra & Nagar Haveli") {
options = {
title = "Gujarat Region, Dadra & Naga Haveli";
}
} else if (region == "Haryana, Delhi, Chandigarh") {
options = {
title = "Haryana, Delhi, Chandigarh"
}
} else if (region == "Himachal Pradesh") {
options = {
title = "Himachal Pradesh"
}
} else if (region == "Jammu, Kashmir") {
options = {
title = "Jammu, Kashmir"
}
} else if (region == "Jharkhand") {
options = {
title = "Jharkhand"
}
} else if (region == "Kerala") {
options = {
title = "Kerala"
}
} else if (region == "Kokan, Goa") {
options = {
title = "Kokan, Goa"
}
} else if (region == "Lakshadweep") {
options = {
title = "Lakshadweep"
}
} else if (region == "Madhya Maharashtra") {
options = {
title = "Madhya Maharashtra"
}
} else if (region == "Maratwada") {
options = {
title = "Maratwada"
}
} else if (region == "Nagaland, Manipur, Mizoram, Tripura") {
options = {
title = "Nagaland, Manipur, Mizoram Tripura";
}
} else if (region == "North Interior Karnataka") {
options = {
title = "orth Interior Karnataka"
}
} else if (region == "Orissa") {
options = {
title = "Orissa"
}
} else if (region == "Punjab") {
options = {
title = "Punjab"
}
} else if (region == "Rayalseema") {
options = {
title = "Rayalseema"
}
} else if (region == "Saurashtra, Kutch, Diu") {
options = {
title = "Saurashtra, Kutch, Diu"
}
} else if (region == "South Interior Karnataka") {
options = {
title = "South Interior Karnataka"
}
} else if (region == "Sub-Himalayan, West Bengal, Sikkim") {
options = {
title = "Sub-Himalayan, West Bengal Sikkim";
}
} else if (region == "Tamil Nadu, Pondicherry") {
options = {
title = "Tamil Nadu, Pondicherry"
}
} else if (region == "Telengana") {
options = {
title = "Telengana"
}
} else if (region == "Uttaranchal") {
options = {
title = "Uttaranchal"
}
} else if (region == "Vidarbha") {
options = {
title = "Vidarbha"
}
} else if (region == "West Madhya Pradesh") {
options = {
title = "West Madhya Pradesh"
}
} else if (region == "West Rajasthan") {
options = {
title = "West Rajasthan"
}
} else if (region == "West Uttar Pradesh") {
options = {
title = "West Uttar Pradesh"
}
}

var formatter = new google.visualization.NumberFormat({
pattern: '#,##0.0'
});

formatter.format(data, 1);

var view = new google.visualization.DataView(data);

view.setColumns([0, 1, {
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
}]);

var chart = new google.visualization.BarChart(document.getElementById("chart"));
chart.draw(view, options);
window.addEventListener('resize', function() {
chart.draw(view, options);
}, false)
};
});

Answer

made a few changes...

  1. google.load and setOnLoadCallback should only be called once per page load
  2. added value attribute to option to avoid long if statement
  3. changed query to use the tq= parameter, which allows sql statement, and returns only the columns needed, instead of entire range
  4. removed 'get data' button

EDIT

  1. chart covers the dropdown list -- is due to css float: left; on .region
    changed to text-align: left;
  2. increase height of bars -- use chart option bar.groupWidth
  3. x-axis to have a difference of 1000 -- use chart option hAxis.ticks
    provide desired labels in an array
  4. y-axis to show all the years and not just a few in between -- same as above, but use vAxis.ticks
  5. added comments, let me know...

see following, working snippet...

// load google charts, version '45'. 'current' version throws error when loading DataView
google.charts.load('45', {
  // callback function when google finished loading
  'callback': function() {
    jQuery(".region").change(drawChart);
    // removed 'drawChart()', appears you want a selection before drawing
  },
  // packages used on this page
  'packages': ['corechart']
});

function drawChart() {
  // get the selected option value
  var region = jQuery(".region").find(":selected").val();

  // build query with select statement based on region value
  var query = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1wLbWMwwu_bXcpxm8TlkNtkR4gbeqz_o8CuRzdDQMUaM/gviz/tq?gid=799372846&tq=select A," + region);

  // run query
  query.send(handleQueryResponse);
};

function handleQueryResponse(response) {
  // get data table
  var data = response.getDataTable();

  // create number formatter
  var formatter = new google.visualization.NumberFormat({
    pattern: '0'
  });
  // format first column
  formatter.format(data, 0);

  // create number formatter
  var formatter = new google.visualization.NumberFormat({
    pattern: '#,##0.0'
  });
  // format second column
  formatter.format(data, 1);

  // set chart area height
  var chartAreaHeight = data.getNumberOfRows() * 12;

  // set chart height
  var chartHeight = chartAreaHeight + 70;

  // set x-axis labels or 'ticks'
  var xTicks = [];

  // find max amount for ticks
  var dataMax = google.visualization.data.group(
    data,
    // modifier column to find max on entire table
    [{column: 0, type: 'string', modifier: function () {return '';}}],
    // max column
    [{column: 1, type: 'number', aggregation: google.visualization.data.max}]
  );

  // 'round up' to nearest 1000
  var maxTick = Math.ceil(dataMax.getValue(0, 1) / 1000) * 1000;

  // load ticks array
  for (var i = 0; i <= maxTick; i = i + 1000) {
    xTicks.push(i);
  }

  // build y-axis ticks, add every year, need to reduce font or increase height
  var yTicks = [];
  for (var i = 0; i < data.getNumberOfRows(); i++) {
    yTicks.push(data.getValue(i, 0));
  }

  // chart options
  var options = {
    animation: {
      startup: true,
      easing: 'linear',
      duration: 750
    },
    annotations: {
      textStyle: {
        fontSize: 7
      }
    },
    title: jQuery(".region").find(":selected").text(),
    legend: "none",
    vAxis: {
      title: "Year",
      format: "0"
    },
    hAxis: {
      title: "Rainfall (in mm)"
    },
    height: chartHeight,
    chartArea: {
      height: chartAreaHeight,
      // use number for exact, string for percentage "100%"
      top: 70,
      right: 100,
      bottom: 100,
      left: 100
    },
    // set bar height
    bar: {
      groupWidth: 7
    },
    // set x-axis ticks
    hAxis: {
      ticks: xTicks
    },
    // set y-axis options
    vAxis: {
      // text style, reduce font
      textStyle: {
        fontSize: 8
      },
      // tick marks
      ticks: yTicks
    }
  };

  // create data view from data table
  var view = new google.visualization.DataView(data);
  // add calculated column for annotations, 'current' version bombs here
  view.setColumns([0, 1, {
    calc: "stringify",
    sourceColumn: 1,
    type: "string",
    role: "annotation"
  }]);

  // create, draw chart
  var chart = new google.visualization.BarChart(document.getElementById("chart"));
  chart.draw(view, options);

  // re-draw chart when the window resizes
  // removed 'window.addEventListener' as may not work in older browsers
  $(window).resize(function() {
    chart.draw(view, options);
  });
};
.text {
  margin-bottom: 10px;
}

.region {
  text-align: left;
}

button {
  text-align: left;
  margin-left: 10px;
}

#chart {
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div class="text">
    Select a region below to know the annual rainfall in that region.
</div>

<div>
    <select class="region">
        <!-- like this better than 'optgroup', if selection must be made before draw -->
        <option selected="selected" disabled>Please select a region...</option>
        <option value="B">Andaman &amp; Nicobar Islands</option>
        <option value="C">Arunachal Pradesh</option>
        <option value="D">Assam, Meghalaya</option>
        <option value="E">Bihar</option>
        <option value="F">Chattisgarh</option>
        <option value="G">Coastal Karnataka</option>
        <option value="H">Coastal Andhra Pradesh</option>
        <option value="I">East Rajasthan</option>
        <option value="J">East Madhya Pradesh</option>
        <option value="K">East Uttar Pradesh</option>
        <option value="L">Gangetic West Bengal</option>
        <option value="M">Gujarat Region, Dadra &amp; Nagar Haveli</option>
        <option value="N">Haryana, Delhi, Chandigarh</option>
        <option value="O">Himachal Pradesh</option>
        <option value="P">Jammu, Kashmir</option>
        <option value="Q">Jharkhand</option>
        <option value="R">Kerala</option>
        <option value="S">Kokan, Goa</option>
        <option value="T">Lakshadweep</option>
        <option value="U">Madhya Maharashtra</option>
        <option value="V">Maratwada</option>
        <option value="W">Nagaland, Manipur, Mizoram, Tripura</option>
        <option value="X">North Interior Karnataka</option>
        <option value="Y">Orissa</option>
        <option value="Z">Punjab</option>
        <option value="AA">Rayalseema</option>
        <option value="AB">Saurashtra, Kutch, Diu</option>
        <option value="AC">South Interior Karnataka</option>
        <option value="AD">Sub-Himalayan, West Bengal, Sikkim</option>
        <option value="AE">Tamil Nadu, Pondicherry</option>
        <option value="AF">Telengana</option>
        <option value="AG">Uttaranchal</option>
        <option value="AH">Vidarbha</option>
        <option value="AI">West Madhya Pradesh</option>
        <option value="AJ">West Rajasthan</option>
        <option value="AK">West Uttar Pradesh</option>
    </select>
</div>

<div id="chart">
</div>

Comments