How to Implement Map API in Angular 8

How to Implement Map API in Angular 8

In this article, we will learn how to implement Here Map API with Angular 8. We're gonna use it in combination with the Here Map API integration for Angular.

In this post, 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.

This is image title

Step 2

After successful Sign In, click on the "Get a Free API Key" button.

This is image title

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.

This is image title

Step 4

Now, create a new Angular CLI Project using ng new command.

This is image title

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.

<!doctype html>  
<html lang="en">  
<head>  
  <meta charset="utf-8">  
  <title>HereMapDemo</title>  
  <base href="/">  

  <meta name="viewport" content="width=device-width, initial-scale=1">  
  <link rel="icon" type="image/x-icon" href="favicon.ico">  
  <link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.0/mapsjs-ui.css?dp-version=1533195059" />  
</head>  
<body>  
  <app-root></app-root>  
  <script src="https://js.api.here.com/v3/3.0/mapsjs-core.js" type="text/javascript" charset="utf-8"></script>  
  <script src="https://js.api.here.com/v3/3.0/mapsjs-service.js" type="text/javascript" charset="utf-8"></script>  
  <script src="https://js.api.here.com/v3/3.0/mapsjs-places.js" type="text/javascript" charset="utf-8"></script>  
  <script src="https://js.api.here.com/v3/3.0/mapsjs-mapevents.js" type="text/javascript" charset="utf-8"></script>  
  <script src="https://js.api.here.com/v3/3.0/mapsjs-ui.js" type="text/javascript" charset="utf-8"></script>  
</body>  
</html>  

Step 6

Now, open the app.component.html file under app folder and replace the html file code with the below code,

<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,

import { Component, OnInit, ViewChild, ElementRef, Input } from '@angular/core';  
import { HttpClient, HttpHeaders } from '@angular/common/http';  

declare var H: any;  

@Component({  
  selector: 'app-root',  
  templateUrl: './app.component.html',  
  styleUrls: ['./app.component.css']  
})  
export class AppComponent {  
  title = 'HereMapDemo';  

  @ViewChild("map", { static: true }) public mapElement: ElementRef;  

  public lat: any = '22.5726';  
  public lng: any = '88.3639';  

  public width: any = '1000px';  
  public height: any = '600px';  

  private platform: any;  
  private map: any;  

  private _appId: string = 'xxxxxx';  
  private _appCode: string = 'uuuuuu';  

  public constructor() {  

  }  

  public ngOnInit() {  
    this.platform = new H.service.Platform({  
      "app_id": this._appId,  
      "app_code": this._appCode,  
      useHTTPS: true  
    });  

  }  

  public ngAfterViewInit() {  
    let pixelRatio = window.devicePixelRatio || 1;  
    let defaultLayers = this.platform.createDefaultLayers({  
      tileSize: pixelRatio === 1 ? 256 : 512,  
      ppi: pixelRatio === 1 ? undefined : 320  
    });  

    this.map = new H.Map(this.mapElement.nativeElement,  
      defaultLayers.normal.map, { pixelRatio: pixelRatio });  

    var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(this.map));  
    var ui = H.ui.UI.createDefault(this.map, defaultLayers);  

    this.map.setCenter({ lat: this.lat, lng: this.lng });  
    this.map.setZoom(14);  
  }  

}  

Now, run the code and result will be as below,

This is image title

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,

<div style="padding: 10px 0">  
  <input type="text" placeholder="Search places..." [(ngModel)]="query" style="width: 90%;" />  
  <button (click)="places(query)">Search</button>  
</div>  

<div #map [style.width]="width" [style.height]="height"></div>  

Now, open the app.component.ts file and change the code as below,

import { Component, OnInit, ViewChild, ElementRef, Input } from '@angular/core';  
import { HttpClient, HttpHeaders } from '@angular/common/http';  

declare var H: any;  

@Component({  
  selector: 'app-root',  
  templateUrl: './app.component.html',  
  styleUrls: ['./app.component.css']  
})  
export class AppComponent {  
  title = 'HereMapDemo';  

  @ViewChild("map", { static: true }) public mapElement: ElementRef;  

  public lat: any = '22.5726';  
  public lng: any = '88.3639';  

  public width: any = '1000px';  
  public height: any = '600px';  

  private platform: any;  
  private map: any;  

  private _appId: string = 'xxxxx';  
  private _appCode: string = 'xxxx';  

  public query: string;  
  private search: any;  
  private ui: any;  


  public constructor() {  
    this.query = "";  
  }  

  public ngOnInit() {  
    this.platform = new H.service.Platform({  
      "app_id": this._appId,  
      "app_code": this._appCode,  
      useHTTPS: true  
    });  
    this.search = new H.places.Search(this.platform.getPlacesService());  
  }  

  public ngAfterViewInit() {  
    let pixelRatio = window.devicePixelRatio || 1;  
    let defaultLayers = this.platform.createDefaultLayers({  
      tileSize: pixelRatio === 1 ? 256 : 512,  
      ppi: pixelRatio === 1 ? undefined : 320  
    });  

    this.map = new H.Map(this.mapElement.nativeElement,  
      defaultLayers.normal.map, { pixelRatio: pixelRatio });  

    var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(this.map));  
    var ui = H.ui.UI.createDefault(this.map, defaultLayers);  

    this.map.setCenter({ lat: this.lat, lng: this.lng });  
    this.map.setZoom(14);  


  }  

  public places(query: string) {  
    this.map.removeObjects(this.map.getObjects());  
    this.search.request({ "q": query, "at": this.lat + "," + this.lng }, {}, data => {  
      for (let i = 0; i < data.results.items.length; i++) {  
        this.dropMarker({ "lat": data.results.items[i].position[0], "lng": data.results.items[i].position[1] }, data.results.items[i]);  
        if (i == 0)  
          this.map.setCenter({ lat: data.results.items[i].position[0], lng: data.results.items[i].position[1] })  
      }  
    }, error => {  
      console.error(error);  
    });  
  }  

  private dropMarker(coordinates: any, data: any) {  
    let marker = new H.map.Marker(coordinates);  
    marker.setData("<p>" + data.title + "<br>" + data.vicinity + "</p>");  
    marker.addEventListener('tap', event => {  
      let bubble = new H.ui.InfoBubble(event.target.getPosition(), {  
        content: event.target.getData()  
      });  
      this.ui.addBubble(bubble);  
    }, false);  
    this.map.addObject(marker);  
  }  

}  

The output of the above code is as below,

This is image title

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.

<div style="padding: 10px 0">  
  <input type="text" placeholder="Search places..." [(ngModel)]="query" style="width: 90%;" />  
  <button (click)="places(query)">Search</button>  
</div>  

<div #map [style.width]="width" [style.height]="height"></div>  

<div style="padding: 10px 0">  
  <div class="col-xxl-12">  
    <div class="red-800">  
      <label>Latitude : {{lat}}</label>  

      <label>Longitude : {{lng}}</label>  
    </div>  
    <div class="blue-800">  
      <label>Address : {{address}}</label>  
    </div>  
  </div>  
</div>  

Add the below marked code in the app.compoent.ts file to fetch the geo code and address.

import { Component, OnInit, ViewChild, ElementRef, Input } from '@angular/core';  
import { HttpClient, HttpHeaders } from '@angular/common/http';  

declare var H: any;  

@Component({  
  selector: 'app-root',  
  templateUrl: './app.component.html',  
  styleUrls: ['./app.component.css']  
})  
export class AppComponent {  
  title = 'HereMapDemo';  

  @ViewChild("map", { static: true }) public mapElement: ElementRef;  

  public lat: any = '22.5726';  
  public lng: any = '88.3639';  

  public width: any = '1000px';  
  public height: any = '600px';  

  private platform: any;  
  private map: any;  

  private _appId: string = 'xxxx';  
  private _appCode: string = 'xxxx';  

  public query: string;  
  private search: any;  
  private ui: any;  
  public address: string = '';  

  public constructor() {  
    this.query = "";  
  }  

  public ngOnInit() {  
    this.platform = new H.service.Platform({  
      "app_id": this._appId,  
      "app_code": this._appCode,  
      useHTTPS: true  
    });  
    this.search = new H.places.Search(this.platform.getPlacesService());  
  }  

  public ngAfterViewInit() {  
    let pixelRatio = window.devicePixelRatio || 1;  
    let defaultLayers = this.platform.createDefaultLayers({  
      tileSize: pixelRatio === 1 ? 256 : 512,  
      ppi: pixelRatio === 1 ? undefined : 320  
    });  

    this.map = new H.Map(this.mapElement.nativeElement,  
      defaultLayers.normal.map, { pixelRatio: pixelRatio });  

    var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(this.map));  
    var ui = H.ui.UI.createDefault(this.map, defaultLayers);  

    this.map.setCenter({ lat: this.lat, lng: this.lng });  
    this.map.setZoom(14);  

    this.setUpClickListener(this.map);  
  }  

  public places(query: string) {  
    this.map.removeObjects(this.map.getObjects());  
    this.search.request({ "q": query, "at": this.lat + "," + this.lng }, {}, data => {  
      for (let i = 0; i < data.results.items.length; i++) {  
        this.dropMarker({ "lat": data.results.items[i].position[0], "lng": data.results.items[i].position[1] }, data.results.items[i]);  
        if (i == 0)  
          this.map.setCenter({ lat: data.results.items[i].position[0], lng: data.results.items[i].position[1] })  
      }  
    }, error => {  
      console.error(error);  
    });  
  }  

  private dropMarker(coordinates: any, data: any) {  
    let marker = new H.map.Marker(coordinates);  
    marker.setData("<p>" + data.title + "<br>" + data.vicinity + "</p>");  
    marker.addEventListener('tap', event => {  
      let bubble = new H.ui.InfoBubble(event.target.getPosition(), {  
        content: event.target.getData()  
      });  
      this.ui.addBubble(bubble);  
    }, false);  
    this.map.addObject(marker);  
  }  

  public setUpClickListener(map: any) {  
    let self = this;  
    this.map.addEventListener('tap', function (evt) {  
      let coord = map.screenToGeo(evt.currentPointer.viewportX, evt.currentPointer.viewportY);  
      self.lat = Math.abs(coord.lat.toFixed(4)) + ((coord.lat > 0) ? 'N' : 'S');  
      self.lng = Math.abs(coord.lng.toFixed(4)) + ((coord.lng > 0) ? 'E' : 'W');  
      self.fetchAddress(coord.lat, coord.lng);  
    });  
  }  

  private fetchAddress(lat: any, lng: any): void {  
    let self = this;  
    let geocoder: any = this.platform.getGeocodingService(),  
      parameters = {  
        prox: lat + ', ' + lng + ',20',  
        mode: 'retrieveAreas',  
        gen: '9'  
      };  


    geocoder.reverseGeocode(parameters,  
      function (result) {  
        let data = result.Response.View[0].Result[0].Location.Address;  
        self.address = data.Label + ', ' + data.City + ', Pin - ' + data.PostalCode + ' ' + data.Country;  
      }, function (error) {  
        alert(error);  
      });  
  }  

}  

Now, the output will be as below.

This is image title

Conclusion

Now, in this post, 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.

Thank you

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

How to Consume a GraphQL API with Angular

In this article, we will show you how to use Angular to Consume a GraphQL API.

Integrate PHP Laravel 5.8 APIs in Angular 7

For PHP Laravel APIs to integrate in Angular 7, we have to write APIs in api.php file in Laravel which is in the routes folder in Laravel project structure. For the sake of this article, we are using example of User API.