Get the location from IP address in JavaScript
In this tutorial, we are going to learn about how to get the location from a IP address using JavaScript.
Consider, we have the following IP:
const ip = "112.39.244.19";
Now, we need to get location by using above address.
Using ipstack.com
To get the location from an IP address, we need to call the api.ipstack.com
api by passing a user ip address to it.
Here is an example:
const ip = "112.39.244.19";
fetch(`https://api.ipstack.com/${ip}?access_key = ${YOUR_ACCESS_KEY}`).
then(res=>res.json()).
then(data=> console.log(data.country_name));
Output:
"United states"
The ipstack api contains various properties related to the user ip address:
{
"ip": "112.39.244.19",
"hostname": "112.312.150.125",
"type": "ipv4",
"continent_code": "NA",
"continent_name": "North America",
"country_code": "US",
"country_name": "United States",
"region_code": "CA",
"region_name": "California",
"city": "Los Angeles",
"zip": "90013",
"latitude": 34.0453,
"longitude": -118.2413,
"location": {
"geoname_id": 5368361,
"capital": "Washington D.C.",
"languages": [
{
"code": "en",
"name": "English",
"native": "English"
}
],
"country_flag": "https://assets.ipstack.com/images/assets/flags_svg/us.svg",
"country_flag_emoji": "🇺🇸",
"country_flag_emoji_unicode": "U+1F1FA U+1F1F8",
"calling_code": "1",
"is_eu": false
},
"time_zone": {
"id": "America/Los_Angeles",
"current_time": "2018-03-29T07:35:08-07:00",
"gmt_offset": -25200,
"code": "PDT",
"is_daylight_saving": true
},
"currency": {
"code": "USD",
"name": "US Dollar",
"plural": "US dollars",
"symbol": "$",
"symbol_native": "$"
},
"connection": {
"asn": 25876,
"isp": "Los Angeles Department of Water & Power"
},
"security": {
"is_proxy": false,
"proxy_type": null,
"is_crawler": false,
"crawler_name": null,
"crawler_type": null,
"is_tor": false,
"threat_level": "low",
"threat_types": null
}
}