How can I modify JS Openweathermap temperature values

72 views Asked by At

I'd like to repurpose the following openweathermap JS weather app for my work project:

https://codepen.io/stack-findover/pen/vYgQrPP

The app defaults the temperature value to Celsius, and i'd like to modify it to default to Fahrenheit instead.

I've attempted to modify the following lines without success. The main problem being, I don't understand how the code calculates Celsius vs Fahrenheit.

$("#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");

  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");

I've also attempted to modify the openweathermap url to include &units=imperial.. but that will not override the code that returns temp by IP automatically.

var api = "https://api.openweathermap.org/data/2.5/forecast?lat=42.1237&lon=-71.1787&units=imperial";

Disclaimer, i'm a complete noob with JavaScript.

Thanks for any help you can provide.

1

There are 1 answers

1
James On

Try changing

$("#cur-deg").html(Math.round(result.list[0].main.temp - 273.15)+"°C");

to

$("#cur-deg").html(Math.round((result.list[0].main.temp * (9/5)) - 459.67)+"°F");

Similarly

$next.eq(i-1).find(".next-deg").html(Math.round(result.list[i].main.temp - 273.15)+"°C");

becomes

$next.eq(i-1).find(".next-deg").html(Math.round((result.list[i].main.temp * (9/5)) - 459.67)+"°F");

Note that you should set all the data-temp attributes in your html to "far", since that will be the default state.