You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaFX WebView无法嵌入Google Maps HTML页面问题求助

JavaFX WebView嵌入Google Maps显示空白矩形问题

测试普通HTML(仅文本和div)可正常嵌入JavaFX WebView,但嵌入包含Google Maps的HTML时,仅显示带滚动条的空白矩形。

我的Google Maps HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title> GUI Embedded Map Test </title>
  <style>
    #map{
        height:600px;
        width:100%;
    }
  </style>
</head>
<body>
  <div id="map"></div>
  <script>
    function initMap() {
      window.map = new google.maps.Map(document.getElementById("map"), {
        zoom: 15,
        center:{lat:32.99069195330653, lng:-106.97436738069189},
        mapTypeId: "terrain",
      });
    }

    window.initMap = initMap;
  </script>
  <script async defer
      src="https://maps.googleapis.com/maps/api/js?key=RANDOMKEY&callback=initMap" /c/
    ></script>
</body>
</html>

注:该HTML在浏览器中可正常显示地图。

我的JavaFX嵌入代码

WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
String map_html = "";
try {
        File myObj = new File(System.getProperty("user.dir")+"/src/main/resources/embeddedMap.html");
        Scanner myReader = new Scanner(myObj);
        while (myReader.hasNextLine()) {
        map_html += myReader.nextLine();
    map_html += "\n";
        }
        myReader.close();
} catch (FileNotFoundException e) {
        System.out.println("An error occurred.");
    e.printStackTrace();
}
webEngine.loadContent(map_html);
mapPane.getChildren().add(webView);

已尝试的操作:

  • 使用Google Maps分享功能生成的iframe标签
  • 更换不同的API密钥

问题仍未解决,求帮助!


解决方案

1. 修复HTML脚本标签的语法错误

HTML中Google Maps的脚本标签存在多余的/c/,会导致脚本加载失败,修正后:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=你的API密钥&callback=initMap"></script>

2. 改用load方法加载本地文件

loadContent以data:协议处理内容,易引发资源加载限制,直接加载文件URI更稳定:

File htmlFile = new File(System.getProperty("user.dir") + "/src/main/resources/embeddedMap.html");
webEngine.load(htmlFile.toURI().toString());

3. 验证API密钥的配置

  • 确保API密钥已启用Maps JavaScript API
  • 若密钥设置了HTTP referrer限制,添加file:///*(测试用),或根据生产环境调整限制规则

4. 添加错误监听排查问题

通过WebEngine的错误监听获取具体加载失败信息:

webEngine.setOnError(event -> {
    System.err.println("WebView加载错误:" + event.getMessage());
});

内容的提问来源于stack exchange,提问作者Kaiser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 04:04:55