Wednesday, May 30, 2012

Embed OpenLayers with OpenStreetMap in JavaFX WebView

OpenLayers makes it easy to put a dynamic map in any web page. With OpenStreetMap, it's a free replacement of Google Maps. We can embed WebView loaded with OpenLayers in JavaFX to display map.

Embed OpenLayers with OpenStreetMap in JavaFX WebView


Create a HTML file, openstreetmap.html. Actually it's a normal web page HTML file.
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8" />
 <script type="text/javascript" src="http://openlayers.org/api/2.11/OpenLayers.js"></script>
 <script type="text/javascript" >
  var myMap;
   
  function loadOpenLayers(){  
   
   myMap = new OpenLayers.Map("mymap", {});
    
   var wms = new OpenLayers.Layer.WMS(
    "OpenLayers WMS",
    "http://vmap0.tiles.osgeo.org/wms/vmap0",
    {layers: "basic"},
    {});
     
   myMap.addLayer(wms);
 
   myMap.setCenter(new OpenLayers.LonLat(-122.349243, 47.651743));
   myMap.zoomTo(6);   
  } 
  
 </script>
</head>
<body onload="loadOpenLayers();">
 <div id="mymap" style="width: 620px; height: 460px; border: 1px solid;">
 </div>
 
</body>
</html>


Java Code
package javafx_openstreetview;

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_OpenStreetView extends Application {
    
    private Scene scene;
    MyBrowser myBrowser;
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
    @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();
    }
    
    class MyBrowser extends Region{
        
        HBox toolbar;

        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();
        
        public MyBrowser(){
            
            final URL urlGoogleMaps = getClass().getResource("openstreetmap.html");
            webEngine.load(urlGoogleMaps.toExternalForm());
            
            getChildren().add(webView);
        
        }
    }
}


Related:
- Embed Google Maps in JavaFX WebView.
- Embed WebView in FXML, to load OpenLayers with OpenStreetMap.


No comments:

Post a Comment