WPF应用中WebView2加载Google Maps不显示问题排查求助
问题:WPF WebView2集成Google Maps空白无报错
在WPF应用中尝试通过WebView2控件集成一个简单的Google Maps窗口,程序运行无报错,但地图无法显示,DevTools也未给出错误信息,无法确定排查方向。
WPF XAML代码
<Window x:Class="StructuralCalculations.WindTool.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:StructuralCalculations.WindTool" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:vm="clr-namespace:StructuralCalculations.MainVM" xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf" Title="MainWindow" Width="800" Height="450" mc:Ignorable="d"> <Window.DataContext> <local:MainVM /> </Window.DataContext> <Grid> <Grid.RowDefinitions> <RowDefinition Height="10" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="10" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="10" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="150" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="10" /> </Grid.ColumnDefinitions> <wv2:WebView2 x:Name="MapBrowser" Grid.Row="1" Grid.Column="1" Width="500" Height="300" /> <StackPanel Grid.Row="1" Grid.Column="2" Margin="0,0,0,0" Orientation="Vertical"> <TextBlock VerticalAlignment="Center" FontWeight="Bold" Text="Project:" /> <TextBox Text="{Binding ProjectName}" /> <TextBlock VerticalAlignment="Center" FontWeight="Bold" Text="Job Number:" /> <TextBox Text="{Binding JobNumber}" /> <TextBlock VerticalAlignment="Center" FontWeight="Bold" Text="Address:" /> <TextBox x:Name="AddressTextBox" Text="{Binding Address}" /> <!--<Button Margin="30,5,30,5" Click="CenterMapButton_Click" Content="Center Map" />--> <TextBlock VerticalAlignment="Center" FontWeight="Bold" Text="Nearest City:" /> <TextBlock x:Name="CityNameTextBlock" Margin="0,0,0,0" VerticalAlignment="Center" Text="{Binding Location, Mode=TwoWay}" /> <TextBlock VerticalAlignment="Center" FontWeight="Bold" Text="Wind Region:" /> <TextBlock Margin="0,0,0,0" VerticalAlignment="Center" Text="{Binding WindRegion}" /> <TextBlock VerticalAlignment="Center" FontWeight="Bold" Text="Elevation:" /> <TextBlock x:Name="ElevationTextBlock" Margin="0,0,0,0" VerticalAlignment="Center" Text="{Binding Elevation, Mode=TwoWay}" /> </StackPanel> <Button Grid.Row="2" Grid.Column="4" Width="100" Height="50" Command="{Binding GenerateReportCommand}" Content="Report" /> </Grid> </Window>
后台代码(XAML.cs)
using Microsoft.Web.WebView2.Core; using System.IO; using System.Windows; namespace StructuralCalculations.WindTool { //[ComVisible(true)] // Make the class visible to COM for scripting public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); InitializeWebView(); } private async void InitializeWebView() { // Ensure WebView2 environment is initialized await MapBrowser.EnsureCoreWebView2Async(); // Enable JavaScript explicitly MapBrowser.CoreWebView2.Settings.IsScriptEnabled = true; // Attach event handlers after WebView2 is initialized MapBrowser.CoreWebView2.WebMessageReceived += CoreWebView2_WebMessageReceived; MapBrowser.CoreWebView2.OpenDevToolsWindow(); // Open DevTools // Add a global error handler for JavaScript errors await MapBrowser.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(@" window.onerror = (message, source, lineno, colno, error) => { console.error(`${message} at ${source}:${lineno}:${colno}`); }; "); // Get the path of the HTML file string htmlFilePath = Path.Combine(Environment.CurrentDirectory, "Shared", "map.html"); // Check if the file exists if (File.Exists(htmlFilePath)) { // Load the HTML file into WebView2 MapBrowser.CoreWebView2.Navigate(htmlFilePath); } else { MessageBox.Show("HTML file not found: " + htmlFilePath); } } void CoreWebView2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e) { MessageBox.Show(e.WebMessageAsJson); } } }
HTML代码(API已隐藏)
<!doctype html> <!-- @license Copyright 2019 Google LLC. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 --> <html> <head> <title>Add Map</title> </head> <body> <h3>My Google Maps Demo</h3> <!--The div element for the map --> <div id="map"></div> <!-- prettier-ignore --> <script> (g => { var h, a, k, p = "The Google Maps JavaScript API", c = "google", l = "importLibrary", q = "__ib__", m = document, b = window; b = b[c] || (b[c] = {}); var d = b.maps || (b.maps = {}), r = new Set, e = new URLSearchParams, u = () => h || (h = new Promise(async (f, n) => { await (a = m.createElement("script")); e.set("libraries", [...r] + ""); for (k in g) e.set(k.replace(/[A-Z]/g, t => "_" + t[0].toLowerCase()), g[k]); e.set("callback", c + ".maps." + q); a.src = `https://maps.${c}apis.com/maps/api/js?` + e; d[q] = f; a.onerror = () => h = n(Error(p + " could not load.")); a.nonce = m.querySelector("script[nonce]")?.nonce || ""; m.head.append(a) })); d[l] ? console.warn(p + " only loads once. Ignoring:", g) : d[l] = (f, ...n) => r.add(f) && u().then(() => d[l](f, ...n)) }) ({ key: "myHiddenApiKey", v: "weekly" });</script> </body> </html>
运行后界面仅显示标题,地图区域为空白,DevTools未检测到任何错误。
内容的提问来源于stack exchange,提问作者Hadi Moosavi
相关产品推荐
相关产品推荐

