javascript - 用户所在位置下雪时激活js

标签 javascript jquery html weather-api

所以我有一个js,我只想在用户区域下雪时激活。

这是一个 JSFiddle Here

<h1 onclick="snowStorm.toggleSnow();">
text
</h1>

<script src="https://web.archive.org/web/20161109225359/http://live.superedu.ml/snow.js"></script>
<script>
snowStorm.followMouse = false;
    snowStorm.freezeOnBlur = true;
    snowStorm.autoStart = false;

</script>

如果您单击“测试”,则会激活雪。 当用户所在的地方下雪时,我该如何制作它来激活雪。谢谢

最佳答案

首先,您需要知道用户所在位置是否正在下雪。因此,您需要知道的第一件事是它们在哪里。为此,您可以使用 IP 地理定位服务。去谷歌上查询。其中之一是https://freegeoip.net/

接下来您需要向气象服务询问天气情况。 查看https://darksky.net/dev/docs/forecast

为了向 DarkSky API 等服务提出问题,您需要告诉他们您对预测感兴趣的位置,即您使用从上面的地理定位服务收到的位置坐标的位置。

然后您将收到来自 DarkSky API 的响应“对象”,其中包含大量信息,其中降水信息如下所述:

precipType optional
The type of precipitation occurring at the given time. If defined, this property will have one of the following values: "rain", "snow", or "sleet" (which refers to each of freezing rain, ice pellets, and “wintery mix”). (If precipIntensity is zero, then this property will not be defined.)
https://darksky.net/dev/docs/response

之后您可以按照以下方式编写代码

if (data.precipType === 'snow') { // do something }

总的来说,它是这样的:

  1. 向 GeoIP 发送请求(ip 8.8.8.8 在哪里?)
  2. 接收来自 GeoIP 的响应(纬度:1.2345 经度:1.432)
  3. 向 DarkSky 发送请求(今天的天气 lat:1.2345 lon:1.432 ?)
  4. 收到来自 DarkSky 的回复(雪!)
  5. ...做事...

如何

为了成功完成此练习,您需要熟悉一下 JS 中的基本异步编程,以及如何发送 AJAX 请求,并使用您收到的回复。

简而言之,您需要学习如何编写仅在功能 A 完成后才能启动功能 B 的代码(在未知的时间后,例如通过网络请求时)

所以事情看起来更像是这样:

1. Send request to GeoIP (where is ip 8.8.8.8 ?)
  2. Receive response from GeoIP (it's at lat:1.2345 lon:1.432)
    3. Send request to DarkSky (what's the weather today at lat:1.2345 lon:1.432 ?)
      4. Receive response from DarkSky (snow!)
        5. … do stuff …

搜索此内容的好关键字是 jQuery AJAX、回调和更高级的 Promises。但从前两个开始。

祝你好运!

关于javascript - 用户所在位置下雪时激活js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40517868/

相关文章:

javascript - 滚动时捕获第一个可见的 div id(视口(viewport))

javascript - 如何将一行中的所有数据复制到所有其他行

javascript - 使用 JavaScript 设置属性时是否需要转义属性?

html - 从浏览器底部取消附加页脚

javascript - 从 IE 11 中的 iframe 获取 html 代码作为字符串

Javascript从ajax函数传递变量

javascript - Bootstrap Accordion 刷新设置

html - 子菜单垂直对齐

JavaScript 实例 : can't define what instance of function's argument is

javascript - 您可以测试 Safari 和 Chrome (iOS) 上的滚动差异吗?