How to Implement Map API In Angular 8

Introduction

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. so, this is showing you know exactly where you coming from. Now a day’s web-based applications, mapping solutions are a part of the application. We Basically 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. Normally, applications and web sites always combine with data. So, the data or functionality from two or more sources.

So, the sources 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 sources. The Map API provides an easy way to display our own data in an efficient and usable manner.

The Here Map API, first we need to generate an API key and then API Code from the Here Map Web Sites. For that purpose, we need to perform the below steps,

Step 1

Let’s go and open the URL:- https://developer.here.com/products/maps and then click on the Sign In link button.

Here Web API in angular 8

Step 2

After the user successful Login, click on the “Create API Key” button.

Create API Key Map webapi

Step 3

Now, click on the “Create API Key” button. It’ll generate the API Key and APP Code for accessing the Here Map API. then Copy that code which we need to use in the Angular Components.

Step 4

Now, Let’s create a new Angular CLI Project using ng new command named “MapDemo”.

create a new Angular CLI Project

Step 5

Now, Go to the Angular CLI project Code Editor. then, 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

After that, open the app.component.html file under the app folder and then replace the HTML file code with the following code.

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

Step 7

Next, open another app.component.ts file and write down the following 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 output will be as below,

Map Implement Web API in angular 8

Create Pointers in the Map Against any input Address

Next, If we want to mark any particular map position against any input address. For that, we first need to add the following 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 follows,

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);  
  }  
}  

here, you’ll see the output of the above code is as follows,

HERE Map Web API

Fetch the Geo Code along with the position of the Map

here, we retrieve and display the Geo Code along with address, we need to add the following 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 following 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 result will be as follows.

HERE Map Web API
Geo Map API location JSON values

Leave a Reply

Your email address will not be published. Required fields are marked *