【问题标题】:How to get the weather conditions based on the user’s current GPS location如何根据用户当前的 GPS 位置获取天气状况
【发布时间】:2017-12-27 21:30:56
【问题描述】:

除了当前位置显示在其他地方之外,一切都适用于我的代码。我住在 Kuils River,它为我提供了 Edgemead 的天气状况。我如何获得我所在的当前位置?谁能帮我解决这个问题。

$(document).ready(function() {
  var lat, lon, api_url;

  if ("geolocation" in navigator) {
    $('#showTemp').on('click', function() {
      navigator.geolocation.getCurrentPosition(gotLocation);

      function gotLocation(position) {
        lat = position.coords.latitude;
        lon = position.coords.longitude;

        api_url = 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&units=metric&appid=b231606340553d9174136f7f083904b3';
        APPID: '53f9d8e4213222cf517d86dc406d67fc'

        $.ajax({
          url: api_url,
          method: 'GET',
          success: function(data) {
            var tempr = data.main.temp;
            var location = data.name;
            var desc = data.weather.description;
            $('#result').text(tempr + '°' + location);
          }
        });
      }
    });
  } else {
    alert('Your browser doesnt support geolocation. Sorry.');
  }
});

【问题讨论】:

  • 那段代码不是这样做的吗?
  • 这与您的代码无关,因为它是正确的。地理位置可能不精确
  • 代码给了我天气和位置,但区域错误我住在 Kuils River 它给了我一个位置名称 Edgemead
  • I live in Kuils River and it gives me the weather conditions for Edgemead 这只是由于 API 或地理位置不准确造成的。代码本身很好。您唯一的解决方案是使用具有更好 GPS 模块的设备,或者找到在区域报告方面具有更高粒度的 API

标签: javascript jquery geolocation location weather-api


【解决方案1】:

我注意到一个错误:

api_url = 'http://api.openweathermap.org/data/2.5/weather?lat=' +
          lat + '&lon=' + 
          lon + '&units=metric&appid=b231606340553d9174136f7f083904b3';
          APPID: '53f9d8e4213222cf517d86dc406d67fc'

//

appid 有两次。你能给我你期望的坐标(纬度,经度)吗?您应该能够直接在浏览器中插入 url 以查看您得到的内容。你试过吗?

【讨论】:

  • 这是他们给我的任务。编写一个单页应用程序,根据用户当前的 GPS 位置显示天气状况。欢迎您使用您选择的框架(Angular、Ember、React 等)。使用 Git 进行版本控制——并在提交测试时向我们发送指向您的存储库的链接。
  • 在这种情况下,框架无关紧要。这只是一个api调用。您修复了 appid 并重试了吗?
  • 您是否遇到任何错误?我注意到它没有通过 ssl/https 提供服务,这给我在 jsfiddle 中造成了问题。
  • 不,我没有得到任何错误,温度是正确的,它只是位置,但我想如果我不正确的位置,我会保持原样,因为代码没有任何问题
【解决方案2】:

位置基于您的 Internet 连接“中断”的位置,此代码似乎使用浏览器/HTML5 getCurrentPosition() API。

用实际的 GPS 值替换它会更准确。

【讨论】:

    猜你喜欢
    • 2013-03-03
    • 2014-09-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 2016-12-01
    相关资源
    最近更新 更多