Skip to content Skip to sidebar Skip to footer

I Have Wind Direction Data Coming From OpenWeatherMap API, And The Data Is Represented In 0 To 360 Degrees. I Want To Convert This Into Text Format

function toTextualDescription(degree){ if ((degree>337.5 && degree<360)|| (degree>22.5 && degree<22.5)) {return 'Northerly';} else if(degre

Solution 1:

You do not need so many checks in if statements. Also, you do not need else if because return will end function execution in proper places.

function  toTextualDescription(degree){
    if (degree>337.5) return 'Northerly';
    if (degree>292.5) return 'North Westerly';
    if(degree>247.5) return 'Westerly';
    if(degree>202.5) return 'South Westerly';
    if(degree>157.5) return 'Southerly';
    if(degree>122.5) return 'South Easterly';
    if(degree>67.5) return 'Easterly';
    if(degree>22.5){return 'North Easterly';}
    return 'Northerly';
}

Solution 2:

Here's a way to do it with an array of sector names. This will also work for values < 0 and > 360

function toTextualDescription(degree) {
  var sectors = ['Northerly','North Easterly','Easterly','South Easterly','Southerly','South Westerly','Westerly','North Westerly'];
  
  degree += 22.5;

  if (degree < 0) 
    degree = 360 - Math.abs(degree) % 360;
  else 
    degree = degree % 360;
  
  var which = parseInt(degree / 45);
  return sectors[which];
}

console.log("0: " + toTextualDescription(0));
console.log("-30: " + toTextualDescription(-30));
console.log("900: " + toTextualDescription(900));
console.log("22.4999: " + toTextualDescription(22.4999));
console.log("22.5: " + toTextualDescription(22.5));
console.log("359: " + toTextualDescription(359));

Solution 3:

let compassSector = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW", "N"];

weather.windDirection = compassSector[(data.wind.deg / 22.5).toFixed(0)];

Post a Comment for "I Have Wind Direction Data Coming From OpenWeatherMap API, And The Data Is Represented In 0 To 360 Degrees. I Want To Convert This Into Text Format"