Reputation: 35
I have markers on a Google Map with dropdown filters, and these filters work perfectly well individually. However, I want the filter to consider all three drop-down lists at once.
Here is my code: https://jsfiddle.net/h4cv57tb/
Somehow the 3 filter functions should be merged, but unfortunately I have no idea how to ...
Here are the filter functions which should be merged:
//Filter by type
filterMarkers = function(category) {
for (i = 0; i < gmarkers1.length; i++) {
marker = gmarkers1[i];
// If is same category or category not picked
if (marker.category == category || category.length === 0) {
marker.setVisible(true);
}
// Categories don't match
else {
marker.setVisible(false);
}
}
}
//FILTER by ripening time
filterMarkersEres = function(eres) {
for (i = 0; i < gmarkers1.length; i++) {
marker = gmarkers1[i];
var ereshonap = marker.eres;
// If is same category or category not picked
if (ereshonap.includes(parseInt(eres)) || eres.length === 0) { //
marker.setVisible(true);
}
// Categories don't match
else {
marker.setVisible(false);
}
}
}
//FILTER by place
filterMarkersHely_tipus = function(hely_tipus) {
for (i = 0; i < gmarkers1.length; i++) {
marker = gmarkers1[i];
// If is same category or category not picked
if (marker.hely_tipus == hely_tipus || hely_tipus.length === 0) {
marker.setVisible(true);
}
// Categories don't match
else {
marker.setVisible(false);
}
}
}
Thanks in advance for your help!
Upvotes: 0
Views: 89
Reputation: 180
Make sure you look at where there is duplicate code and simply combine areas that are different, if feasible. To combine these functions into a single one just combine the if conditions together.
filterMarkers = function(category = null, eres = null, hely_tipus = null) {
for (i = 0; i < gmarkers1.length; i++) {
marker = gmarkers1[i];
ereshonap = marker.eres;
visible = false;
if (category){
if (marker.category == category || category.length === 0) {
visible = true;
}
}
if (eres) {
if (ereshonap.includes(parseInt(eres)) || eres.length === 0) {
visible = true;
}
}
if (hely_tipus) {
if(marker.hely_tipus == hely_tipus) {
visible = true;
}
}
if (visible) {
marker.setVisible(true);
} else {
marker.setVisible(false);
}
}
}
Upvotes: 1