Q060. WPF で Google Map API を使うには?

A. WebBrowser コントロールを使います。以下は NavigateToString メソッドを使ったサンプルです。Google Maps API の使い方については以下の記事を参考にさせて頂きましたが、たいへん判りやすいサイトで助かりました。



関連記事Google Maps入門(Google Maps JavaScript API V3)


<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <WebBrowser x:Name="browser" />
</Window>


WebBrowser.NavigateToString メソッドに HTML 形式の文字列を渡します。HTML 内の引用符はすべてシングルクオートを使用しました。

Option Explicit On
Option Strict On

Public Class MainWindow
    Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
        Me.SetNavigateToString()
    End Sub

    Private Sub SetNavigateToString()
        Dim html As New System.Text.StringBuilder()
        With html
            .AppendLine("<!DOCTYPE html '-//W3C//DTD XHTML 1.0 Strict//EN'  ")
            .AppendLine("  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'> ")
            .AppendLine("<html xmlns='http://www.w3.org/1999/xhtml'> ")
            .AppendLine("  <head> ")
            .AppendLine("    <meta http-equiv='content-type' content='text/html; charset=utf-8'/> ")
            .AppendLine("    <title>Google Maps JavaScript API サンプル</title> ")
            .AppendLine("    <script type='text/javascript' src='http://maps.google.com/maps/api/js?sensor=false&language=ja'></script> ")
            .AppendLine("    <script type='text/javascript'> ")
            .AppendLine("        function initialize() { ")
            .AppendLine("            var latlng = new google.maps.LatLng(35.709984, 139.810703); ")
            .AppendLine("            var opts = { ")
            .AppendLine("                zoom: 15, ")
            .AppendLine("                center: latlng, ")
            .AppendLine("                mapTypeId: google.maps.MapTypeId.ROADMAP ")
            .AppendLine("            }; ")
            .AppendLine("            var map = new google.maps.Map(document.getElementById('map_canvas'), opts); ")
            .AppendLine("        } ")
            .AppendLine("    </script> ")
            .AppendLine("  </head> ")
            .AppendLine("  <body onload='initialize()'> ")
            .AppendLine("    <div id='map_canvas' style='width: 100%; height: 500px'></div> ")
            .AppendLine("  </body> ")
            .AppendLine("</html> ")
        End With
        Me.browser.NavigateToString(html.ToString())
    End Sub
End Class


別の方法では、Google Maps API for FlashActiveX 経由で使う方法もあるようです。しかしこちらは ActiveX & WindowsFormsHost を使うだけにかなり敷居は高そうですね。

関連記事Google マップを XAML を使用する Microsoft WPF アプリケーションでホストする



WPF FAQ の目次に戻る