如何修改OpenWeatherMap JS应用默认温度为华氏度
修改OpenWeatherMap天气应用默认显示华氏度的方法
先搞懂温度单位转换逻辑
OpenWeatherMap API默认返回**开尔文(K)**温度,三种单位转换公式:
- 开尔文转摄氏度(℃):
℃ = K - 273.15 - 开尔文转华氏度(℉):
℉ = (K × 9/5) - 459.67 - 华氏度转摄氏度:
℃ = (℉ - 32) × 5/9
方法一:直接修改代码转换逻辑(不用改API参数)
适合不想调整API请求的场景:
1. 修改初始温度显示(当前+未来)
找到你提供的这两行代码:
$("#cur-deg").html(Math.round(result.list[0].main.temp - 273.15)+"°C"); $next.eq(i-1).find(".next-deg").html(Math.round(result.list[i].main.temp - 273.15)+"°C");
改成直接转换并显示华氏度:
$("#cur-deg").html(Math.round((result.list[0].main.temp*(9/5)) - 459.67)+"°F"); $next.eq(i-1).find(".next-deg").html(Math.round((result.list[i].main.temp*(9/5)) - 459.67)+"°F");
2. 调整温度切换按钮逻辑
原来的逻辑是默认显示摄氏度,切换到华氏度,现在要反过来:
找到这段切换代码:
if(t=="cel") { $this.html(Math.round((weatherData.list[i].main.temp*(9/5)) - 459.67)+"°F"); $this.attr("data-temp", "far"); } else { $this.html(Math.round(weatherData.list[i].main.temp - 273.15)+"°C"); $this.attr("data-temp", "cel"); }
修改为:
if(t=="far") { // 当前是华氏度,切换为摄氏度 $this.html(Math.round(weatherData.list[i].main.temp - 273.15)+"°C"); $this.attr("data-temp", "cel"); } else { // 当前是摄氏度,切换为华氏度 $this.html(Math.round((weatherData.list[i].main.temp*(9/5)) - 459.67)+"°F"); $this.attr("data-temp", "far"); }
同时找到HTML中的温度切换按钮,将其data-temp属性值从cel改为far,确保初始状态是华氏度模式。
方法二:用API参数直接返回华氏度(更简单)
OpenWeatherMap支持通过units=imperial参数直接返回华氏度,省去手动转换步骤:
1. 给所有API请求添加units=imperial参数
找到代码中所有构建API URL的地方,比如你提供的固定坐标URL:
var api = "https://api.openweathermap.org/data/2.5/forecast?lat=42.1237&lon=-71.1787&units=imperial";
如果代码里有自动通过IP获取位置的逻辑(比如根据用户IP获取经纬度再拼接URL),也要把&units=imperial加进去,示例:
// 原拼接代码 var api = "https://api.openweathermap.org/data/2.5/forecast?lat=" + lat + "&lon=" + lon + "&appid=" + appid; // 修改后 var api = "https://api.openweathermap.org/data/2.5/forecast?lat=" + lat + "&lon=" + lon + "&units=imperial&appid=" + appid;
2. 修改温度显示代码
此时API返回的main.temp已经是华氏度数值,直接取数显示即可:
// 当前温度 $("#cur-deg").html(Math.round(result.list[0].main.temp)+"°F"); // 未来温度 $next.eq(i-1).find(".next-deg").html(Math.round(result.list[i].main.temp)+"°F");
3. 调整切换逻辑(如需保留切换功能)
现在默认是华氏度,切换到摄氏度需要做华氏度转摄氏度的计算:
if(t=="far") { // 华氏度转摄氏度 var celsius = Math.round((weatherData.list[i].main.temp - 32) * 5/9); $this.html(celsius + "°C"); $this.attr("data-temp", "cel"); } else { // 显示华氏度 $this.html(Math.round(weatherData.list[i].main.temp)+"°F"); $this.attr("data-temp", "far"); }
内容的提问来源于stack exchange,提问作者KHSharon
相关产品推荐
相关产品推荐

