简体   繁体   中英

Geochart: define one js function for multiple charts?

I have one html page to display three geocharts but I don't know how to group function together so I can shorten the code and not duplicate it (and not sure if it's possible)

for ex. I have these duplicated function (3 functions for 3 charts)

This is for distinct color on the map

 //assign color to colorValues var colorNames = []; colorValues.forEach(function(value) { if (value <= 1) { //1(E)PR framework legislation in place// colorNames.push('#ffff57'); } else if ((value > 1) && (value <= 2)) { //2(E)PR legislation in planning// colorNames.push('#ffff9b'); } else if ((value > 2) && (value <= 3)) { //3//Alternative model with producer funding colorNames.push('#3FE5C9'); } else if ((value > 3) && (value <= 4)) { //4// Alternative model – not producer funded colorNames.push('#B97A57'); } else if ((value > 4) && (value <= 5)) { //5// Competing organisation model colorNames.push('#85C9F3'); } else if ((value > 5) && (value <= 6)) { //6//Competing organisation model with coordination centre colorNames.push('#3DA9EC'); } else if ((value > 6) && (value <= 7)) { //7/ Competing organisation model with eco-tax back-up colorNames.push('#DFA6FF'); } else if ((value > 7) && (value <= 8)) { //8 Different EPR models by product category or other criteria colorNames.push('#99F1E2'); } else if ((value > 8) && (value <= 9)) { //9 None - but municipalities responsible for sep. collection colorNames.push('#9edae5'); } else if ((value > 9) && (value <= 10)) { //10 None - but other obligations for producers colorNames.push('#d1d19d'); } else if ((value > 10) && (value <= 11)) { //11 Other model colorNames.push('#9edae5'); } else if ((value > 11) && (value <= 12)) { //12 Recycler centric model colorNames.push('#9edae5'); } else if ((value > 12) && (value <= 13)) { //13 Single organisation model colorNames.push('#98df8a'); } else if ((value > 15) && (value <= 16)) { //16 under other jurisdiction colorNames.push('#e2dace'); } else { colorNames.push('#ffaf87'); } }); 

This is for tooltips

 var view1 = new google.visualization.DataView(data1); view1.setColumns([16, 15, { type: 'string', role: 'tooltip', properties: { html: true }, calc: function(dt, row) { var country = dt.getFormattedValue(row, 5) var policy = dt.getFormattedValue(row, 6) var dataname = dt.getFormattedValue(row, 8) var dropname = dt.getFormattedValue(row, 9) var formatter = new google.visualization.DateFormat({ pattern: "MMMM yyyy" }); var startdate = formatter.formatValue(dt.getValue(row, 10)); //var startdate = dt.getFormattedValue(row, 10) var comment = dt.getFormattedValue(row, 12) //colorValues.push(dt.getFormattedValue(row, 6)) if (dropname != 'EPR policy not in place') { return '<br><div id="country">' + country + " - " + policy + '<br><br></div> ' + '<div id="header1">Dominant (E)PR policy model:<br></div>' + '<div id="dropname">' + dropname + '<br><br></div>' + '<div id ="header2">Since :&nbsp;</div><div id="date">' + startdate + '</div><br><br><br>' + '<div id ="comment">' + comment + '<\\/div>' } else { return '<br><div id="country">' + country + " - " + policy + '<br><br></div> ' + '<div id="header1">Dominant (E)PR policy model:<br></div>' + '<div id="dropname">' + dropname + '<br><br></div>' } }, } ]); 

this is for charts properties

 var options1 = { colorAxis: { colors: colorNames, values: colorValues }, backgroundColor: { fill: '#FFF' }, datalessRegionColor: '#F5F0E7', displayMode: 'regions', legend: 'none', enableRegionInteractivity: 'true', resolution: 'countries', //sizeAxis: {minValue: 1, maxValue:1,minSize:10, maxSize: 10}, region: 'null', keepAspectRatio: false, width: 800, height: 480, tooltip: { isHtml: 'true', textStyle: { color: '#444444' }, showTitle: false } }; 

and the complete code is here

is it possible to combine them together for multiple charts?

thanks for helping.

sure it's possible.
the only difference, really, is the id of the <div> the chart needs to use.

see following working snippet,
here, I'm using a variable to change the id of the <div> --> 'colormap' + id
all queries call the same function --> handleQueryResponseTR

EDIT

instead of incrementing the div's id, let's pass it to the function instead.
this will ensure the data is shown on the correct chart.

function handleQueryResponseTR(response1, divId) {
  ...
    var chart1 = new google.visualization.GeoChart(document.getElementById(divId));

and...

    query1.send(function (response) {
      handleQueryResponseTR(response, 'colormap1');
    });
    query2.send(function (response) {
      handleQueryResponseTR(response, 'colormap2');
    });
    query3.send(function (response) {
      handleQueryResponseTR(response, 'colormap3');
    });

see following updated snippet...

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>MAPS 1 MENU</title> <link rel="stylesheet" href="styles.css"> </head> <body style="width:850px"> <script type='text/javascript' src='https://www.gstatic.com/charts/loader.js'></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> google.charts.load('current', { packages: ["geochart"], mapsApiKey: 'AIzaSyB5KSY9RtRmKv3Kzf1hsdzzRGZktpsUqEQ' }); google.charts.setOnLoadCallback(drawRegionsMap); var data1; var data2; var data3; $(function() { $(".preload").fadeOut(4500, function() { $(".content").fadeIn(1000); }); }); function handleQueryResponseTR(response1, divId) { if (response1.isError()) { alert('Error in query: ' + response1.getMessage() + ' ' + response1.getDetailedMessage()); return; } data1 = response1.getDataTable(); var colorValues = []; var numRows = data1.getNumberOfRows(); for (var i = 0; i < numRows; i++) { colorValues.push(parseInt(data1.getValue(i, 15))); } //assign color to colorValues var colorNames = []; colorValues.forEach(function(value) { if (value <= 1) { //1(E)PR framework legislation in place// colorNames.push('#ffff57'); } else if ((value > 1) && (value <= 2)) { //2(E)PR legislation in planning// colorNames.push('#ffff9b'); } else if ((value > 2) && (value <= 3)) { //3//Alternative model with producer funding colorNames.push('#3FE5C9'); } else if ((value > 3) && (value <= 4)) { //4// Alternative model – not producer funded colorNames.push('#B97A57'); } else if ((value > 4) && (value <= 5)) { //5// Competing organisation model colorNames.push('#85C9F3'); } else if ((value > 5) && (value <= 6)) { //6//Competing organisation model with coordination centre colorNames.push('#3DA9EC'); } else if ((value > 6) && (value <= 7)) { //7/ Competing organisation model with eco-tax back-up colorNames.push('#DFA6FF'); } else if ((value > 7) && (value <= 8)) { //8 Different EPR models by product category or other criteria colorNames.push('#99F1E2'); } else if ((value > 8) && (value <= 9)) { //9 None - but municipalities responsible for sep. collection colorNames.push('#9edae5'); } else if ((value > 9) && (value <= 10)) { //10 None - but other obligations for producers colorNames.push('#d1d19d'); } else if ((value > 10) && (value <= 11)) { //11 Other model colorNames.push('#9edae5'); } else if ((value > 11) && (value <= 12)) { //12 Recycler centric model colorNames.push('#9edae5'); } else if ((value > 12) && (value <= 13)) { //13 Single organisation model colorNames.push('#98df8a'); } else if ((value > 15) && (value <= 16)) { //16 under other jurisdiction colorNames.push('#e2dace'); } else { colorNames.push('#ffaf87'); } }); var view1 = new google.visualization.DataView(data1); view1.setColumns([16, 15, { type: 'string', role: 'tooltip', properties: { html: true }, calc: function(dt, row) { var country = dt.getFormattedValue(row, 5) var policy = dt.getFormattedValue(row, 6) var dataname = dt.getFormattedValue(row, 8) var dropname = dt.getFormattedValue(row, 9) var formatter = new google.visualization.DateFormat({ pattern: "MMMM yyyy" }); var startdate = formatter.formatValue(dt.getValue(row, 10)); //var startdate = dt.getFormattedValue(row, 10) var comment = dt.getFormattedValue(row, 12) //colorValues.push(dt.getFormattedValue(row, 6)) if (dropname != 'EPR policy not in place') { return '<br><div id="country">' + country + " - " + policy + '<br><br></div> ' + '<div id="header1">Dominant (E)PR policy model:<br></div>' + '<div id="dropname">' + dropname + '<br><br></div>' + '<div id ="header2">Since :&nbsp;</div><div id="date">' + startdate + '</div><br><br><br>' + '<div id ="comment">' + comment + '<\\/div>' } else { return '<br><div id="country">' + country + " - " + policy + '<br><br></div> ' + '<div id="header1">Dominant (E)PR policy model:<br></div>' + '<div id="dropname">' + dropname + '<br><br></div>' } }, } ]); var chart1 = new google.visualization.GeoChart(document.getElementById(divId)); google.visualization.events.addListener(chart1, 'select', function() { var selection = chart1.getSelection(); var dropname = data1.getValue(selection[0].row, 9); //alert(dropname); if (dropname != 'EPR policy not in place') { var cnid = data1.getValue(selection[0].row, 0); var polid = data1.getValue(selection[0].row, 1); var strid = data1.getValue(selection[0].row, 2); var sid = (strid) - 1; var statecode = data1.getValue(selection[0].row, 4); //if (selection.length > 0 && dropname != '(E)PR policy in planning' ) { //http://www.sagisepr.com/country.php?country=21&polsel=1&sid=17&statecode=AR //http://www.sagisepr.com/v3/country.php?country=38&statecode=US-ME&t=2&polsel=1&sid=1 window.open("http://www.sagisepr.com/v3/country.php?country=" + cnid + "&statecode=" + statecode + "&t=2" + "&polsel=" + polid + "&sid=" + sid); } }); var options1 = { colorAxis: { colors: colorNames, values: colorValues }, backgroundColor: { fill: '#FFF' }, datalessRegionColor: '#F5F0E7', displayMode: 'regions', legend: 'none', enableRegionInteractivity: 'true', resolution: 'countries', //sizeAxis: {minValue: 1, maxValue:1,minSize:10, maxSize: 10}, region: 'null', keepAspectRatio: false, width: 800, height: 480, tooltip: { isHtml: 'true', textStyle: { color: '#444444' }, showTitle: false } }; //radio button // 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]; //console.log(regions[i]); } } if ((defaultRegion === null) && (regions.length > 0)) { defaultRegion = regions[0]; defaultRegion.checked = true; } drawChart({ target: defaultRegion }); //console.log(drawChart); // radio on 'click' handler function drawChart(sender) { options1.region = null; if (sender.target.value !== 'all') { options1.region = sender.target.value; //console.log(sender.target.value); } chart1.draw(view1, options1); } } function drawRegionsMap() { var query1 = new google.visualization.Query("https://docs.google.com/spreadsheets/d/1ysbR58fP12YRfrvWtYoJRrLnbCwooR7kTjVldz-pWJc/edit?usp=sharing"); query1.setQuery('select * where N = "Y" and G="WEEE" and O="Country" and H="Take back policy model"'); //bat sheet var query2 = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1ysbR58fP12YRfrvWtYoJRrLnbCwooR7kTjVldz-pWJc/edit?usp=sharing'); query2.setQuery('select * where N="Y" and G="Batteries" and O="Country" and H="Take back policy model"'); //pack sheet var query3 = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1ysbR58fP12YRfrvWtYoJRrLnbCwooR7kTjVldz-pWJc/edit?usp=sharing'); query3.setQuery('select * where N="Y" and G="Packaging" and O="Country" and H="Take back policy model"'); query1.send(function (response) { handleQueryResponseTR(response, 'colormap1'); }); query2.send(function (response) { handleQueryResponseTR(response, 'colormap2'); }); query3.send(function (response) { handleQueryResponseTR(response, 'colormap3'); }); } </script> <div class="content"> <div id="chartwithoverlay1"> <div id="overlay1">WEEE</div> <div id="regionbutton"> <div id="radio1"><input type="radio" name="region" id="all" value="all" /><label for="all">All</label></div> <div id="radio2"><input type="radio" name="region" id="africa" value="002" /><label for="africa">Africa</label></div> <div id="radio4"><input type="radio" name="region" id="americas" value="013" /><label for="americas">Central America</label></div> <div id="radio5"><input type="radio" name="region" id="americas" value="005" /><label for="americas">South America</label></div> <div id="radio6"><input type="radio" name="region" id="europe" value="150" /><label for="europe">Europe</label></div> <div id="radio7"><input type="radio" name="region" id="asia" value="142" /><label for="asia">Asia/Middle East</label></div> </div> <div id='colormap1'> </div> </div> <div id="chartwithoverlay2"> <div id="overlay2">Batteries</div> <div id='colormap2'> </div> </div> <div id="chartwithoverlay3"> <div id="overlay3">Packaging</div> <div id='colormap3'> </div> </div> <div id="img"> <img src="legend.png" alt="" /> </div> </div> <div class="preload"> <img src="http://i.imgur.com/KUJoe.gif"> </div> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM