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);

        }
    }
}


No comments:

Post a Comment