如何修改OpenWeatherMap JS代码以使用指定经纬度坐标
问题
我正在改造一个基于OpenWeatherMap的JS天气应用,此前已发布相关问题,本次为后续问询。当前代码的getWeather函数采用城市搜索与地理定位获取天气数据,我希望将其修改为使用一组特定的经纬度(Lat/Long)坐标。我尝试修改OpenWeatherMap的API链接,但未得到预期结果,相关代码如下,请问最佳修改方式是什么?
原有核心代码片段:
var weatherData = {}; var api = "https://api.openweathermap.org/data/2.5/forecast?lat=&lon=-&units=imperial"; var id = "&APPID=acc38546e41e0baf9aa6ba45661c094b"; var cnt = "&cnt=4" var country=""; var ctyName = ""; var options = { weekday: "long", year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" };
完整业务逻辑代码:
var curDate = $("#cur-date"); curDate.html(new Date().toLocaleTimeString('en-US', options)); $.ajax({url: "https://ipinfo.io/json?"}) .done( function(res) { console.log(res); country = res.country; ctyName = "q="+res.city+","+country; getWeather(); }); function getWeather() { $.ajax({url: api+ctyName+id+cnt, dataType: 'json', success: function(result) { $('#loader').hide(); console.log(result); weatherData = result; var icons= []; $("#loc").html(result.city.name+", "+result.city.country); $("#cur-weath").html(result.list[0].weather[0].main); $("#cur-deg").html(Math.round((result.list[0].main.temp * (9/5)) - 459.67)+"°"); $("#cur-desc").html(result.list[0].weather[0].description); var icon = result.list[0].weather[0].icon; setBackground(icon); console.log(Icons[icon].icn); skycons.set("cur-icon",Icons[icon].icn); for(var i=1;i<4;i++) { var $next=$(".next-weath"); icons.push(result.list[i].weather[0].icon); var dt = new Date(result.list[i].dt_txt); if(dt == "Invalid Date") { //兼容IE的日期处理 var ar = result.list[i].dt_txt.split(" "); dt = new Date(ar[0]+"T"+ar[1]); } var hour = dt.toLocaleTimeString('en-US', {hour: "2-digit", minute: "2-digit", hour12: true, }); $next.eq(i-1).find(".next-hour").html(hour); $next.eq(i-1).find(".next-desc").text(result.list[i].weather[0].description); $next.eq(i-1).find(".next-deg").html(Math.round((result.list[i].main.temp * (9/5)) - 459.67)+"°"); skycons.set($next.eq(i-1).find(".next-icon")[0], Icons[icons[i-1]].icn); } }, error: function(error, errorType, errorMessage) { $("#loc").html("无法定位").next().hide(); }, beforeSend: function() { $("#loc").html("加载中").next().show(); }}); } $("button").on("click", getCityWeather); $("input").keydown(function(event){ if (event.which == 13) getCityWeather(); }); $(".next-deg").on("click", function() { if(weatherData) changeTempScale( $(this)); }); $("#cur-deg").on("click", function() { if(weatherData) changeTempScale( $(this)); }); function setBackground(icon) { $(".wrap").css('background-image', 'url(' + Icons[icon].bg + ')'); } function getCityWeather() { $("input").val() ctyName = "q="+$("input").val(); getWeather(); }
我尝试修改API链接但未成功,修改后的代码:
var weatherData = {}; var api = "https://api.openweathermap.org/data/2.5/forecast?lat=&lon=&units=imperial";
最佳修改方案
核心问题是原有代码同时混合了q(城市参数)和lat/lon(经纬度参数),导致接口无法正确识别请求条件。以下是分步修改方案:
1. 定义固定经纬度变量
替换原来的country、ctyName变量,直接声明目标经纬度:
var weatherData = {}; // 替换为你需要的目标经纬度,示例为北京坐标 const TARGET_LAT = "39.9042"; const TARGET_LON = "116.4074"; var api = "https://api.openweathermap.org/data/2.5/forecast?units=imperial"; var id = "&APPID=acc38546e41e0baf9aa6ba45661c094b"; var cnt = "&cnt=4" var options = { weekday: "long", year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" };
2. 移除地理定位请求
原来的ipinfo.io请求用于获取当前城市,现在改用固定经纬度,直接删除这段代码并调用getWeather():
var curDate = $("#cur-date"); curDate.html(new Date().toLocaleTimeString('en-US', options)); // 直接调用天气获取函数,无需地理定位 getWeather();
3. 修改getWeather函数的API拼接逻辑
把原来拼接ctyName的逻辑替换为拼接经纬度参数:
function getWeather() { // 拼接经纬度参数,替代原有的城市参数 const locationParams = `&lat=${TARGET_LAT}&lon=${TARGET_LON}`; $.ajax({ url: api + locationParams + id + cnt, dataType: 'json', success: function(result) { // 原有成功逻辑保持不变 $('#loader').hide(); console.log(result); weatherData = result; var icons= []; $("#loc").html(result.city.name+", "+result.city.country); $("#cur-weath").html(result.list[0].weather[0].main); $("#cur-deg").html(Math.round((result.list[0].main.temp * (9/5)) - 459.67)+"°"); $("#cur-desc").html(result.list[0].weather[0].description); var icon = result.list[0].weather[0].icon; setBackground(icon); console.log(Icons[icon].icn); skycons.set("cur-icon",Icons[icon].icn); for(var i=1;i<4;i++) { var $next=$(".next-weath"); icons.push(result.list[i].weather[0].icon); var dt = new Date(result.list[i].dt_txt); if(dt == "Invalid Date") { //兼容IE的日期处理 var ar = result.list[i].dt_txt.split(" "); dt = new Date(ar[0]+"T"+ar[1]); } var hour = dt.toLocaleTimeString('en-US', {hour: "2-digit", minute: "2-digit", hour12: true, }); $next.eq(i-1).find(".next-hour").html(hour); $next.eq(i-1).find(".next-desc").text(result.list[i].weather[0].description); $next.eq(i-1).find(".next-deg").html(Math.round((result.list[i].main.temp * (9/5)) - 459.67)+"°"); skycons.set($next.eq(i-1).find(".next-icon")[0], Icons[icons[i-1]].icn); } }, error: function(error, errorType, errorMessage) { $("#loc").html("无法获取天气数据").next().hide(); }, beforeSend: function() { $("#loc").html("加载中").next().show(); } }); }
4. 可选:移除城市搜索功能
如果不需要用户搜索城市的功能,可以删除以下代码:
$("button").on("click", getCityWeather); $("input").keydown(function(event){ if (event.which == 13) getCityWeather(); }); function getCityWeather() { $("input").val() ctyName = "q="+$("input").val(); getWeather(); }
修改完成后,应用将直接使用你指定的经纬度请求天气数据,不再依赖地理定位或城市搜索。
内容的提问来源于stack exchange,提问作者KHSharon
相关产品推荐
相关产品推荐

