
Here are two methods that can help transform the JSON wind data returned by Openweathermap API into units that users will find easier to understand.
I have used these in my own application to convert a JSON response of:
"wind": {
"speed": 5.7,
"deg": 50
},
into:
Wind speed: 12.75 mph in a North East direction.
speed
The default unit of measurement for wind speed is meter/second. To convert this into Miles per Hour(mph) I used this formula(PDF) by National Weather Service This multiples the meter/sec value by 2.23694.
Here is my Typscript implementation.
convertMetersPerSecToMPH(mps: number): number {
const mph = +((2.23694 * mps).toFixed(2));
return mph;
}
After multiplying the Meter\Second value (mps) I want two digits after the decimal point so I have used toFixed which returns a string which I convert back to a number using +
deg
deg is the wind direction and the default unit of measurement is degrees (meteorological). To convert the value to a point on a compass I used this answer from Stack Overflow which is based on another answer.
Here is my Typescript implementation:
convertDegreeToCompassPoint(wind_deg: number): string {
const compassPoints = ["North", "North North East", "North East", "East North East",
"East", "East South East", "South East", "South South East",
"South", "South South West", "South West", "West South West",
"West", "West North West", "North West", "North North West"];
const rawPosition = Math.floor((wind_deg / 22.5) + 0.5);
const arrayPosition = (rawPosition % 16);
return compassPoints[arrayPosition];
};
The method creates an array containing the compass points. The raw position constant is calculated and will contain a number that will correspond to the position in the array. If you want to know more the Stack Overflow answers have explanations along with comments for what the magic numbers represent.
Acknowledgements
The National Weather Service for the formula to convert meters\second into Miles Per Hour.
The Stack Overflow answers here and here that helped me understand how to convert wind direction to compass points.