summaryrefslogtreecommitdiff
path: root/examples/demos/src/main/scala/webpage/Weather3.scala
blob: 4dadf9412fc72753b2c8e1de1603cbafefcddca9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package webpage

import org.scalajs.dom
import org.scalajs.dom.{Node, Element}
import scala.scalajs.js
import scala.scalajs.js.annotation.JSExport
import scalatags.JsDom.all._

@JSExport
object Weather3 extends{
  @JSExport
  def main(target: dom.HTMLDivElement) = {
    import dom.extensions._
    import scala.scalajs
    .concurrent
    .JSExecutionContext
    .Implicits
    .runNow

    val url =
      "http://api.openweathermap.org/" +
        "data/2.5/weather?q=Singapore"

    Ajax.get(url).onSuccess{ case xhr =>
      if (xhr.status == 200) {
        val json = js.JSON.parse(
          xhr.responseText
        )
        val name = json.name.toString
        val weather = json.weather
                          .pop()
                          .main
                          .toString

        def celsius(kelvins: js.Dynamic) = {
          kelvins.asInstanceOf[Double] - 273.15
        }.toInt
        val min = celsius(json.main.temp_min)
        val max = celsius(json.main.temp_max)
        val humid = json.main.humidity.toString
        target.appendChild(
          div(
            b("Weather in Singapore:"),
            ul(
              li(b("Country "), name),
              li(b("Weather "), weather),
              li(b("Temp "), min, " - ", max),
              li(b("Humidity "), humid, "%")
            )
          ).render
        )
      }
    }
  }
}