当前位置: 首页 > news >正文

根据IP获取用户信息和天气信息的方法

获取ip信息

async function fetchGeolocation(ip) {try {// const response = await fetch(`http://ip-api.com/json/${ip}?fields=status,message,country,regionName,city,isp`);const response = await fetch(`https://ipapi.co/${ip}/json`);if (!response.ok) {throw new Error('Failed to fetch geolocation data');}return await response.json();} catch (error) {console.error('Error fetching geolocation:', error);return null;}
}
"url":"https://ipapi.co/${ip}/json",
"method" : "GET",
"response" :
{"ip": "1.1.1.1","network": "1.1.1.0/24","version": "IPv4","city": "Sydney","region": "New South Wales","region_code": "NSW","country": "AU","country_name": "Australia","country_code": "AU","country_code_iso3": "AUS","country_capital": "Canberra","country_tld": ".au","continent_code": "OC","in_eu": false,"postal": "2000","latitude": -33.859336,"longitude": 151.203624,"timezone": "Australia/Sydney","utc_offset": "+1000","country_calling_code": "+61","currency": "AUD","currency_name": "Dollar","languages": "en-AU","country_area": 7686850.0,"country_population": 24992369,"asn": "AS13335","org": "CLOUDFLARENET"
}

更多信息见:
https://ipapi.co/

获取天气信息

// Function to fetch weather data from api.open-meteo.com
async function getWeather(latitude, longitude, timezone) {const url = "https://api.open-meteo.com/v1/forecast";const params = new URLSearchParams({latitude: latitude,longitude: longitude,current_weather: "true",timezone: timezone});try {const response = await fetch(`${url}?${params}`);if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}const data = await response.json();if (data.current_weather) {return data;} else {return null}} catch (error) {console.error("fetch weather failed", error);return null}
}function getWeatherDescription(code) {const weatherCodeEmojiMap = {0: { emoji: "☀️", en: "Clear sky", zh: "晴天" },1: { emoji: "🌤️", en: "Mainly clear", zh: "少云" },2: { emoji: "⛅", en: "Partly cloudy", zh: "多云" },3: { emoji: "☁️", en: "Overcast", zh: "阴天" },45: { emoji: "🌫️", en: "Fog", zh: "雾" },48: { emoji: "❄️🌫️", en: "Rime fog", zh: "霜雾" },51: { emoji: "🌦️", en: "Light drizzle", zh: "小到中雨(毛毛雨)" },53: { emoji: "🌧️", en: "Moderate drizzle", zh: "中雨(毛毛雨)" },55: { emoji: "🌧️🌧️", en: "Dense drizzle", zh: "大到暴雨(毛毛雨)" },61: { emoji: "🌦️", en: "Light rain", zh: "小雨" },63: { emoji: "🌧️", en: "Moderate rain", zh: "中雨" },65: { emoji: "🌧️🌧️", en: "Heavy rain", zh: "大雨" },71: { emoji: "🌨️", en: "Light snow", zh: "小雪" },73: { emoji: "❄️", en: "Moderate snow", zh: "中雪" },75: { emoji: "❄️❄️", en: "Heavy snow", zh: "大雪" },80: { emoji: "🌦️", en: "Light showers", zh: "小阵雨" },81: { emoji: "🌧️", en: "Moderate showers", zh: "中阵雨" },82: { emoji: "🌧️🌧️", en: "Heavy showers", zh: "大阵雨" },95: { emoji: "⛈️", en: "Thunderstorm", zh: "雷暴" },96: { emoji: "⛈️🌨️", en: "Thunderstorm with light hail", zh: "雷暴伴小冰雹" },99: { emoji: "⛈️❄️", en: "Thunderstorm with heavy hail", zh: "雷暴伴大冰雹" }};return `${weatherCodeEmojiMap[code].emoji} ${weatherCodeEmojiMap[code].en}`;
}
"url":"
https://api.open-meteo.com/v1/forecast?latitude=-33.859336&longitude=151.203624&current_weather=true&timezone=Australia%2FSydney",
"method" : "GET",
"response" :
{"latitude": -33.75,"longitude": 151.25,"generationtime_ms": 1.6900300979614258,"utc_offset_seconds": 36000,"timezone": "Australia/Sydney","timezone_abbreviation": "GMT+10","elevation": 24.0,"current_weather_units": {"time": "iso8601","interval": "seconds","temperature": "°C","windspeed": "km/h","winddirection": "°","is_day": "","weathercode": "wmo code"},"current_weather": {"time": "2025-09-14T18:00","interval": 900,"temperature": 20.8,"windspeed": 3.6,"winddirection": 6,"is_day": 0,"weathercode": 1}
}

更多信息见:
https://open-meteo.com/

调用

const geoData = await fetchGeolocation("1.1.1.1");
if (geoData) {const locationText = `${geoData.city}, ${geoData.region}, ${geoData.country_name}`;document.getElementById('location').textContent = locationText;document.getElementById('isp').textContent = geoData.org;const weatherData = await getWeather(geoData.latitude, geoData.longitude, geoData.timezone)if (weatherData) {var weatherText = `${getWeatherDescription(weatherData.current_weather.weathercode)},`weatherText += `${weatherData.current_weather.temperature}${weatherData.current_weather_units.temperature},`weatherText += `wind:${weatherData.current_weather.windspeed}${weatherData.current_weather_units.windspeed} `weatherText += `${weatherData.current_weather.winddirection}${weatherData.current_weather_units.winddirection}`;document.getElementById('weather').textContent = weatherText;} else {document.getElementById('weather').textContent = 'weather data unavailable';}
}

效果

https://lezeya.com/now/


文章转载自:

http://w3KkgtjM.spwLn.cn
http://agmVfwe1.spwLn.cn
http://II4kip18.spwLn.cn
http://a9eEWH59.spwLn.cn
http://vG2xbz5v.spwLn.cn
http://cAYfehbB.spwLn.cn
http://1jrrpKbl.spwLn.cn
http://QWmzVKQN.spwLn.cn
http://dLG2UUKS.spwLn.cn
http://Xy8HKT1q.spwLn.cn
http://biPh0pC5.spwLn.cn
http://hVJzsKrK.spwLn.cn
http://0FTjcvYs.spwLn.cn
http://WFRPvIoR.spwLn.cn
http://mnrnMgew.spwLn.cn
http://bveMCc2r.spwLn.cn
http://YEOZlVl0.spwLn.cn
http://8O9VqbyJ.spwLn.cn
http://zcRKmrXG.spwLn.cn
http://8sYT8Q47.spwLn.cn
http://RSfnr2XR.spwLn.cn
http://YvLFt5Bi.spwLn.cn
http://mHQ1C8tG.spwLn.cn
http://FcMWO6uV.spwLn.cn
http://4bZtBHJa.spwLn.cn
http://L5djjmeq.spwLn.cn
http://1YLodY77.spwLn.cn
http://ecMBVpeR.spwLn.cn
http://6NuDuyKx.spwLn.cn
http://APmaIHLL.spwLn.cn
http://www.dtcms.com/a/383864.html

相关文章:

  • Paxos协议
  • 上网行为二层部署案例
  • XLua教程之热补丁技术
  • Linux 基本命令超详细解释第一期 | cd | pwd | ls | mkdir | rmdir
  • 如何查找 Linux 中 `dm-X` 设备对应的真实磁盘或虚拟机?
  • 线性稳压器LDO原理
  • 大模型浪潮来袭
  • 第6课:安全性与权限控制
  • 如何用 Rust 重写 SQLite 数据库(二):是否有市场空间?
  • pgsql 特有字段记录
  • Leetcode第165场双周赛题目详解+复盘
  • rt1180 rt1180处理器ethercat具体技术介绍
  • Sugov 关于频率变化
  • 多语言编码Agent解决方案(6)-部署和使用指南
  • React 原理篇 - React 新架构深度解析
  • Flowgorith,一款图形化编程入门工具
  • LeetCode 674.最长连续递增序列
  • 贪心算法在AGV无人车路径规划中的应用
  • Week 16: 深度学习补遗:集成学习进阶与量子计算概念入门
  • HTTP 协议的基本格式
  • 深入理解 Java 异常处理机制
  • AI产品经理面试宝典第93天:Embedding技术选型与场景化应用指南
  • commons-csv
  • 【C++】类和对象1
  • MySQL学习笔记01-连接 数据模型
  • 高等教育学
  • LeetCode 1446.连续字符
  • 力扣966 元音拼写器(三个哈希表解法)详解
  • godot+c#操作sqlite并加解密
  • 利用DeepSeek实现服务器客户端模式的DuckDB原型