Showing posts with label OpenWeatherMap. Show all posts
Showing posts with label OpenWeatherMap. Show all posts

Thursday, July 25, 2013

Embed OpenWeatherMap in JavaFX WebView

OpenWeatherMap provide Javascript library to let developer load OpenWeatherMap in web page. So we can easy embed OpenWeatherMap in WebView of JavaFX.

Embed OpenWeatherMap in JavaFX WebView
Embed OpenWeatherMap in JavaFX WebView
Create HTML file, OpenWeatherMap.html, to load OpenWeatherMap in webpage. Copy the example from OpenWeatherMap tutorial for web developers.

OpenWeatherMap.html
<html>
<head>
<title>Open Weather Map</title>
<script src="http://openlayers.org/api/OpenLayers.js"></script>
<script src="http://openweathermap.org/js/OWM.OpenLayers.1.3.4.js" ></script>
</head>
<body  onload="init()">
<div id="basicMap"></div>
</body>

<script type="text/javascript">
function init() {
 //Center of map
 var lat = 7486473; 
 var lon = 4193332;
 var lonlat = new OpenLayers.LonLat(lon, lat);
        var map = new OpenLayers.Map("basicMap");
 // Create overlays
 //  OSM
        var mapnik = new OpenLayers.Layer.OSM();
 // Stations
 var stations = new OpenLayers.Layer.Vector.OWMStations("Stations");
 // Current weather
 var city = new OpenLayers.Layer.Vector.OWMWeather("Weather");
 //Addind maps
 map.addLayers([mapnik, stations, city]);
 map.setCenter( lonlat, 10 );
}
</script>
</html>


Java code to load the OpenWeatherMap.html in JavaFX WebView.
package javafx_openweathermap;

import java.net.URL;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_OpenWeatherMap extends Application {

    private Scene scene;
    MyBrowser myBrowser;

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");

        myBrowser = new MyBrowser();
        scene = new Scene(myBrowser, 640, 480);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    class MyBrowser extends Region {

        HBox toolbar;
        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();

        public MyBrowser() {

            final URL urlGoogleMaps = getClass().getResource("OpenWeatherMap.html");
            webEngine.load(urlGoogleMaps.toExternalForm());

            getChildren().add(webView);

        }
    }
}


Wednesday, July 24, 2013

Parse JSON with Java SE and java-json, to search weather data from OpenWeatherMap

OpenWeatherMap provide APIs to search weather data in JSON, XML or HTML format. This example demonstrate how to parse JSON from OpenWeatherMap to search weather of London, UK.

Before we can use java-json in our project, follow the instruction to add JAR in NetBeans.

Example code:

package java_openweathermap;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Java_OpenWeatherMap {

    static final String URL_OpenWeatherMap_weather_London_uk =
            "http://api.openweathermap.org/data/2.5/weather?q=London,uk";

    public static void main(String[] args) {
        
        String result = "";
        
        try {
            URL url_weather = new URL(URL_OpenWeatherMap_weather_London_uk);

            HttpURLConnection httpURLConnection = (HttpURLConnection) url_weather.openConnection();

            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                InputStreamReader inputStreamReader =
                    new InputStreamReader(httpURLConnection.getInputStream());
                BufferedReader bufferedReader =
                    new BufferedReader(inputStreamReader, 8192);
                String line = null;
                while((line = bufferedReader.readLine()) != null){
                    result += line;
                }
                
                bufferedReader.close();
                
                String weatherResult = ParseResult(result);
                
                System.out.println(weatherResult);

            } else {
                System.out.println("Error in httpURLConnection.getResponseCode()!!!");
            }

        } catch (MalformedURLException ex) {
            Logger.getLogger(Java_OpenWeatherMap.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Java_OpenWeatherMap.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JSONException ex) {
            Logger.getLogger(Java_OpenWeatherMap.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    static private String ParseResult(String json) throws JSONException{
        
        String parsedResult = "";
     
        JSONObject jsonObject = new JSONObject(json);

        parsedResult += "Number of object = " + jsonObject.length() + "\n\n";
     
        //"coord"
        JSONObject JSONObject_coord = jsonObject.getJSONObject("coord");
        Double result_lon = JSONObject_coord.getDouble("lon");
        Double result_lat = JSONObject_coord.getDouble("lat");
     
        //"sys"
        JSONObject JSONObject_sys = jsonObject.getJSONObject("sys");
        String result_country = JSONObject_sys.getString("country");
        int result_sunrise = JSONObject_sys.getInt("sunrise");
        int result_sunset = JSONObject_sys.getInt("sunset");
        
        //"weather"
        String result_weather;
        JSONArray JSONArray_weather = jsonObject.getJSONArray("weather");
        if(JSONArray_weather.length() > 0){
            JSONObject JSONObject_weather = JSONArray_weather.getJSONObject(0);
            int result_id = JSONObject_weather.getInt("id");
            String result_main = JSONObject_weather.getString("main");
            String result_description = JSONObject_weather.getString("description");
            String result_icon = JSONObject_weather.getString("icon");
        
            result_weather = "weather\tid: " + result_id +"\tmain: " + result_main + "\tdescription: " + result_description + "\ticon: " + result_icon;
        }else{
            result_weather = "weather empty!";
        }
        
        //"base"
        String result_base = jsonObject.getString("base");
        
        //"main"
        JSONObject JSONObject_main = jsonObject.getJSONObject("main");
        Double result_temp = JSONObject_main.getDouble("temp");
        Double result_pressure = JSONObject_main.getDouble("pressure");
        Double result_humidity = JSONObject_main.getDouble("humidity");
        Double result_temp_min = JSONObject_main.getDouble("temp_min");
        Double result_temp_max = JSONObject_main.getDouble("temp_max");
        
        //"wind"
        JSONObject JSONObject_wind = jsonObject.getJSONObject("wind");
        Double result_speed = JSONObject_wind.getDouble("speed");
        //Double result_gust = JSONObject_wind.getDouble("gust");
        Double result_deg = JSONObject_wind.getDouble("deg");
        String result_wind = "wind\tspeed: " + result_speed + "\tdeg: " + result_deg;
        
        //"clouds"
        JSONObject JSONObject_clouds = jsonObject.getJSONObject("clouds");
        int result_all = JSONObject_clouds.getInt("all");
        
        //"dt"
        int result_dt = jsonObject.getInt("dt");
        
        //"id"
        int result_id = jsonObject.getInt("id");
        
        //"name"
        String result_name = jsonObject.getString("name");
        
        //"cod"
        int result_cod = jsonObject.getInt("cod");
        
        return 
            "coord\tlon: " + result_lon + "\tlat: " + result_lat + "\n" +
            "sys\tcountry: " + result_country + "\tsunrise: " + result_sunrise + "\tsunset: " + result_sunset + "\n" +
            result_weather + "\n"+
            "base: " + result_base + "\n" +
            "main\ttemp: " + result_temp + "\thumidity: " + result_humidity + "\tpressure: " + result_pressure + "\ttemp_min: " + result_temp_min + "\ttemp_max: " + result_temp_min + "\n" +
            result_wind + "\n" +
            "clouds\tall: " + result_all + "\n" +
            "dt: " + result_dt + "\n" +
            "id: " + result_id + "\n" +
            "name: " + result_name + "\n" +
            "cod: " + result_cod + "\n" +
            "\n";
    }
}


search weather data from OpenWeatherMap
search weather data from OpenWeatherMap

Note:
- It's a simple example, without handle error condition; such as service unavailable, some item missing...etc.


OpenWeatherMap

The OpenWeatherMap service provides free weather data and forecast API suitable for any cartographic services like web and smartphones applications. Ideology is inspired by OpenStreetMap and Wikipedia that make information free and available for everybody. OpenWeatherMap provides wide range of weather data such as map with current weather, week forecast, precipitation, wind, clouds, data from weather Stations and many others. Weather data is received from global Meteorological broadcast services and more than 40 000 weather stations.

All weather data can be obtained in JSON, XML or HTML format.

http://openweathermap.org/

For example, you can search weather of London in JSON format with "http://api.openweathermap.org/data/2.5/weather?q=London,uk". The return result will be like this:

{"coord":{"lon":-0.12574,"lat":51.50853},"sys":{"country":"GB","sunrise":1374639224,"sunset":1374696019},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"gdps stations","main":{"temp":297,"humidity":61,"pressure":1011,"temp_min":295.37,"temp_max":298.71},"wind":{"speed":0.51,"gust":0.51,"deg":199},"clouds":{"all":76},"dt":1374693664,"id":2643743,"name":"London","cod":200}


Examples:
Parse JSON with Java SE and java-json, to search weather data from OpenWeatherMap.
Embed OpenWeatherMap in JavaFX WebView
Another example to embed Open Weather Map in JavaFX WebView