Tuesday, February 12, 2013

Embed Google Maps API v3 in JavaFX WebView

Embed Google Maps API v3 in JavaFX WebView
Embed Google Maps API v3 in JavaFX WebView

Note:
  • In order to use Google Maps API v3 in your application, you have to obtain API Key. Read here: Obtain API Key for Google Maps API v3.
  • In the current version, it seem that there are problem in mouse gesture action on Map; you cannot plan on the may.

package javafxgooglemaps;

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 JavaFXGoogleMaps extends Application {
    
    private Scene scene;
    MyBrowser myBrowser;
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("java-buddy.blogspot.com");
        primaryStage.setWidth(400);
        primaryStage.setHeight(300);
        myBrowser = new MyBrowser();
        scene = new Scene(myBrowser, 400, 300);
        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("GoogleMapsV3.html");
            webEngine.load(urlGoogleMaps.toExternalForm());
            webEngine.setJavaScriptEnabled(true);
            
            getChildren().add(webView);
         
      }
    }
}


Create a html file, GoogleMapsV3.html.
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map_canvas { height: 100% }
    </style>
    <script type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?key=< your API Key >&sensor=false">
    </script>
    <script type="text/javascript">
      function initialize() {
        var mapOptions = {
          center: new google.maps.LatLng(-34.397, 150.644),
          zoom: 8,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"),
            mapOptions);
      }
    </script>
  </head>
  <body onload="initialize()">
    <div id="map_canvas" style="width:400px; height:300px"></div>
  </body>
</html>


No comments:

Post a Comment