Reputation: 267
I wanted to incorporate Google Geocharts on my site, so I included the code from their guidelines and it's all working smoothly.
However, I would like to add a couple of radio buttons to the site, which would control which region is being shown on the chart.
I understand that I need to change the variable region from below code from '150' to the value of the radio button when I click it, but I don't have much experience with Javascript, and would love some pointers how I can do that.
Thank you.
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity'],
['Germany', 200],
['United States', 300],
['Brazil', 400],
['Canada', 500],
['France', 600],
['RU', 700]
]);
var options = {
region: '150',
};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="regions_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
Upvotes: 1
Views: 464
Reputation: 61275
changing the chart's options
based on radio input is pretty straightforward
just need to find the region inputs and add a click handler
then get the value of the radio that was clicked
see following working snippet, which uses the first radio by default...
google.charts.load('current', {
callback: drawRegionsMap,
packages: ['geochart']
});
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity'],
['Germany', 200],
['United States', 300],
['Brazil', 400],
['Canada', 500],
['France', 600],
['RU', 700],
['Tunisia', 220],
['Cameroon', 420]
]);
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
var options = {};
// init regions
var regions = document.getElementsByName('region');
var defaultRegion = null;
for (var i = 0; i < regions.length; i++) {
regions[i].addEventListener('click', drawChart, false);
if (regions[i].checked) {
defaultRegion = regions[i];
}
}
if ((defaultRegion === null) && (regions.length > 0)) {
defaultRegion = regions[0];
defaultRegion.checked = true;
}
drawChart({target: defaultRegion});
// radio on 'click' handler
function drawChart(sender) {
options.region = null;
if (sender.target.value !== 'all') {
options.region = sender.target.value;
}
chart.draw(data, options);
}
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div><input type="radio" name="region" id="all" value="all" /><label for="all">All</label></div>
<div><input type="radio" name="region" id="africa" value="002" /><label for="africa">Africa</label></div>
<div><input type="radio" name="region" id="americas" value="019" /><label for="americas">Americas</label></div>
<div><input type="radio" name="region" id="europe" value="150" /><label for="europe">Europe</label></div>
<div id="regions_div"></div>
Upvotes: 1