Setting the file. One moment.
Chapter 12 · Mapbox Search Integration
Subchapter 12.6
references/pitfalls.mdMarkdown3 KBView on GitHub
Problem:
input.addEventListener('input', (e) => {
performSearch(e.target.value); // API call on EVERY keystroke!
});Impact:
Solution: Always debounce (see Best Practices #1)
Problem:
// No session token = each request charged separately
fetch('...suggest?q=query&access_token=xxx');Impact:
Solution: Use session tokens (see Best Practices #2)
Problem:
// Searching globally for "Paris"
{
q: 'Paris';
} // Paris, France? Paris, Texas? Paris, Kentucky?Impact:
Solution:
// Much better
{ q: 'Paris', country: 'US', proximity: user_location }Problem:
<!-- Tiny touch targets -->
<div style="height: 20px; padding: 2px;">Search result</div>Impact:
Solution:
.search-result {
min-height: 48px; /* Android minimum */
padding: 12px;
margin: 4px 0;
}Problem:
// Just shows empty container
displayResults([]); // User sees blank space - is it loading? broken?Impact:
Solution:
if (results.length === 0) {
showMessage('No results found. Try a different search term.');
}Problem:
// No timeout = waits forever on slow network
await fetch(searchUrl);Impact:
Solution:
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);
fetch(searchUrl, { signal: controller.signal }).finally(() => clearTimeout(timeout));Problem:
// Treating all results the same
displayResult(result.name); // But is it an address? POI? Region?Impact:
Solution:
function handleResult(result) {
const type = result.feature_type;
if (type === 'poi') {
map.flyTo({ center: coords, zoom: 17 }); // Close zoom
addPOIMarker(result);
} else if (type === 'address') {
map.flyTo({ center: coords, zoom: 16 });
addAddressMarker(result);
} else if (type === 'place') {
map.flyTo({ center: coords, zoom: 12 }); // Wider view for city
}
}Problem:
// Fast typing: "san francisco"
// API responses arrive out of order:
// "san f" results arrive AFTER "san francisco" resultsImpact:
Solution:
let searchCounter = 0;
async function performSearch(query) {
const currentSearch = ++searchCounter;
const results = await fetchResults(query);
// Only display if this is still the latest search
if (currentSearch === searchCounter) {
displayResults(results);
}
}