In this article, we will implement the steps to fetch the user IP Address and Geolocation in an angular application.
Third-Party APIs:
The API to get users IP Address endpoint:
https://jsonip.com/
Free endpoint, for official docs, visit "https://getjsonip.com/#docs".
https://jsonip.com/
Free endpoint, for official docs, visit "https://getjsonip.com/#docs".
The API to get users Geolocation based on users IP Address endpoint:
http://api.ipstack.com/User_IP?access_key=your_api_key&format=1
This endpoint has pricing subscription plans including the free subscription plan, for official docs, visit: "https://ipstack.com/"
Create An Angular Sample Application:
Let's implement an angular sample that will display users' IP Addresses and Geolocation by using third-party APIs.
Command To Install Angular CLI:(If not installed on your system previously)
npm install -g @angular/cli
Angular CLI Command To Create Angular App: ng new your_project_name
Command To Run App:
ng serve
Import HttpClientMoudle:
Let's inject the 'HttpClientMoudle' which is loads from '@angular/common/http' into our AppModule.
src/app/app.module.ts:
import { HttpClientModule } from '@angular/common/http'; // code hidden for display purpose @NgModule({ imports: [ HttpClientModule ] }) export class AppModule { }
Fetch User IP Address:
Now let's implement our API call to fetch the user IP Address.
src/app/app.component.ts:
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit { userIP = '' constructor(private httpClient: HttpClient) {} ngOnInit(): void { this.loadIp(); } loadIp() { this.httpClient.get('https://jsonip.com').subscribe( (value:any) => { console.log(value); this.userIP = value.ip; }, (error) => { console.log(error); } ); } }
- Here invoking the IP Address API and storing the user IP Address into the 'userIP' variable.
<div> <h4>User IP Address - {{userIP}}</h4> </div>
Fetch User GeoLocation:
Now we will fetch the user geolocation using the user's public IP Address.
loadIp() { this.httpClient.get('https://jsonip.com') .pipe( switchMap((value:any) => { this.userIP = value.ip; let url = `http://api.ipstack.com/${value.ip}?access_key=Your_API_Key` return this.httpClient.get(url); }) ).subscribe( (value:any) => { console.log(value); }, err => { console.log(err); } ); }
- Here fetching the IP Address and then it passed as path value to the Geolocation API. The 'access_key' query parameter should pass your key that is available in your account.
Support Me!
Buy Me A Coffee
PayPal Me
Wrapping Up:
Hopefully, I think this article delivered some useful information about fetching IP Addresses and Geolocation in angular application. I love to have your feedback, suggestions, and better techniques in the comment section below.
Comments
Post a Comment