10. Search Points of Interest

The following tutorial will demonstrate how to search for points of interest using the UNL SDK.

Create a new method in unlApi.js which uses the SDK's function to search for POIs.

export const fetchSearchResults = (projectId, searchParams) => {
return unlApi.searchApi.search(projectId, searchParams);
};

The next stept is to add a new button in the menu action sheet component (ActionSheet.js) inside the <div> element, followed by an input and a list for search results.

<button id="search-poi-button" class="action-sheet-button">
Search for POI
</button>
<input id="search-poi-input" class="input" placeholder="Search here" />
<ul id="search-result-list" class="search-result-list"></ul>

Add styles for the search result list and its elements in styles.css.

.search-result-list {
display: none;
list-style-type: none;
padding: 0;
margin: 0;
height: 200px;
overflow: auto;
}
.search-result {
border: 1px solid #ddd;
background-color: #f6f6f6;
padding: 10px;
display: block;
}
.search-result:hover:not(.header) {
background-color: #eee;
}

Create a new method which fetches search results and allows to generate a route towards them if clicked on. Firstly, append them to the search result list, then add an event listener to each element in the list, such that when a click event happens, a route to its location is generated.

export const searchPois = async (map) => {
let searchResultList = document.getElementById("search-result-list");
searchResultList.innerHTML = "";
const projectId = config.PROJECT_ID;
const searchParams = {
q: document.getElementById("search-poi-input").value,
lat: 13.406131,
lon: 52.520936,
};
const pois = await fetchSearchResults(projectId, searchParams);
pois.features.forEach((item) => {
let li = document.createElement("li");
li.innerText = item.properties.name;
li.classList.add("search-result");
li.addEventListener("click", () => {
map.getSource("unlCell").setData({
type: "Feature",
geometry: {
type: "Polygon",
coordinates: coordinatesToGejsonPositionArray(
{
lng: item.geometry.coordinates[0],
lat: item.geometry.coordinates[1],
},
9
),
},
properties: {},
});
previewRoute(map);
});
searchResultList.appendChild(li);
});
};

Finally, show the search input in index.js when the Search for POIs button is clicked and call the previous method (searchPois) when a new character gets typed in the input field.

document.getElementById("search-poi-button").addEventListener("click", () => {
toggleSearchContent();
});
document.getElementById("search-poi-input").addEventListener("keypress", () => {
searchPois(map);
});

Now you should be able to search for POIs.


The complete code for this sample project can be found on our GitHub page.