World Cities API Test
by Jayson Buquia
HTML
<div class="combobox">
<input type="text" class="search_place">
<select name="place" id="">
<option value=""></option>
</select>
</div>
SCSS
.combobox {
display: flex;
flex-flow: column nowrap;
width: 300px;
padding: 10px;
input {
height: 20px;
margin-bottom: 10px;
}
select {
height: 20px;
margin-bottom: 10px;
}
}
JavaScript
const input = document.querySelector('.search_place');
const select = document.querySelector('select');
const option = select.firstElementChild.cloneNode();
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
async function fetchPlaces(term) {
const request = await fetch(`https://devru-latitude-longitude-find-v1.p.rapidapi.com/latlon.php?location=${term}`, {
headers: {
"X-RapidAPI-Host": "devru-latitude-longitude-find-v1.p.rapidapi.com",
"X-RapidAPI-Key": "db6bf170a9msh26128878263f969p161af2jsn48660039fdaa"
},
method: 'GET',
});
const { Results } = await request.json();
return Results;
}
async function searchPlace(term) {
const matches = await fetchPlaces(term);
// Empty out options
select.innerHTML = '';
matches.forEach(({name, c, l, ll}) => {
const optionTemplate = option.cloneNode();
optionTemplate.value = `${name};${c};${l};${ll}`;
optionTemplate.textContent = `${name}, ${c}`;
select.appendChild(optionTemplate);
});
}
function init() {
input.addEventListener('keyup', debounce(() => {
console.log('proceed');
if ( input.value ) {
searchPlace(input.value);
}
}, 300));
select.addEventListener('change', _ => console.log(select.value))
}
init();