Build Different

Building a Responsive Location Search Component with Angular

Niyati Tailor
Niyati Tailor
Aug 12, 2022 • Last edit on Sep 20, 20226 min read
Building a Responsive Location Search Component with Angular

As websites get bigger and bigger, it’s almost impossible to find one without search functionality. There are two forms of searches: responsive and passive.

When performing a passive search, the user inputs a keyword and then clicks a button or presses Enter to reveal the search results. In other words, passive search waits for action after the input to display the results.

Conversely, responsive search shows the results immediately as a user starts typing inside the input box. Furthermore, it improves the search results as the user types more meaningful information.

Responsive search brings a lot of value to the table, including the following benefits:

  • It provides a better experience for users who only remember part of what they’re looking for.
  • It provides a faster experience for users searching long strings of text.

In this article, we create a responsive location search component in Angular using TomTom’s Map Display API and Search API. Here’s a link to the completed project code.

Creating a Basic Angular Application

In this section, we create a basic Angular application using this repository as a starting point. You can skip this section if you already have an Angular application running. The starting code is just a cleaned-up version of the initial Angular application with additional dependencies.

After cloning the repository, we must install all the dependencies.

npm i

Once installed, we can start the application by running the following command.

npm start

After successful compilation, the application runs on port 4200. If you open the URL in the browser, you should see the following screen:

Photo 1

This means the starter application is successfully set up.

TomTom API Key

We need a TomTom API key to integrate map and responsive search components in our Angular application. For that, we need a verified developer account.

You can create an account by visiting the developer portal.

Once you have created, verified, and signed in to your account, go to the dashboard and select Keys on the left navigation bar to copy the API key.

Photo 2

Next, create an environment.ts file in src/environments and add the API key to the file:

1export const environment = {
2 production: false,
3 tomtom: {
4 key: 'YOUR_API_KEY',
5 },
6};

Photo 3

After adding an API key, we can start creating an Angular component that can search for a location or a point of interest (POI). We’ll build a component that displays the result in a list and shows the POI on a map when we click it.

Responsive Search Component with TomTom Maps

It’s time to build our component by adding code to app/app.component.ts.

First, we declare three variables: currentLon, currentLat, and map to store the map data and the user’s current location.

1export class AppComponent implements AfterViewInit {
2 map: any;
3 currentLat: number = 0;
4 currentLon: number = 0;
5
6
7
8 constructor(private http: HttpClient) {}

Then, in the ngAfterViewInit method, we call the function initLocationMap. The initLocationMap function creates an instance of a map using the TomTom API and adds it to the DOM element using an ID named map with full screen and navigation controls.

1 public ngAfterViewInit(): void {
2 this.initLocationMap();
3 }

Next, we subscribe to a function called getCurrentPosition to get the user’s current location and display it in a map using the Popup and Marker.

1private getCurrentPosition(): any {
2 return new Observable((observer: Subscriber<any>) => {
3 if (navigator.geolocation) {
4 navigator.geolocation.getCurrentPosition((position: any) => {
5 observer.next({
6 latitude: position.coords.latitude,
7 longitude: position.coords.longitude,
8 });
9 this.currentLon = position.coords.longitude;
10 this.currentLat = position.coords.latitude;
11 observer.complete();
12 });
13 } else {
14 observer.error();
15 }
16 });
17 }
18
19
20
21 private initLocationMap(): void {
22 this.map = tt.map({
23 key: environment.tomtom.key,
24 container: "map",
25 });
26
27
28
29 this.map.addControl(new tt.FullscreenControl());
30 this.map.addControl(new tt.NavigationControl());
31
32
33
34 this.getCurrentPosition().subscribe((position: any) => {
35 this.map.flyTo({
36 center: {
37 lat: position.latitude,
38 lng: position.longitude,
39 },
40 zoom: 13,
41 });
42
43
44
45 const popup = new tt.Popup({
46 anchor: "bottom",
47 offset: { bottom: [0, -40] },
48 }).setHTML("Current Location");
49
50
51
52 const marker = new tt.Marker()
53 .setLngLat({
54 lat: position.latitude,
55 lng: position.longitude,
56 })
57 .addTo(this.map);
58 marker.setPopup(popup).togglePopup();
59 });
60 }
61}

That’s all we need to do for the logic portion, but to display a map, we also need to edit the src/app/app.component.html file. Right after the H1 tag, we must add the following code, which displays the user’s location and the map.

1<p class="text-center">Current Latitude: {{currentLat}} </p>
2<p class="text-center">Current longitude: {{currentLon}} </p>
3<div id="map" class="map"></div>

After adding this code, your app should look like this:

Photo 4

Here is what src/app/app.component.html looks like once you’ve added the code above:

1<div class="container-fluid py-3">
2 <h1 class="text-center">Building a Responsive Location Search Component with Angular</h1>
3 <p class="text-center">Current Latitude: {{currentLat}} </p>
4 <p class="text-center">Current longitude: {{currentLon}} </p>
5 <div class="d-flex">
6 <div class="search-wrapper">
7 <input type="text" class="form-control" (keyup)="getValue(search.value)" #search name="search"
8 placeholder="Search Locations" />
9 <div>
10 <ul class="resultList" *ngFor="let result of searchResults" class="list-group">
11 <li role="button" (click)="setPlaceLocation(result.position.lat,result.position.lon,result.poi.name)"
12 class="list-group-item cursor">{{result.poi.name}}</li>
13 </ul>
14 </div>
15 </div>
16 <div id="map" class="map"></div>
17 </div>
18</div>

Here, the function getValue(search.value) uses the current input’s value into the API as a query and sets a response in the variable. For that, let’s create two new variables inside src/app/app.component.ts.

ROOT_URL = 'https://api.tomtom.com/search/2/search/';
searchResults: any = [];

Then, the ngAfterViewInit function creates a function named getValue, which calls the TomTom API to find the locations or POIs according to the user’s search input and the current location.

1getValue(value: string) {
2 this.http
3 .get(
4 this.ROOT_URL +
5 `${value}.json?
6 lat=${this.currentLat}&
7 lon=${this.currentLon}&
8 minFuzzyLevel=1&
9 maxFuzzyLevel=2&
10 view=Unified&
11 relatedPois=off&
12 key=${environment.tomtom.key}`
13 )
14 .subscribe((data: any) => (this.searchResults = data['results']));
15}

Last, we must create a function that adds a location or POI to the map with a click.

1setPlaceLocation(lat: number, lng: number, placeName: string): void {
2 this.map.flyTo({
3 center: {
4 lat: lat,
5 lng: lng,
6 },
7 zoom: 13,
8 });
9
10
11
12 const popup = new tt.Popup({
13 anchor: 'bottom',
14 offset: { bottom: [0, -40] },
15 }).setHTML(placeName);
16
17
18
19 const marker = new tt.Marker()
20 .setLngLat({
21 lat: lat,
22 lng: lng,
23 })
24 .addTo(this.map);
25 marker.setPopup(popup).togglePopup();
26 }

After all these changes, the app looks like this:

Photo 5

Now, if we search for any term — for example, pizza — we can see a list as we type.

Photo 6

As we keep typing more specific terms, it shows more specific POIs.

Photo 7

When we click on an element from the list, it appears on the map.

Photo 8

Conclusion

A responsive search provides a better experience for users who want to search for something but only remember a part of the term they want to find. As a responsive search narrows down the search results while a user types more specific terms, it helps users find the search term easily compared to a passive search.

A responsive search has become a necessary tool in standard websites, helping you stand out from your competitors, and with TomTom APIs, it is extremely easy to implement.

Check out the Map Display API and Search API further enhance your application’s capabilities effortlessly.

Get the developer
newsletter.

No marketing fuff. Tech content only.
Thanks for contacting us

We will reach out to you soon.
Blog cards
tomtom tech news