У меня есть одна html-страница для отображения трех географических диаграмм, но я не знаю, как сгруппировать функции вместе, чтобы я мог сократить код и не дублировать его (и не уверен, возможно ли это)
например У меня есть эта дублированная функция (3 функции на 3 графика)
Это для четкого цвета на карте
//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 : </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 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
}
};а полный код - здесь
можно ли объединить их вместе для нескольких диаграмм?
Спасибо за помощь.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


уверен, что это возможно.
единственная разница, на самом деле, - это идентификатор <div>, который должен использовать диаграмма.
см. следующий рабочий фрагмент,
здесь я использую переменную для изменения идентификатора <div> -> 'colormap' + id
все запросы вызывают одну и ту же функцию -> handleQueryResponseTR
РЕДАКТИРОВАТЬ
вместо увеличения идентификатора div, давайте передадим его функции. это обеспечит отображение данных на правильной диаграмме.
function handleQueryResponseTR(response1, divId) {
...
var chart1 = new google.visualization.GeoChart(document.getElementById(divId));
и...
query1.send(function (response) {
handleQueryResponseTR(response, 'colormap1');
});
query2.send(function (response) {
handleQueryResponseTR(response, 'colormap2');
});
query3.send(function (response) {
handleQueryResponseTR(response, 'colormap3');
});
см. следующий обновленный фрагмент ...
<!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 : </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.info(regions[i]);
}
}
if ((defaultRegion === null) && (regions.length > 0)) {
defaultRegion = regions[0];
defaultRegion.checked = true;
}
drawChart({
target: defaultRegion
});
//console.info(drawChart);
// radio on 'click' handler
function drawChart(sender) {
options1.region = null;
if (sender.target.value !== 'all') {
options1.region = sender.target.value;
//console.info(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>Привет - данные отображаются правильно на картах, но функция щелчка кажется неправильной ... например, я щелкнул по России, затем она перешла на страницу Беларуси - и иногда функция щелчка не работает вообще - также цвета неправильные. кстати, я очень ценю вашу помощь. Большое спасибо. вы все еще можете проверить sagisepr.com/CLEANMAPS/shorten%20version%20not%20working/…, и правильный, который должен быть, находится здесь; sagisepr.com/CLEANMAPS/takeback_policymap_current.html
Привет - на самом деле это работает неправильно - если вы можете посмотреть на эту ссылку: sagisepr.com/CLEANMAPS/shorten%20version%20not%20working/… - вы увидите, что карты отображают неправильные данные - например, на WEEE вместо этого отображаются данные о батареях, и они меняются каждый раз, когда я обновляю страницу