如何创建JavaFx应用程序的实例并推送自己的参数?

时间:2017-10-08 16:53:14

标签: java google-maps javafx google-maps-markers

我正在尝试使用Google Maps Api + JavaFx创建地图。在主类我读取JSON文件然后创建集群,程序点是将这些集群显示为具有位置数量的标记。 所以在主类中我读取JSON文件然后创建DBSCANClusterer clusterer = new DBSCANClusterer(coordinates, 2, 2);,我必须将其推送到类GoogleMap,其中JavaFX正在创建webView,依此类推。我也用这个在我的html文件中的脚本中使用java代码:

JSObject jsobj = (JSObject) webView.getEngine()
             .executeScript("window");
     jsobj.setMember("BrowserJavaObject", new BrowserJavaObject(clusterer));

然后必须在BrowserJavaObject类中进一步推送相同的东西,其中所有聚类计算都是。 我试图创建GoogleMap类的对象,但这不起作用。 那么如何让它发挥作用呢?或者这甚至可能吗?谢谢你的建议。

JSONMain类:

public class JsonMain {

     static List<Coordinate> coordinates = new ArrayList<>();

    private static final String ITEMS_NAME = "items";
    private static final String LATITUDE_PROPERTY = "latitude";
    private static final String LONGITUDE_PROPERTY = "longitude";
    private static final String CRASH_NAME = "em_type_name";

    static void parseCrashCoordinates(final JsonReader jsonReader, final ICoordinatesListener listener)
            throws IOException {    
        // Reading JSON file
    }

     // Collecting all coordinates in ArrayList.
    private static void testCollecting()
            throws IOException {
      //  List<Coordinate> coordinates = new ArrayList<>();
        readAndParse((lat, lng) -> coordinates.add(new Coordinate(lat, lng)));
        System.out.println(coordinates.size());   
    }

    public static void main(String[] args) throws IOException, URISyntaxException {
        testCollecting();  


     // Initialize our clustering class with locations, minimum points in cluster and max Distance
        DBSCANClusterer clusterer = new DBSCANClusterer(coordinates, 2, 2);

        GoogleMap gm = new GoogleMap(clusterer);
        gm.launch(GoogleMap.class);
    }

GoogleMap类:

public class GoogleMap extends Application {

private DBSCANClusterer clusterer ;

public GoogleMap(DBSCANClusterer c) {
    this.clusterer = c;
}


@Override 
public void start(Stage stage) throws MalformedURLException {

    File file = new File("C:/Users/Evgeny/git/Diploma_MSU/diploma/html/map.html");
    URL url222 = file.toURI().toURL();

     WebView webView = new WebView();
     final WebEngine webEngine = webView.getEngine();

     JSObject jsobj = (JSObject) webView.getEngine()
             .executeScript("window");
     jsobj.setMember("BrowserJavaObject", new BrowserJavaObject(clusterer));

    webEngine.load(url222.toString()); 

    // create scene
    stage.setTitle("Web Map");
    Scene scene = new Scene(webView,1000,700, Color.web("#666970"));
    stage.setScene(scene);
    // show stage
    stage.show();

} 
}

BrowserJavaObject类:

public class BrowserJavaObject {

private DBSCANClusterer clusterer ;

public BrowserJavaObject(DBSCANClusterer c) {
    this.clusterer = c;
}

public String showMarkers() {
    ArrayList<ArrayList<Coordinate>> clusters_raw= this.clusterer.performClustering();
    ArrayList<Cluster> clusters = new ArrayList<>();

    String pointsArray = " [ ";
    for(int i=0; i<clusters_raw.size(); i++) {
            Cluster c = new Cluster(clusters_raw.get(i));
            clusters.add(c);

            pointsArray += c.getLocationAsArray() + " , ";
    }
    pointsArray += "]";

    System.out.println("Number Of Clusters Created: "+clusters.size());
    return pointsArray;

}
}

map.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Map</title>
<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 async defer type="text/javascript"
            src="https://maps.googleapis.com/maps/api/js?callback=loadmap">
    </script>
</head>
<body onload="loadmap()">
<div id="map_canvas" style="width:100%; height:100%"></div>
<script>
var map;
function loadmap(){

  var options = {
      zoom: 16,
      center: new google.maps.LatLng(55.7558, 37.6173),
      mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map_canvas"), options);

  var markers = [];

  // Call the Java code to calculate clusters data, and save the returned clusters into a variable
  var markers_data = BrowserJavaObject.showMarkers();

  for( var i=0; i<markers_data.length; i++ ){
    var position = markers_data[i];
    var icon = "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2238%22%20height%3D%2238%22%20viewBox%3D%220%200%2038%2038%22%3E%3Cpath%20fill%3D%22%23a22%22%20stroke%3D%22%23ccc%22%20stroke-width%3D%22.5%22%20d%3D%22M34.305%2016.234c0%208.83-15.148%2019.158-15.148%2019.158S3.507%2025.065%203.507%2016.1c0-8.505%206.894-14.304%2015.4-14.304%208.504%200%2015.398%205.933%2015.398%2014.438z%22%2F%3E%3Ctext%20transform%3D%22translate%2819%2018.5%29%22%20fill%3D%22%23fff%22%20style%3D%22font-family%3A%20Arial%2C%20sans-serif%3Bfont-weight%3Abold%3Btext-align%3Acenter%3B%22%20font-size%3D%2212%22%20text-anchor%3D%22middle%22%3E" 
                + position[2]
              + "%3C%2Ftext%3E%3C%2Fsvg%3E";

//    if(zoom > 11) icon = null; //Default to marker with no number if at city zom level

    markers.push( new google.maps.Marker({
                    position: new google.maps.LatLng( position[0], position[1] ),
                    map: map,
                    title: position[2],
                    text: position[2],
                    icon: icon
                }) 
    );
  } 
}
</script>
</body>
</html>

所以地图已加载但没有集群。并且最终没有调用所有这些聚类方法,因为我的clusterer对象在其他类中没有进一步传递。

非常感谢!

1 个答案:

答案 0 :(得分:1)

您正在以错误的方式使用Application类。 Application类代表您的整个应用程序,并负责其生命周期;特别是它有一个start()方法,当通过调用launch()启动JavaFX工具包时,会调用该方法。 Application课程并不代表您的用户界面的特定部分(这是GoogleMap课程所针对的部分)。

所以你应该让JsonMain成为Application的子类,而不是GoogleMap,你应该将启动代码移动到(恰当命名的)start()方法:< / p>

public class GoogleMap {

    private DBSCANClusterer clusterer ;

    private final WebView view ;

    public GoogleMap(DBSCANClusterer c) throws MalformedURLException {
        this.clusterer = c;

        File file = new File("C:/Users/Evgeny/git/Diploma_MSU/diploma/html/map.html");
        URL url222 = file.toURI().toURL();

        view = new WebView();
        final WebEngine webEngine = webView.getEngine();

        JSObject jsobj = (JSObject) webView.getEngine()
                 .executeScript("window");
        jsobj.setMember("BrowserJavaObject", new BrowserJavaObject(clusterer));

        webEngine.load(url222.toString()); 

    } 

    public Node getView() {
        return view ;
    }

}

public class JsonMain extends Application {

    static List<Coordinate> coordinates = new ArrayList<>();

    private static final String ITEMS_NAME = "items";
    private static final String LATITUDE_PROPERTY = "latitude";
    private static final String LONGITUDE_PROPERTY = "longitude";
    private static final String CRASH_NAME = "em_type_name";

    static void parseCrashCoordinates(final JsonReader jsonReader, final ICoordinatesListener listener)
            throws IOException {    
        // Reading JSON file
    }

     // Collecting all coordinates in ArrayList.
    private static void testCollecting()
            throws IOException {
      //  List<Coordinate> coordinates = new ArrayList<>();
        readAndParse((lat, lng) -> coordinates.add(new Coordinate(lat, lng)));
        System.out.println(coordinates.size());   
    }

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

    @Override
    public void start(Stage stage)  
        throws IOException, URISyntaxException, MalformedURLException {

        testCollecting();  


     // Initialize our clustering class with locations, minimum points in cluster and max Distance
        DBSCANClusterer clusterer = new DBSCANClusterer(coordinates, 2, 2);

        GoogleMap gm = new GoogleMap(clusterer);

        // create scene
        stage.setTitle("Web Map");
        Scene scene = new Scene(gm.getView(), 1000, 700, Color.web("#666970"));
        stage.setScene(scene);
        // show stage
        stage.show();

    }

}

您应该进一步重构,以便妥善区分您的疑虑;例如它可能不是你的Application类的工作来解析数据等。但这至少可以让你将参数传递给你的GoogleMap类,并允许你启动应用程序预定的方式。