Search and filtering

Overview

In this guide you will see an example of how to search for Locations. The full code example is shown in the JSFiddle below, which will be examined below.

The mapsindoors.services.LocationsService class exposes the getLocations function that enables you to search for Locations.

It will return a Promise that gets resolved when the query has executed.

See mapsindoors.services.LocationsService for more information.

searchElement.addEventListener('input', debounce((e) => {
const value = e.target.value;
if (value > '') {
mapsindoors.services.LocationsService.getLocations({ q: value, includeOutsidePOI: true })
.then(displayResults)
.then(filterMap);
} else {
clearResults();
clearFilter();
}
}, 500));

The debounce method is there to ensure that the service is not being called in rapid succession. This method delays the execution of the function by 500ms, unless debounce is called again within 500ms, in which case the timer is reset.

See this article "What is debouncing" by Jamis Charles for a more detailed description of the debounce concept.

When the function executes, we check whether the input is empty or not. A request object is created if the input is not empty.

The getLocations function expects either no input, in which case it returns all Locations, or an Object (please refer to the official documentation for an exhaustive list of properties). In this case, the constant value is passed to the q property and the includeOutsidePOI property is set to true. When the Promise resolves, the response is passed to the displayResults helper function.

If the input is empty, we clear the result list and reset the map filter by calling the helper functions clearResults and clearFilter.

Checking for results

We need to clear the previous results, and check if any Locations were returned. If so, we loop through them and add them to the result list.

function displayResults(locations) {
clearResults();

if (locations.length > 0) {
for (const location of locations) {
searchResults.innerHTML += `<li>${location.properties.name}</li>`;
}
} else {
searchResults.innerHTML = '<li class="no-results">No results matched the query.</li>';
}

return locations;
}

If no Locations are returned, a message is shown to the user stating "No results matched the query.". Otherwise, we pass the Locations on to the next helper function called filterMap.

function filterMap(locations) {
mapsIndoors.filter(locations.map(location => location.id), false);
return locations;
}

The purpose of the filterMap function is to create a list of location ids used to filter the Locations on the map.

The second parameter tells MapsIndoors not to change the viewport of the map.

For more information, see MapsIndoors.filter in the reference documentation.