Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

| Views: 7390
I've had my JPhotoFrame project using the OpenWeatherMap API for some time now, at least since Yahoo messed up its own weather service. I thought it would be useful to share a bit of code on how to use the OWM API, so here it is.

I'm using the OWM JAPIs library, which is compatible with the OWM 2.5 version API.

In order to use OWM programatically, an API key is required. This unfortunately means that the end user has to get their own key too, it's free and not a big deal but is a little bit of an annoyance to have to go through. To get an API key for OWM, first an account is required, one can be created on the OWM sign-up page. After signing up, the API key is available. Update: on the updated site there is an API keys tab.

So here's the bit of code to get a three day forecast and display the minimum and maximum temperature for those days. All of the code is straight forward, it's just a matter of using the right classes.
 OWM Example
public class WeatherTest {
public static final void main(String[] args) {
boolean isMetric = true;
String weatherCity = "Brisbane,AU";
byte forecastDays = 3;
OpenWeatherMap.Units units = (isMetric)
? OpenWeatherMap.Units.METRIC
: OpenWeatherMap.Units.IMPERIAL;
OpenWeatherMap owm = new OpenWeatherMap(units, owmApiKey);
try {
DailyForecast forecast = owm.dailyForecastByCityName(weatherCity, forecastDays);
System.out.println("Weather for: " + forecast.getCityInstance().getCityName());
int numForecasts = forecast.getForecastCount();
for (int i = 0; i < numForecasts; i++) {
DailyForecast.Forecast dayForecast = forecast.getForecastInstance(i);
DailyForecast.Forecast.Temperature temperature = dayForecast.getTemperatureInstance();
System.out.println("\t" + dayForecast.getDateTime());
System.out.println("\tTemperature: " + temperature.getMinimumTemperature() +
" to " + temperature.getMaximumTemperature() + "\n");
catch (IOException | JSONException e) {

This is the output that the code above produces (it's hot in Australia on the first day of 2017!)
Weather for: Brisbane
Sun Jan 01 11:00:00 EST 2017
Temperature: 23.1 to 27.0
Mon Jan 02 11:00:00 EST 2017
Temperature: 23.25 to 30.04
Tue Jan 03 11:00:00 EST 2017
Temperature: 22.25 to 25.1


Have comments or feedback on what I wrote? Please share them below! Found this useful? Consider sending me a small tip.
comments powered by Disqus
Other posts you may like...