通过Webview将URL从Java类传递到html

时间:2019-08-05 16:47:37

标签: javascript java webview

我正在使用Java桌面应用程序(Maven构建)。如果存在互联网连接,Webview将加载map.html以显示openstreetmaps.org,如果互联网连接不存在,Webview将显示地图图块(png)。这是通过openlayers.js库实现的。我的目标是能够访问用户文件系统上的图块,例如,与生成的jar处于同一级别。

我尝试通过Webview将tile文件夹的绝对路径传递给html,但没有成功。

Controller.java

 private void loadMap() {
    final URL urlOSMaps = getClass().getResource("/html/Map.html");

     File tileFolder = new File("./tiles/");
     if(tileFolder.exists()) System.out.println("exits");

    String pathToTiles= tileFolder.getAbsolutePath();
    String pathToTilesCorrected= pathToTiles.replaceAll("\\\\", "/");

    webEngine.getLoadWorker().stateProperty().addListener((ov, oldState, newState) -> {
        if (newState == Worker.State.SUCCEEDED) {
            JSObject win = (JSObject) webEngine.executeScript("window");
            win.setMember("controlParent", this);
            win.setMember("tilesUrl", pathToTilesCorrected);
            String script = "";

            if (isAvailableConnection()) {
                script = "mapSource.set('OSM');";


            } else {
                System.out.println("Online map not available looking for tiles...");

                script = "mapSource.set('local');";
                             }

            try {
                webEngine.executeScript(script);
            } catch (netscape.javascript.JSException jse) {
                jse.printStackTrace();
            }
        } 

Map.html

 <script>  
    var GeoControlParent;
    //var select = new ol.interaction.Select(); 
    var tilesUrl;

    var mapSource = (function(){
        var osmSource;
        return{
            get: function()
            {
                return osmSource;
            },
            set: function(source)
            {

                    osmSource = new ol.source.OSM({
                                    /*attributions: [
                                      'All maps © <a href="https://www.osm.org/">OpenStreetMaps</a>',
                                      ATTRIBUTION
                                    ],*/
                                     url: str.concat(tilesUrl, '/tiles/tiles/{z}/{x}/{y}.png');
                                  });
            }
        }
    })();

我在做什么错了?

0 个答案:

没有答案