From c186275bdbea9940e4c17b0d4f990139c8e44860 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arne=20Schl=C3=BCter?= Date: Sat, 7 Feb 2015 21:37:11 +0100 Subject: [PATCH] Implement filter logic --- static/css/style.css | 1 + static/js/main.js | 59 +++++++++++++++++++++++++++++++++++++++----- views/index.tpl | 1 - 3 files changed, 54 insertions(+), 7 deletions(-) diff --git a/static/css/style.css b/static/css/style.css index 0e0b9eb..96554a8 100644 --- a/static/css/style.css +++ b/static/css/style.css @@ -67,6 +67,7 @@ body { .category-filter li { margin: 12px 0; opacity: .5; + transition: opacity .3s ease; } .category-filter li.active { diff --git a/static/js/main.js b/static/js/main.js index 3c33a9d..df46b97 100644 --- a/static/js/main.js +++ b/static/js/main.js @@ -21,9 +21,35 @@ console.log('Got data successfully!'); response = data; - displayAll(); + displayMarkers(response); }); + // event handling / user interaction + var $categoryList = $('.category-filter'); + + function getActiveCategories ($li) { + var activeCategories = []; + $categoryList.children().each(function () { + var $li = $(this); + if ($li.hasClass('active')) + activeCategories.push($li[0].classList[0]) + }); + + return activeCategories; + } + + $categoryList.on('click', 'a', function (e) { + $(this).parent().toggleClass('active'); + + var categories = getActiveCategories(); + var incidents = filterByCategories(categories); + displayMarkers(incidents); + + e.preventDefault(); + e.stopPropagation(); + return false; + }) + // logic for drawing follows var markers = []; @@ -39,11 +65,32 @@ } /** - * Display all incidents at once + * Clear the map and render new markers + * @param {Array[Object]} data The incidents to be shown */ - function displayAll () { - for (var i = 0, l = response.length; i < l; i++) { - markers.push(createMarker(response[i]).bindPopup(response[i].description)); - } + function displayMarkers (incidents) { + markers.forEach(function (marker) { + map.removeLayer(marker); + }); + markers = []; + + incidents.forEach(function (incident) { + markers.push(createMarker(incident).bindPopup(incident.description)); + }); + } + + /** + * Returns only the incidents which fall into the given categories + * @param {Array[String]} categories + * @return {Arreay[Obect]} + */ + function filterByCategories (categories) { + return response.filter(function (incident) { + for (var i = 0, l = incident.categories.length; i < l; i++) + if (categories.indexOf(incident.categories[i]) !== -1) + return true; + + return false; + }); } })(); diff --git a/views/index.tpl b/views/index.tpl index 46fd02c..4faf2a8 100644 --- a/views/index.tpl +++ b/views/index.tpl @@ -30,7 +30,6 @@ -