UNPKG

geography-apis-sdk

Version:

SDK for making requests to Geography APIs

91 lines (79 loc) 3.25 kB
<!DOCTYPE html> <html> <head> <title>Country Search App</title> <style> .result { margin-bottom: 10px; padding: 10px; border: 1px solid #ccc; } </style> </head> <body> <h1>Country Search App</h1> <input type="text" id="searchInput" placeholder="Enter country name"> <div id="searchResults"></div> <script src="./dist/geography-apis-sdk.bundle.js"></script> <script> const apiKey = 'YOUR_API_KEY'; const apiHost = 'geography4.p.rapidapi.com'; const baseURL = 'https://geography4.p.rapidapi.com'; //const baseURL = 'http://localhost:8080'; const countrySDK = new GeographyAPISDK(apiKey, apiHost, baseURL); // Get the necessary elements const searchInput = document.getElementById('searchInput'); const searchResults = document.getElementById('searchResults'); // Function to render the search results function renderResults(countries) { searchResults.innerHTML = ''; if (countries.length === 0) { searchResults.innerHTML = 'No results found.'; } else { countries.forEach(country => { const resultDiv = document.createElement('div'); resultDiv.classList.add('result'); resultDiv.innerHTML = ` <h3>${country.name?.common || 'N/A'}</h3> <p>Capital: ${country?.capital?.[0]?.name || 'N/A'}</p> <p>Population: ${country.population || 'N/A'}</p> <hr>`; searchResults.appendChild(resultDiv); }); } } // Function to handle search async function handleSearch() { const searchName = searchInput.value.trim(); if (searchName !== '') { try { const options = { headers: { 'Content-Type': 'application/json' }, params: { exactMatch: false, includeNativeName: false, fields: 'name,capital,population', sortBy: 'name', sortOrder: 'asc', limit: 10, offset: 0 }, }; const countries = await countrySDK.searchCountriesByName(searchName, options); console.log(".....>>>" +countries.headers.get('x-total-count')); renderResults(countries.body); } catch (error) { console.error('Error:', error); searchResults.innerHTML = `An error occurred: ${error.message}`; } } else { searchResults.innerHTML = ''; } } // Add input event listener to trigger search searchInput.addEventListener('input', handleSearch); </script> </body> </html>