In this article, we will take an in-depth look at the Fuzzy Search API call, defining some ways in which this API call can be leveraged to bolster an application’s functionality.
Web applications with functions related to mapping and location search can benefit greatly from the addition of address and POI (point of interest) search through a third-party API. One such API is the TomTom Search API. In this article, I’ll explain how to get started with the TomTom Search API, and the uses of the API.
Within the article, we will take an in-depth look at the Fuzzy Search API call, defining some ways in which this API call can be leveraged to bolster an application’s functionality. I’ll also provide an example implementation of the Fuzzy Search call to demonstrate how to get started with integrating Fuzzy Search into a simple web application.
Toward the end of the article, I’ll also take a quick look at an alternative approach to achieving the same result: Using the TomTom SDK. The SDK is typically quicker to and simpler to use, but if you’re a developer, you probably think about APIs first and foremost.
What is the TomTom Search API?
The TomTom Search API is a RESTful API that makes life easier on developers who need to provide an address or point of interest search in their application. This API provides calls for searches such as Fuzzy Search, Point of Interest Search, and Category Search, among several others. It is both free and easy as a developer to sign up to utilize this API, only requiring the developer to visit the TomTom for Developers site and register by clicking the link in the top right corner of the page.
Upon registering, the developer will be granted access to the developer dashboard, which will allow the developer to visit the My Apps screen and add an application. Simply adding an application here and requesting access to the Search API product will prompt TomTom to provide the developer with a non-expiring API key for use with the Search API. The developer will then be afforded 2,500 free API transactions per day to support their application. It should be noted that should 2,500 API transactions per day not be enough, more transactions can be purchased by visiting the My Credits screen in the developer dashboard.
What is Fuzzy Search?
So what is Fuzzy Search exactly? Technically speaking, Fuzzy Search references an API call from the TomTom Search API product that provides a location search service based on “fuzzy input.” This “fuzzy input” can be any combination of an address, a point of interest, or even geocoding (latitude and longitude). This API call is designed to take this input and provide a result set of addresses and points of interest that are relevant to the search. Examples of fuzzy search input can include the following:
- pizza near Minnesota
- coffee shop Los Angeles CA
- shopping malls in new jersey
- restaurants
The Fuzzy Search service is designed to simply take this search input and provide results in one of several response formats (JSON, JSONP, JS, XML). In addition, this service can leverage a latitude and longitude representation of the user’s position (or any position in general) to filter the result set in an effort to provide results that are most relevant to that particular location.
Let’s take the last example from above—“restaurants.” Maybe the developer utilizing Fuzzy Search is designing an application for users to search for locations that are directly related to where they stand. In this case, the user is searching for restaurants near them. The Fuzzy Search service simply requires the developer to provide the latitude and longitude information representing the position of the user as parameters to the API call to weight the search for “restaurants” to provide the user with a more relevant result set of restaurants near their particular location. And this is just one of several ways in which the Fuzzy Search API call can be customized to filter the result set in a particular manner, depending on the developer’s intentions in their application.
Implementing Fuzzy Search in a Web Application
The Fuzzy Search service can be implemented fairly simply and seamlessly into a web application. In an effort to demonstrate this, I have built a simple Node.js web application using the Express framework. The view engine I chose to use for my sample application is Pug.js. (Here you can find a simple guide for integrating Pug with Express as your potential templating engine of choice for a web app utilizing the Fuzzy Search service from TomTom.)
In my particular application, there are only four files that really need to be mentioned to give the full gist of my implementation. These files are all present in the image of my Project Explorer, shown below:
In this image, you can see the Bootstrap CSS file for styling the search form that will be used in my application. In addition, you can see that I have created two view files: index.pug and layout.pug for use in displaying the search form and the results returned from the Fuzzy Search API call. And finally, the app.js file provides the functionality for the form and the Express application as a whole.
The view file layout.pug simply provides the template that can be used for each page in our site. It includes the bootstrap.min.css file so that we can style the form using Bootstrap classes on any page that extends this layout file.
layout.pug
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/bootstrap.min.css')
body
block content
Index.pug extends the layout, granting us access to the Bootstrap classes. This is also where most of the work is done. This view will be responsible for displaying the search form to be used for providing the fuzzy search input, as well as displaying the results of the API call. The form is quite simple, providing a text input for the search term and a submit button.
In the event that there are results in the array named resultSet
, the results will be looped over and a line item will be added that will display the name of the establishment (should it be a point of interest) and the address in a reader-friendly format (stored in the address node of the result as freeformAddress
).
Index.pug
extends layout
block content
h1="Search for Places"
form(norm="fuzzy-search", method="get", action="/")
div.form-group
span.label Search Term
input(type="text", name="searchterm" value=searchedTerm)
div.form-group
input(type="submit", value="Search")
h2="Results for: " + searchedTerm
ul
each result, i in resultSet
if result.poi
li=result.poi.name + " -- " + result.address.freeformAddress
else
li=result.address.freeformAddress
The JavaScript file associated with this application is entitled app.js. The code located in app.js for the request to index.pug is displayed in the image below:
app.js
app.get('/', function(req, res){
var query = req.query.searchterm;
console.log(query);
if (query) {
request('https://api.tomtom.com/search/2/search' + query + '.JSON?key=YOUR_API_KEY_HERE', function(error, response, body) {
if (!error && response.statusCode == 200) {
var jsonResponse = JSON.parse(body);
console.log(jsonResponse);
res.render('index', {
resultSet: jsonResponse.results,
searchTerm: query
});
}
});
}
});
The function that executes for each request made to the home page will look for a submitted search term. If a search term is provided, the Fuzzy Search API call is made using the “request” library from Express. The request is a simple HTTP GET request made to the TomTom API with the appropriate parameters provided. A full list of the parameters can be found in the Fuzzy Search documentation online. For the sake of the example shown in this article, I am simply providing the required parameters. As you can see in the App.js code snippet, we are sending the following parameters with the request based on the format snippet below from the TomTom Search API documentation for Fuzzy Search:
https:
Parameters provided in the sample API call:
- baseURL: api.tomtom.com
- versionNumber: 2
- query: the query parameter
- ext: JSON
In this example, I didn’t provide any of the parameters that were not required in the documentation.
And now to test the application. After loading the homepage for the application, we are met with the following screen:
As a sample search, I typed “coffee shop Los Angeles CA” into the search box. Upon clicking “Search,” the following page was loaded with results from the search populated on the screen:
As you can see, points of interest along with their associated addresses were returned by the API call. And upon parsing the JSON response, it was simple to add the names of the establishments and the addresses to the display. In addition, by including “Los Angeles CA” in our search term, the API call was sure to return coffee shops relevant to the location provided. Below, I have provided the summary and first result in the result set returned in the JSON response by the HTTP GET request made in the sample application to the TomTom API:
{
"summary":{
"query":"coffee shop los angeles ca",
"queryType":"NON_NEAR",
"queryTime":121,
"numResults":10,
"offset":0,
"totalResults":1354,
"fuzzyLevel":1
},
"results":[
{
"type":"POI",
"id":"US/POI/p1/1991172",
"score":15.6,
"info":"search:ta:840069009242067-US",
"poi":{
"name":"Dunkin' Donuts",
"phone":"+(1)-(424)-2872119",
"url":"www.dunkindonuts.com",
"categories":[
"café/pub",
"coffee shop"
],
"classifications":[
{
"code":"CAFE_PUB",
"names":[
{
"nameLocale":"en-US",
"name":"coffee shop"
},
{
"nameLocale":"en-US",
"name":"café/pub"
}
]
}
]
},
"address":{
"streetNumber":"1326",
"streetName":"W Anaheim St",
"municipalitySubdivision":"Los Angeles, LA, Wilmington",
"municipality":"Los Angeles, Wilmington, LA",
"countrySecondarySubdivision":"Los Angeles",
"countryTertiarySubdivision":"Los Angeles",
"countrySubdivision":"CA",
"postalCode":"90744",
"countryCode":"US",
"country":"United States Of America",
"countryCodeISO3":"USA",
"freeformAddress":"1326 W Anaheim St, Los Angeles, CA 90744",
"countrySubdivisionName":"California"
},
"position":{
"lat":33.7788,
"lon":-118.27913
},
"viewport":{
"topLeftPoint":{
"lat":33.7797,
"lon":-118.28021
},
"btmRightPoint":{
"lat":33.7779,
"lon":-118.27805
}
},
"entryPoints":[
{
"type":"main",
"position":{
"lat":33.77906,
"lon":-118.27914
}
}
]
},
…
}
Alternative Approach: Using the TomTom SDK
Another useful way to implement Fuzzy Search in your web application is through the use of the Maps SDK from TomTom. This development kit provides an easy way to utilize many TomTom services in your web application by simply leveraging methods provided in the SDK library for your convenience. The Maps SDK download and documentation can be found here.
To show the ease with which you can implement the fuzzy search service using the SDK, I’ve developed a very simple web application using only HTML and JavaScript. The HTML page contains one form field, along with a text input to provide a search term. The search term is then used to perform a fuzzy search call and add the results to an interactive map that contains information regarding each search result.
This is what my code looks like:
<!DOCTYPE html>
<html>
<head>
<title>Sample Map</title>
<link rel='styesheet' type='text/css' href='maps_sdk/map.css' />
<script src='maps_sdk/tomtom.min.js'></script>
</head>
<body>
<form id="form">
Search: <input id="fuzzySearchTerm" type="text" />
<br />
<input type="submit" />
</form>
<br />
<div id="map" style="height: 500px; width: 500px;"></div>
<script>
tomtom.searchKey('YOUR-API-KEY-HERE');
var map = L.map('map', {key: 'YOUR-API-KEY-HERE'});
var form = document.getElementById("form");
form.onsubmit = function() {
var value = document.getElementById("fuzzySearchTerm").value;
tomtom.fuzzySearch()
.query(value)
.go(function(result) {
var markers = new L.TomTomMarkersLayer().addTo(map);
markers.setMarkersData(result);
markers.addMarkers();
map.fitBounds(markers.getBounds());
});
return false;
}
</script>
</body>
</html>
As you can see from the code, a map is added to the page along with the form field and a submit button. When the form is submitted, the search term is collected from the input element, and a fuzzy search is performed using the fuzzySearch function from the SDK. For each result, a marker is added to the map to denote the location. By comparison to the example earlier in this article involving the API, the SDK is simpler and requires less code, saving the developer time and leaving less room for error.
Below is a screenshot of the web page search. In this example I have searched for “coffee houston texas.” This is the term used in the fuzzy search call. The results are marked on the map with additional information appended to each marker describing the point of interest
Conclusion
The Fuzzy Search service can easily be folded into any web application where location/point of interest searching is required. Simply making an HTTP GET request to the TomTom Search API will return relevant results for nearly any one-line “fuzzy” search. In its most basic form, a developer can leverage the use of the Fuzzy Search service by providing a one-line form and returning a list of results (as shown above), or they can even build a more complex solution involving geocoding by mapping the position of each resulting location, utilizing the latitude and longitude for each location returned in the result set.