在 WPF 应用程序中获取地图窗口

问题描述 投票:0回答:1

我正在尝试在我的 WPF 应用程序中创建一个简单的地图窗口。该应用程序运行没有任何错误,但地图不显示。我不确定如何调试该问题。

我的 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>

这是我运行应用程序时得到的结果:

enter image description here

开发工具没有给出任何错误。

javascript wpf maps
1个回答
0
投票

我只是看了他们的例子,看来你缩小的js代码只是为了导入库。添加脚本以在其之后实际渲染地图:

<script>
    let map;

    async function initMap() {
        const { Map } = await google.maps.importLibrary("maps");

        map = new Map(document.getElementById("map"), {
            center: { lat: -34.397, lng: 150.644 },
            zoom: 8,
        });
    }

    initMap();
</script>
© www.soinside.com 2019 - 2024. All rights reserved.