How to get Geolocation using IP Address in Angular

In the last article, we discuss how to get the IP address of the clients. In this article, we discuss how to get the Geolocation using your IP Address.

In this article, I have used “https://ipgeolocation.io” Free Api to get the IP Adress information.
Let’s update our “visitors.service” to get IP Address Geolocation



import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse,HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class VisitorsService {

  constructor(
    private http: HttpClient
  ) { 

  }
 
  getIpAddress() {
    return this.http
          .get('https://api.ipify.org/?format=json')
          .pipe(
            catchError(this.handleError)
          );
  } 

   getGEOLocation(ip) {
  // Update your api key to get from https://ipgeolocation.io
  let url = "https://api.ipgeolocation.io/ipgeo?apiKey=YourAPIKEY&ip="+ip; 
    return this.http
          .get(url)
          .pipe(
            catchError(this.handleError)
          );
  } 

  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  }

}



Let’s Update our Component code after getting IP address we need to call other services to get geolocation information.


<h3> My public IP address is </h3> 
<p>{{ipaddress}}</p>

<h4>IP Address Info</h4>
<p>latitude : {{latitude}}</p>
<p>longitude : {{longitude}}</p>
<p>currency : {{currency}}</p>
<p>currencysymbol : {{currencysymbol}}</p>
<p>city : {{city}}</p>
<p>country : {{country}}</p>
<p>isp : {{isp}}</p>


import { Component,OnInit } from '@angular/core';

import { VisitorsService } from './services/visitors.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit   {
  name = 'Angular';

   ipaddress:string = '';
   latitude:string= '';
   longitude:string= '';
   currency:string = '';
   currencysymbol:string = '';
   isp:string= '';
   city:string = '';
   country:string ='';
   constructor(
      private visitorsService:VisitorsService
   ){

   }

   ngOnInit(){

      this.visitorsService.getIpAddress().subscribe(res => {

        this.ipaddress = res['ip'];
        this.visitorsService.getGEOLocation(this.ipaddress).subscribe(res => {
 
          this.latitude = res['latitude'];
          this.longitude = res['longitude'];
          this.currency = res['currency']['code'];
          this.currencysymbol = res['currency']['symbol'];
          this.city = res['city'];
          this.country = res['country_code3'];
          this.isp = res['isp'];
          console.log(res);
        });
        //console.log(res);

      });
   }
}


Below is the running embedded code for Getting Client IP Address.

Spread the love
  •  
  •  
  •  
  •  
  • 1
  • 2
  •  
  •