[英]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(degree>22.5 && degree<67.5){return 'North Easterly';}
else if(degree>67.5 && degree<112.5){return 'Easterly';}
else if(degree>122.5 && degree<157.5){return 'South Easterly';}
else if(degree>157.5 && degree<202.5){return 'Southerly';}
else if(degree>202.5 && degree<247.5){return 'South Westerly';}
else if(degree>247.5 && degree<292.5){return 'Westerly';}
else if(degree>292.5 && degree<337.5){return 'North Westerly';}
}
https://compuweather.com/files/2009/10/CompuWeather-Wind-Direction-Compass-Chart.pdf on the above link you can find the direction representation, i want to change the degree to textual for as, North, NorthEast, East, SouthEast, South, south west, west , and Northwest could you suggest a better way of doing this.how can i improve it? https://compuweather.com/files/2009/10/CompuWeather-Wind-Direction-Compass-Chart.pdf在上面的链接中,您可以找到方向表示,我想将程度更改为文本,例如 as、North、NorthEast 、东、东南、南、西南、西和西北你能提出一个更好的方法吗?我怎样才能改进它? i am using Javascript.我正在使用 Javascript。
You do not need so many checks in if
statements.您不需要在if
语句中进行这么多检查。 Also, you do not need else if because return will end function execution in proper places.此外,您不需要 else if 因为 return 将在适当的位置结束函数执行。
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';
}
Here's a way to do it with an array of sector names.这是一种使用扇区名称数组的方法。 This will also work for values < 0 and > 360这也适用于 < 0 和 > 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));
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)];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.