From 640c6cd655d50c8d6d851c4a5a2f754308acc179 Mon Sep 17 00:00:00 2001 From: codwiz23 Date: Sun, 5 Oct 2025 23:06:39 -0400 Subject: [PATCH 1/2] complete project --- css/style.css | 46 +++++++++ index.html | 71 ++++++++++++++ js/main.js | 253 ++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 370 insertions(+) create mode 100644 css/style.css create mode 100644 index.html create mode 100644 js/main.js diff --git a/css/style.css b/css/style.css new file mode 100644 index 0000000..b992274 --- /dev/null +++ b/css/style.css @@ -0,0 +1,46 @@ +* { + box-sizing: border-box; +} +html{ + font-size: 62.5%; +} +body{ + display: flex; + flex-direction: column; + align-items: center; + font-size: 2rem; + background-color: antiquewhite; +} +div { + display: flex; + flex-wrap: wrap; + flex: 1; + gap: 1em; + justify-content: center; +} + +article { + width: 30%; + border: 2px solid; + text-align: center; + font-size: 2rem; + margin-top: 2%; + padding: 2%; + background-color: lightgray; +} +article h4{ + height: 50px; + margin-top: 0.5%; +} +article img { + width: 70%; +} + +article a { + color: black; + text-decoration: none; +} +#myChart { + width: 300px !important; + height: 300px !important; +} diff --git a/index.html b/index.html new file mode 100644 index 0000000..28c5eff --- /dev/null +++ b/index.html @@ -0,0 +1,71 @@ + + + + + + + + + + News API Demo + + + +

Welcome to my News API

+
+ + + + + + + + +
+ +

Results:

+

+ + + + + \ No newline at end of file diff --git a/js/main.js b/js/main.js new file mode 100644 index 0000000..0d92002 --- /dev/null +++ b/js/main.js @@ -0,0 +1,253 @@ +/** + * get the country and category of news and then use the city info to get population + */ + +/** + * this is to see if there is any connection between the population density and crime rates + */ + +document.querySelector('button').addEventListener('click', search) + +function search() { + reset() + + const newsApiKey = 'c9d5229cea5b6863d3bd277a6c2ede67' + + + let keyWord; + let country; + //https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript + let selectCountry = document.getElementById("country"); + let selectCategory = document.getElementById("category"); + let textCountry = selectCountry.options[selectCountry.selectedIndex].text; + // let textCategory = selectCategory.options[selectCategory.selectedIndex].text.toLowerCase(); + let popCountry = textCountry + switch (textCountry) { + case 'Australia': + country = 'au'; + break; + case 'Brazil': + country = 'br'; + break; + case 'Canada': + country = 'ca'; + break; + case 'China': + country = 'cn'; + break; + case 'Egypt': + country = 'eg'; + break; + case 'France': + country = 'fr'; + break; + case 'Germany': + country = 'de'; + break; + case 'Greece': + country = 'gr'; + break; + case 'India': + country = 'in'; + break; + case 'Ireland': + country = 'ie'; + break; + case 'Italy': + country = 'it'; + break; + case 'Japan': + country = 'jp'; + break; + case 'Netherlands': + country = 'nl'; + break; + case 'Norway': + country = 'no'; + break; + case 'Pakistan': + country = 'pk'; + break; + case 'Peru': + country = 'pe'; + break; + case 'Philippines': + country = 'ph'; + break; + case 'Portugal': + country = 'pt'; + break; + case 'Romania': + country = 'ro'; + break; + case 'Russian Federation': + country = 'ru'; + break; + case 'Singapore': + country = 'sg'; + break; + case 'Sweden': + country = 'se'; + break; + case 'Switzerland': + country = 'ch'; + break; + case 'Taiwan': + country = 'tw'; + break; + case 'Ukraine': + country = 'ua'; + break; + case 'United Kingdom': + country = 'gb'; + break; + case 'United States': + country = 'us'; + break; + default: + console.log('Error: Unknown country'); + country = 'us'; + break; + } + + // switch (textCategory) { + // case 'general': + // category = 'general' + // break; + // case 'world': + // category = 'world' + // break; + // case 'business': + // category = 'business' + // break; + // case 'technology': + // category = 'technology' + // break; + // case 'entertainment': + // category = 'entertainment' + // break; + // case 'science': + // category = 'science' + // break; + // case 'sports': + // category = 'sports' + // break; + // case 'health': + // category = 'health' + // break; + // case 'nation': + // category = 'nation' + // break; + // default: + // category = 'null' + // console.log('Error: Uknown category') + // break; + // } + + + console.log(textCountry) + // console.log(textCategory) + keyWord = document.querySelector('input').value.toLowerCase() + const urlPop = `https://d6wn6bmjj722w.population.io:443/1.0/population/2025/${popCountry}/` + const url = `https://gnews.io/api/v4/search?q=${keyWord}&lang=en&max=9&country=${country}&apikey=${newsApiKey}` + + let results = document.querySelector('h3') + fetch(urlPop) + .then(res => res.json()) + + .then(data => { + console.log(data) + let totalFem = 0; + let totalMale = 0; + + data.forEach(element => { + totalFem += Number(element.females); + totalMale += Number(element.males); + }); + + let sum = totalFem + totalMale; + //https://stackoverflow.com/questions/2901102/how-to-format-a-number-with-commas-as-thousands-separators + let popString = sum.toLocaleString() + + + //used this as a template and tweaked it for my needs + //https://www.w3schools.com/js/tryit.asp?filename=trychartjs_pie + const malePercent = totalMale / sum * 100 + const femPercent = totalFem / sum * 100 + const xValues = ["Male", "Female"]; + const yValues = [malePercent, femPercent]; + const barColors = [ + "#1d21dcff", + "#c018f3ff", + ] + + const ctx = document.getElementById('myChart') + new Chart(ctx, { + type: "pie", + data: { + labels: xValues, + datasets: [{ + backgroundColor: barColors, + data: yValues + }] + }, + options: { + title: { + display: true, + text: `${textCountry}'sPopulation Distribution Graph` + } + } + }); + + console.log("First element:", data[0]); + console.log("Total population:", sum); + let pop = document.querySelector('p') + pop.innerText = `Total population: ${popString}` + fetch(url) + .then(res => res.json()) + .then(data => { + console.log(data) + article = data.articles; + if (data.articles.length < 1) { + results.innerText = 'There is no news.' + } else { + const container = document.createElement('div') + article.forEach(element => { + const art = document.createElement('article') + art.innerHTML = `

${element.title}

${element.description}

` + container.appendChild(art) + }); + document.body.appendChild(container) + } + + }) + .catch(err => { + console.log(`error ${err}`) + }) + }) + + .catch(err => { + console.log(`error ${err}`) + }) + + +} +function reset() { + const info = document.querySelectorAll('article') + if (info) { + info.forEach(element => { + //https://developer.mozilla.org/en-US/docs/Web/API/Element/remove + element.remove() + }) + } + //used chatGPT to help me remove the graph with each new search + const ctx = document.getElementById('myChart'); + if (ctx) { + ctx.remove(); // remove old canvas + let newCanvas = document.createElement('canvas'); + newCanvas.id = 'myChart'; + document.body.appendChild(newCanvas); + } + let results = document.querySelector('h3') + results.innerText = "Results:" +} \ No newline at end of file From 8e4cff8e8a53389717825f1261ea7d04cb93cf59 Mon Sep 17 00:00:00 2001 From: Abdirahman Mohamed <144724786+abdirxhmxn@users.noreply.github.com> Date: Fri, 7 Nov 2025 10:08:12 -0500 Subject: [PATCH 2/2] Update README.md --- README.md | 87 +++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 71 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 83ce771..1dee343 100644 --- a/README.md +++ b/README.md @@ -1,22 +1,77 @@ -# 📊 Project: Complex API 2 +# 📰 News Search with Population Insights -### Goal: Use data returned from one api to make a request to another api and display the data returned +A web application that combines news search with demographic data visualization. Search for news articles by keyword and country, then see population statistics for that country displayed in an interactive pie chart. -### How to submit your code for review: +## What It Does -- Fork and clone this repo -- Create a new branch called answer -- Checkout answer branch -- Push to your fork -- Issue a pull request -- Your pull request description should contain the following: - - (1 to 5 no 3) I completed the challenge - - (1 to 5 no 3) I feel good about my code - - Anything specific on which you want feedback! +This project fetches news articles based on your search criteria and simultaneously retrieves population data for the selected country. You'll see: + +- Up to 9 recent news articles matching your keyword +- Total population count for the selected country +- A pie chart showing the male/female population distribution +- Clickable article cards with images and descriptions + +## Technologies Used + +- **HTML/CSS/JavaScript** - Core web technologies +- **GNews API** - Fetches news articles from around the world +- **Population.io API** - Retrieves demographic data by country +- **Chart.js** - Creates the population distribution pie chart + +## How to Use + +1. Enter a keyword you want to search for (e.g., "technology", "sports", "climate") +2. Select a country from the dropdown menu +3. Click the "Search" button +4. Browse the news results and view the population data + +The app currently supports 27 countries including the US, UK, Canada, Japan, Germany, and more. + +## Setup Instructions + +1. Clone this repository to your local machine +2. Open `index.html` in your web browser +3. Start searching for news! + +**Note:** The API key is included in the code for demonstration purposes. In a production environment, you'd want to secure this on a backend server. + +## Features + +- **Responsive Design** - Articles display in a flexible grid layout +- **External Links** - Click any article to read the full story on the source website +- **Fresh Data** - Each search clears previous results and generates a new chart +- **Visual Analytics** - Instantly see gender distribution for your selected country + +## Project Structure -Example: ``` -I completed the challenge: 5 -I feel good about my code: 4 -I'm not sure if my constructors are setup cleanly... +├── index.html # Main HTML structure +├── css/ +│ └── style.css # Styling and layout +└── js/ + └── main.js # API calls and DOM manipulation ``` + +## Known Limitations + +- The category selector is currently commented out but could be re-enabled +- Some news sources may not provide images +- Population API data is for the year 2025 +- Limited to 9 articles per search (API constraint) + +## Future Improvements + +- Add error handling for failed API requests +- Implement loading indicators during data fetch +- Add filtering by news category +- Include more demographic data visualizations +- Add pagination for viewing more than 9 articles + +## API Credits + +- News data provided by [GNews.io](https://gnews.io/) +- Population data from [Population.io](http://population.io/) + +--- + +Built as a learning project to practice working with multiple APIs and data visualization.