Wednesday, March 28, 2012

Embed Google Maps in JavaFX WebView

The Google Maps Javascript API lets you embed Google Maps in your own web pages. With WebView in JavaFX 2.0, you can easy embed Google Maps in your Java application.

Embed Google Maps in JavaFX WebView

Create a googlemaps.html to embed Google Maps in web page.
<!DOCTYPE html>
<html>
<head>
<title>Java-Buddy: Google Maps</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<style>#mapcanvas { height: 360px; width: 100%}</style>

<script>
var map;
function loadmap(){

var options = {
zoom: 16,
center: new google.maps.LatLng(51.507222, -0.1275),
mapTypeId: google.maps.MapTypeId.SATELLITE
}
map = new google.maps.Map(document.getElementById("mapcanvas"), options);
}

</script>

</head>
<body onload="loadmap()">
<h1>Java-Buddy: Google Maps</h1>
<div id="mapcanvas"></div>
</body>
</html>


Embed googlemaps.html in WebView in your Java application.
package javafx_googlemaps;

import java.net.URL;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.VPos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

/**
*
* @web http://java-buddy.blogspot.com/
*/
public class JavaFX_GoogleMaps 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("googlemaps.html");
webEngine.load(urlGoogleMaps.toExternalForm());

getChildren().add(webView);

}

}
}


Related:
- Embed OpenLayers with OpenStreetMap in JavaFX WebView


No comments:

Post a Comment