Public
Edited
Nov 27, 2022
3 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
// will be populated when a suggested result is clicked on.
mutable selectedLocation = null
Insert cell
// update our mutable cell when this function is called
function selectSuggestedLocation(id) {
mutable selectedLocation = results.features.find(
(feature) => feature.id === id
);
}
Insert cell
{
// reset the value of the mutable `selectedLocation` cell when the text input's value is cleared
if (!results || !results.features || !results.features.length) {
mutable selectedLocation = null;
}
}
Insert cell
// populated after the mapbox geocoder api call is made
results = geocodeSearchDebounced(searchValue)
Insert cell
// use lodash.debounce to avoid calling the API on every keystroke to reduce the number of API calls
// see: https://docs-lodash.com/v4/debounce/
geocodeSearchDebounced = debounce(geocodeSearch, 350, {
leading: true,
trailing: false,
maxWait: 500
})
Insert cell
// the async lets us `await` the result of a Promise rather than use Promise.then
// see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
async function geocodeSearch(searchText = "") {
// we early return to avoid prematurely calling mapbox geocode API
if (!searchText || searchText.length < 3) {
return;
}

// wrap the API call in a try/catch for error handling
try {
const response = await fetch(
`${baseUrl}/${encodeURIComponent(
searchText
)}.json?types=${placeTypes}&access_token=${accessToken}`
);
const json = await response.json();
return json;
} catch (error) {
return error.message;
}
}
Insert cell
// the list of place types we'd like to search for using the geocoder
placeTypes = ["postcode", "place", "locality", "district"].join(",")
Insert cell
// the mapbox forward geocoder api route
baseUrl = "https://api.mapbox.com/geocoding/v5/mapbox.places"
Insert cell
// This token will only work on Observable notebooks by @clhenrick.
// Please acquire your own Mapbox token at https://account.mapbox.com/access-tokens
accessToken = "pk.eyJ1IjoiY2hlbnJpY2siLCJhIjoiY2xhdmdtbGY3MDVseDNwcDVtdTJ6MzRnNyJ9.H3sT8bYytYXSxmxzyZnJ-A"
Insert cell
// reference to lodash debounce
debounce = _.debounce
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more