在JavaScript中从IP地址获取位置的方法

130 阅读1分钟

在本教程中,我们将学习如何使用JavaScript从一个IP地址中获取位置。

考虑一下,我们有以下的IP。

const ip = "112.39.244.19";

现在,我们需要通过上述地址来获取位置。

使用ipstack.com

为了从一个IP地址获取位置,我们需要通过传递用户的IP地址来调用api.ipstack.com api。

下面是一个例子。

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

输出。

"United states"

ipstack api包含与用户ip地址有关的各种属性。

{
  "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
  }
}