Implementing Here Map API In Angular 8

In this article, we will discuss how to use Here Map API in Angular 8.

In this article, we will discuss how to implement Here Map API with Angular 8. On today’s web-based applications, mapping solutions is a natural part of the application. We normally use them to see the location of things, to search for any address, to get the driving directions and also many more different types of actions. Basically, applications and web sites always combine with data. Normally, data or functionality from two or more sources is commonly referred to as mashups.
 
Nowadays, mashups are becoming much more popular and have revolutionized the way information is being used and visualized. Mapping solutions are one important ingredient in a lot of these mashups. The Here Map API provides us with an easy way to display our own data in an efficient and usable manner.
 
For using the Here Map API, we first need to generate an API key and API Code from the Here Map Web Sites. For that purpose, we need to perform the below steps,
 
Step 1
 
First, open the URL:- https://developer.here.com/products/maps and click on the Sign In link in the top right corner.
 
Implement Here Map API using Angular 8 
 
Step 2
 
After successful Sign In, click on the "Get a Free API Key" button.
 
Implement Here Map API using Angular 8
 
Step 3
 
Now, click on the "Generate API Key" button. It will generate the API ID and APP Code for accessing the Here Map API. Copy these codes which we need to use in the Angular Components.
 
Implement Here Map API using Angular 8
 
Step 4
 
Now, create a new Angular CLI Project using ng new command.
 
Implement Here Map API using Angular 8
 
Step 5
 
Now open the above Angular cli project in Visual Studio Code Editor. Now open the Index.html file and use the below file reference in the index page for using the Here Map API.
  1. <!doctype html>  
  2. <html lang="en">  
  3. <head>  
  4.   <meta charset="utf-8">  
  5.   <title>HereMapDemo</title>  
  6.   <base href="/">  
  7.   
  8.   <meta name="viewport" content="width=device-width, initial-scale=1">  
  9.   <link rel="icon" type="image/x-icon" href="favicon.ico">  
  10.   <link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.0/mapsjs-ui.css?dp-version=1533195059" />  
  11. </head>  
  12. <body>  
  13.   <app-root></app-root>  
  14.   <script src="https://js.api.here.com/v3/3.0/mapsjs-core.js" type="text/javascript" charset="utf-8"></script>  
  15.   <script src="https://js.api.here.com/v3/3.0/mapsjs-service.js" type="text/javascript" charset="utf-8"></script>  
  16.   <script src="https://js.api.here.com/v3/3.0/mapsjs-places.js" type="text/javascript" charset="utf-8"></script>  
  17.   <script src="https://js.api.here.com/v3/3.0/mapsjs-mapevents.js" type="text/javascript" charset="utf-8"></script>  
  18.   <script src="https://js.api.here.com/v3/3.0/mapsjs-ui.js" type="text/javascript" charset="utf-8"></script>  
  19. </body>  
  20. </html>  
Step 6
 
Now, open the app.component.html file under app folder and replace the html file code with the below code,
  1. <div #map [style.width]="width" [style.height]="height"></div>  
Step 7
 
Now, open the app.component.ts file and write down the below code to generate the basic map objects in the browser,
  1. import { Component, OnInit, ViewChild, ElementRef, Input } from '@angular/core';  
  2. import { HttpClient, HttpHeaders } from '@angular/common/http';  
  3.   
  4. declare var H: any;  
  5.   
  6. @Component({  
  7.   selector: 'app-root',  
  8.   templateUrl: './app.component.html',  
  9.   styleUrls: ['./app.component.css']  
  10. })  
  11. export class AppComponent {  
  12.   title = 'HereMapDemo';  
  13.   
  14.   @ViewChild("map", { statictrue }) public mapElement: ElementRef;  
  15.   
  16.   public lat: any = '22.5726';  
  17.   public lng: any = '88.3639';  
  18.   
  19.   public width: any = '1000px';  
  20.   public height: any = '600px';  
  21.   
  22.   private platform: any;  
  23.   private map: any;  
  24.   
  25.   private _appId: string = 'xxxxxx';  
  26.   private _appCode: string = 'uuuuuu';  
  27.   
  28.   public constructor() {  
  29.       
  30.   }  
  31.   
  32.   public ngOnInit() {  
  33.     this.platform = new H.service.Platform({  
  34.       "app_id"this._appId,  
  35.       "app_code"this._appCode,  
  36.       useHTTPS: true  
  37.     });  
  38.       
  39.   }  
  40.   
  41.   public ngAfterViewInit() {  
  42.     let pixelRatio = window.devicePixelRatio || 1;  
  43.     let defaultLayers = this.platform.createDefaultLayers({  
  44.       tileSize: pixelRatio === 1 ? 256 : 512,  
  45.       ppi: pixelRatio === 1 ? undefined : 320  
  46.     });  
  47.   
  48.     this.map = new H.Map(this.mapElement.nativeElement,  
  49.       defaultLayers.normal.map, { pixelRatio: pixelRatio });  
  50.   
  51.     var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(this.map));  
  52.     var ui = H.ui.UI.createDefault(this.map, defaultLayers);  
  53.   
  54.     this.map.setCenter({ lat: this.lat, lng: this.lng });  
  55.     this.map.setZoom(14);  
  56.   }  
  57.   
  58. }  
Now, run the code and result will be as below,
 
Implement Here Map API using Angular 8
 

Create Pointers in the Map Against any Given Address

 
Now, we want to mark any particular map position against any given address. For that, we first need to add the below code in the app.component.html file as below,
  1. <div style="padding: 10px 0">  
  2.   <input type="text" placeholder="Search places..." [(ngModel)]="query" style="width: 90%;" />  
  3.   <button (click)="places(query)">Search</button>  
  4. </div>  
  5.   
  6. <div #map [style.width]="width" [style.height]="height"></div>  
Now, open the app.component.ts file and change the code as below,
  1. import { Component, OnInit, ViewChild, ElementRef, Input } from '@angular/core';  
  2. import { HttpClient, HttpHeaders } from '@angular/common/http';  
  3.   
  4. declare var H: any;  
  5.   
  6. @Component({  
  7.   selector: 'app-root',  
  8.   templateUrl: './app.component.html',  
  9.   styleUrls: ['./app.component.css']  
  10. })  
  11. export class AppComponent {  
  12.   title = 'HereMapDemo';  
  13.   
  14.   @ViewChild("map", { statictrue }) public mapElement: ElementRef;  
  15.   
  16.   public lat: any = '22.5726';  
  17.   public lng: any = '88.3639';  
  18.   
  19.   public width: any = '1000px';  
  20.   public height: any = '600px';  
  21.   
  22.   private platform: any;  
  23.   private map: any;  
  24.   
  25.   private _appId: string = 'xxxxx';  
  26.   private _appCode: string = 'xxxx';  
  27.   
  28.   public query: string;  
  29.   private search: any;  
  30.   private ui: any;  
  31.   
  32.   
  33.   public constructor() {  
  34.     this.query = "";  
  35.   }  
  36.   
  37.   public ngOnInit() {  
  38.     this.platform = new H.service.Platform({  
  39.       "app_id"this._appId,  
  40.       "app_code"this._appCode,  
  41.       useHTTPS: true  
  42.     });  
  43.     this.search = new H.places.Search(this.platform.getPlacesService());  
  44.   }  
  45.   
  46.   public ngAfterViewInit() {  
  47.     let pixelRatio = window.devicePixelRatio || 1;  
  48.     let defaultLayers = this.platform.createDefaultLayers({  
  49.       tileSize: pixelRatio === 1 ? 256 : 512,  
  50.       ppi: pixelRatio === 1 ? undefined : 320  
  51.     });  
  52.   
  53.     this.map = new H.Map(this.mapElement.nativeElement,  
  54.       defaultLayers.normal.map, { pixelRatio: pixelRatio });  
  55.   
  56.     var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(this.map));  
  57.     var ui = H.ui.UI.createDefault(this.map, defaultLayers);  
  58.   
  59.     this.map.setCenter({ lat: this.lat, lng: this.lng });  
  60.     this.map.setZoom(14);  
  61.   
  62.       
  63.   }  
  64.   
  65.   public places(query: string) {  
  66.     this.map.removeObjects(this.map.getObjects());  
  67.     this.search.request({ "q": query, "at"this.lat + "," + this.lng }, {}, data => {  
  68.       for (let i = 0; i < data.results.items.length; i++) {  
  69.         this.dropMarker({ "lat": data.results.items[i].position[0], "lng": data.results.items[i].position[1] }, data.results.items[i]);  
  70.         if (i == 0)  
  71.           this.map.setCenter({ lat: data.results.items[i].position[0], lng: data.results.items[i].position[1] })  
  72.       }  
  73.     }, error => {  
  74.       console.error(error);  
  75.     });  
  76.   }  
  77.   
  78.   private dropMarker(coordinates: any, data: any) {  
  79.     let marker = new H.map.Marker(coordinates);  
  80.     marker.setData("<p>" + data.title + "<br>" + data.vicinity + "</p>");  
  81.     marker.addEventListener('tap', event => {  
  82.       let bubble = new H.ui.InfoBubble(event.target.getPosition(), {  
  83.         content: event.target.getData()  
  84.       });  
  85.       this.ui.addBubble(bubble);  
  86.     }, false);  
  87.     this.map.addObject(marker);  
  88.   }  
  89.   
  90. }  
The output of the above code is as below,
 
Implement Here Map API using Angular 8
 

Fetch Geo Code along with Address on Mouse Click in any position of the Map

 
Now, to retrieve and display the Geo Code along with address, we need to add the below HTML code in the app.component.html file.
  1. <div style="padding: 10px 0">  
  2.   <input type="text" placeholder="Search places..." [(ngModel)]="query" style="width: 90%;" />  
  3.   <button (click)="places(query)">Search</button>  
  4. </div>  
  5.   
  6. <div #map [style.width]="width" [style.height]="height"></div>  
  7.   
  8. <div style="padding: 10px 0">  
  9.   <div class="col-xxl-12">  
  10.     <div class="red-800">  
  11.       <label>Latitude : {{lat}}</label>  
  12.           
  13.       <label>Longitude : {{lng}}</label>  
  14.     </div>  
  15.     <div class="blue-800">  
  16.       <label>Address : {{address}}</label>  
  17.     </div>  
  18.   </div>  
  19. </div>  
Add the below marked code in the app.compoent.ts file to fetch the geo code and address.
  1. import { Component, OnInit, ViewChild, ElementRef, Input } from '@angular/core';  
  2. import { HttpClient, HttpHeaders } from '@angular/common/http';  
  3.   
  4. declare var H: any;  
  5.   
  6. @Component({  
  7.   selector: 'app-root',  
  8.   templateUrl: './app.component.html',  
  9.   styleUrls: ['./app.component.css']  
  10. })  
  11. export class AppComponent {  
  12.   title = 'HereMapDemo';  
  13.   
  14.   @ViewChild("map", { statictrue }) public mapElement: ElementRef;  
  15.   
  16.   public lat: any = '22.5726';  
  17.   public lng: any = '88.3639';  
  18.   
  19.   public width: any = '1000px';  
  20.   public height: any = '600px';  
  21.   
  22.   private platform: any;  
  23.   private map: any;  
  24.   
  25.   private _appId: string = 'xxxx';  
  26.   private _appCode: string = 'xxxx';  
  27.   
  28.   public query: string;  
  29.   private search: any;  
  30.   private ui: any;  
  31.   public address: string = '' 
  32.   
  33.   public constructor() {  
  34.     this.query = "";  
  35.   }  
  36.   
  37.   public ngOnInit() {  
  38.     this.platform = new H.service.Platform({  
  39.       "app_id"this._appId,  
  40.       "app_code"this._appCode,  
  41.       useHTTPS: true  
  42.     });  
  43.     this.search = new H.places.Search(this.platform.getPlacesService());  
  44.   }  
  45.   
  46.   public ngAfterViewInit() {  
  47.     let pixelRatio = window.devicePixelRatio || 1;  
  48.     let defaultLayers = this.platform.createDefaultLayers({  
  49.       tileSize: pixelRatio === 1 ? 256 : 512,  
  50.       ppi: pixelRatio === 1 ? undefined : 320  
  51.     });  
  52.   
  53.     this.map = new H.Map(this.mapElement.nativeElement,  
  54.       defaultLayers.normal.map, { pixelRatio: pixelRatio });  
  55.   
  56.     var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(this.map));  
  57.     var ui = H.ui.UI.createDefault(this.map, defaultLayers);  
  58.   
  59.     this.map.setCenter({ lat: this.lat, lng: this.lng });  
  60.     this.map.setZoom(14);  
  61.   
  62.     this.setUpClickListener(this.map);  
  63.   }  
  64.   
  65.   public places(query: string) {  
  66.     this.map.removeObjects(this.map.getObjects());  
  67.     this.search.request({ "q": query, "at"this.lat + "," + this.lng }, {}, data => {  
  68.       for (let i = 0; i < data.results.items.length; i++) {  
  69.         this.dropMarker({ "lat": data.results.items[i].position[0], "lng": data.results.items[i].position[1] }, data.results.items[i]);  
  70.         if (i == 0)  
  71.           this.map.setCenter({ lat: data.results.items[i].position[0], lng: data.results.items[i].position[1] })  
  72.       }  
  73.     }, error => {  
  74.       console.error(error);  
  75.     });  
  76.   }  
  77.   
  78.   private dropMarker(coordinates: any, data: any) {  
  79.     let marker = new H.map.Marker(coordinates);  
  80.     marker.setData("<p>" + data.title + "<br>" + data.vicinity + "</p>");  
  81.     marker.addEventListener('tap', event => {  
  82.       let bubble = new H.ui.InfoBubble(event.target.getPosition(), {  
  83.         content: event.target.getData()  
  84.       });  
  85.       this.ui.addBubble(bubble);  
  86.     }, false);  
  87.     this.map.addObject(marker);  
  88.   }  
  89.   
  90.   public setUpClickListener(map: any) {  
  91.     let self = this;  
  92.     this.map.addEventListener('tap'function (evt) {  
  93.       let coord = map.screenToGeo(evt.currentPointer.viewportX, evt.currentPointer.viewportY);  
  94.       self.lat = Math.abs(coord.lat.toFixed(4)) + ((coord.lat > 0) ? 'N' : 'S');  
  95.       self.lng = Math.abs(coord.lng.toFixed(4)) + ((coord.lng > 0) ? 'E' : 'W');  
  96.       self.fetchAddress(coord.lat, coord.lng);  
  97.     });  
  98.   }  
  99.   
  100.   private fetchAddress(lat: any, lng: any): void {  
  101.     let self = this;  
  102.     let geocoder: any = this.platform.getGeocodingService(),  
  103.       parameters = {  
  104.         prox: lat + ', ' + lng + ',20',  
  105.         mode: 'retrieveAreas',  
  106.         gen: '9'  
  107.       };  
  108.   
  109.   
  110.     geocoder.reverseGeocode(parameters,  
  111.       function (result) {  
  112.         let data = result.Response.View[0].Result[0].Location.Address;  
  113.         self.address = data.Label + ', ' + data.City + ', Pin - ' + data.PostalCode + ' ' + data.Country;  
  114.       }, function (error) {  
  115.         alert(error);  
  116.       });  
  117.   }  
  118.   
  119. }  
Now, the output will be as below.
 
Implement Here Map API using Angular 8
 

Conclusion

 
Now, in this article, we discussed how to implement Here Map API using Angular 8. I hope this will help the readers to understand how to use Here Map in any application. Any feedback or query related to this article or content is most welcome.