How To Fetch The User Location Details From IP Address
Posted By : Anil Kumar | 28-Sep-2017
Introduction: In this article, i will show you how to fetch user location details like his country, state, city, latitude, longitude from his IP address.
And how can we use these details to prefill the user data in user registration or wherever these details are required.
First step: Use this URL: http://ipinfo.io/json? to get the user current location details
Example: This is the example of Angular js
getUserCurrentLocationDetail: {
url: 'http://ipinfo.io/json?',
method: "GET",
headers: {
'Content-Type': 'application/json'
},
},
Result: It provide the result in JSON fromat, In this example i am using it for my IP address.
{
"ip": "180.151.85.198",
"hostname": "180.151.85.198.reverse.spectranet.in",
"city": "New Delhi",
"region": "National Capital Territory of Delhi",
"country": "IN",
"loc": "28.6000,77.2000",
"org": "AS10029 CITYCOM NETWORKS PVT LTD"
}
Uses:
We can use these details to prefill the form which makes user friendly environment.
We can also use these details where we automatically save user details in our database without knowing to user.
And we can also use these details to validate user defined data whether user is providing correct input data or not
Example: How to get data from the response provided in the json format
function generateRequestData(response) {
var Location = response.loc.split(",");
var Latitude = Location[0];
var Longitude = Location[1];
return {
"ipAddress": response.ip,
"city": response.city,
"state": response.region,
"country": response.country,
"langitude": Longitude,
"latitude": Latitude
}
}
In this example country field having the isoCode2 value like "IN" for India, so here we go to fetch the exact country name from this isoCode2
function defaultCountry() {
$scope.spinner = true;
AuthenticationService.getUserDetail(function(response) {
var requestData = generateRequestCountry(response);
var data = {
'isoCode2': requestData.country
};
$scope.spinner = true;
AuthenticationService.defaultCountry(data, function(response) {
$scope.spinner = false;
}, function(errorResponse) {
$scope.spinner = false;
console.log(errorResponse.data.message);
});
},
function(error) {
$scope.spinner = true;
console.log("DefaultCountry not fetched: ");
$scope.spinner = false;
});
}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Anil Kumar
Anil is a Web Developer who specializes in creating dynamic and beautiful web projects and has good experience of working in distributed teams.