Bila Hassan
Bila Hassan

Reputation: 33

How to pass a Java array to javascript

I have a JavaFX application that shows the location point on Google maps. It is working fine when I pass only variables in javascript. Hhere is the code in JavaFX where I am passing the variables name (lat and lon)

  public void handle(ActionEvent arg0) {
                lat = Double.parseDouble(latitude.getText());
                lon = Double.parseDouble(longitude.getText());

                System.out.printf("%.2f %.2f%n", lat, lon);

                webEngine.executeScript("" +
                    "window.lat = " + lat + ";" +
                    "window.lon = " + lon + ";" +
                    "document.goToLocation(window.lat, window.lon);"
                );
            }
        });

I want to pass a double array instead of double variable. Here is the javascript function where I am receiving values from Java variable name (x and y)

 document.goToLocations = function(x, y) {
        alert("goToLocation, x: " + x +", y:" + y);
        var latLng = new google.maps.LatLng(x, y);
        marker.setPosition(latLng);
        map.setCenter(latLng);


    }

And here is the code example link that i am using Code Example

Upvotes: 2

Views: 290

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79075

You can do something like:

public void handle(ActionEvent arg0) {
    List<Double> list = List.of(Double.parseDouble(latitude.getText()), Double.parseDouble(longitude.getText()));
    //Pass list.toString() to the JavaScript function
    //...
}

document.goToLocations = function(values) {
    var x = values.split(", ");
    alert(x);
    alert(x[0]);
    //...
}

List.of was added in Java9. For Java version lower than 9, use the following statement:

List<Double> list = Arrays.asList(Double.parseDouble(latitude.getText()), Double.parseDouble(longitude.getText()));

-OR-

List<Double> list = new ArrayList<Double>();
list.add(Double.parseDouble(latitude.getText()));
list.add(Double.parseDouble(longitude.getText()));

Upvotes: 1

Related Questions