トップへ(mam-mam.net/)

Webview4Delphi(WebView2)でブラウザの位置情報(GPS)機能をDelphiから使用する ~Delphiソースコード集

webview4delphi(WebView2)でブラウザの位置情報(GPS)機能をDelphiから使用する

Delphi 11.3(Community Edition)でwebview4delphiを使ってブラウザの位置情報(GPS)機能(navigator.geolocation.getCurrentPosition)を使用します。

(1)はじめに

Windows10の場合はMicrosoft WebView2 ランタイムのインストールを以下のURLを参照してインストールしてください。
https://mam-mam.net/delphi/tedgebrowser.html
「WebView2Loader.dll」も、
https://mam-mam.net/delphi/tedgebrowser.html を参照してください。

webview4delphiのインストールは以下を参考にDelphiにインストールしてください
https://mam-mam.net/delphi/tedgebrowser_webview4delphi.html

(2)プロジェクトの作成と保存

Delphi IDEを起動し、「ファイル」⇒「Windows VCLアプリケーション -Delphi」をクリックします
「ファイル」⇒「すべて保存 Ctrl+Shift+S」をクリックして、プロジェクト保存用フォルダを作成して ユニット(Unit1)とプロジェクト(Project1)を保存します
次に、「プロジェクト」⇒「Project1をビルト Shift+F9」をクリックして事前に一度コンパイルしておきます。(フォルダが生成される)
プロジェクトフォルダ内の「win32\degub」フォルダに「files」フォルダを作成します。
「win32\degub\files」フォルダ内に、以下のHTMLファイル「index.html」を作成してUTF-8で保存してください。

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
</head>
<body>
<script>
  window.addEventListener("load",function(){
    console.log("event:loaded");//■HTMLがロード完了
  });
  function get_location_gps(){
    if(navigator.geolocation){
      //現在の位置情報取得
      navigator.geolocation.getCurrentPosition(
        function(pos){
          //成功時に呼ばれる関数
          var posLatitude=pos.coords.latitude;
          var posLongitude=pos.coords.longitude;
          console.log("gps:"+posLatitude+","+posLongitude);//■位置情報取得成功
        },
        function(err){
          //敗時に呼ばれる関数
          //位置情報取得を拒否された場合 "User denied Geolocation"、
          //インターネット接続が無い場合 "Network error. Check DevTools console for more information."
          console.log("error:"+err.message);//■エラー
        },
        //位置情報取得オプション
        {
          //何ミリ秒以前にキャッシュされた位置を返してもよいか。0を指定すると現在の位置情報を取得
          maximumAge:0,
          //位置情報取得に要してよい最大時間(ミリ秒)
          timeout:3000,
          //true:なるべく正確な情報を返してほしい場合  false:正確でない場合
          enableHighAccuracy:true,
        }
      );
    }else{
      console.log("error:disabled");//■GPS取得未対応
    }
  }
</script>
</body>
</html>

(3)フォームの設計

フォームにTButton×1個と、TMemo1×1個、TWVBrowser×1個、TWVWindowParent×1個をドラッグ&ドロップします

緯度経度を求めるアプリケーションの設計

(4)ソースコードの記述

フォームのButton1をダブルクリックしてソースコードを記述します。

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
  uWVWinControl, uWVWindowParent, uWVBrowserBase, uWVBrowser,
  uWVTypes, uWVConstants, uWVTypeLibrary, uWVLoader, uWVInterfaces,
  uWVCoreWebView2Args, uWVLibFunctions, uWVCoreWebView2CookieList,
  uWVCoreWebView2Cookie, uWVCoreWebView2HttpRequestHeaders,
  uWVCoreWebView2, System.Json;

type
  TForm1 = class(TForm)
    WVBrowser1: TWVBrowser;
    WVWindowParent1: TWVWindowParent;
    Button1: TButton;
    Memo1: TMemo;
    procedure FormCreate(Sender: TObject);
    procedure WVBrowser1AfterCreated(Sender: TObject);
    procedure WVBrowser1DevToolsProtocolEventReceived(Sender: TObject;
      const aWebView: ICoreWebView2;
      const aArgs: ICoreWebView2DevToolsProtocolEventReceivedEventArgs;
      const aEventName: wvstring; aEventID: Integer);
    procedure Button1Click(Sender: TObject);
  private
    { Private 宣言 }
  public
    { Public 宣言 }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses System.JSON.Serializers, System.IOUtils;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Button1.Enabled:=False;
  //Javascriptの位置情報取得を開始する
  WVBrowser1.ExecuteScript('get_location_gps()',1);
end;

procedure TForm1.FormCreate(Sender: TObject);
var ct:integer;
begin
  Button1.Enabled:=False;
  Button1.Caption:='位置情報取得';
  Memo1.Lines.Clear;

  WVWindowParent1.Browser:=WVBrowser1;
  if GlobalWebView2Loader.InitializationError then
  begin
    ShowMessage(GlobalWebView2Loader.ErrorMessage);
  end
  else
  begin
    ct:=0;
    while (ct<20) and (not GlobalWebView2Loader.Initialized) do
    begin
      sleep(500);
      Application.ProcessMessages;
      inc(ct);
    end;
    if GlobalWebView2Loader.Initialized then
    begin
      WVBrowser1.CreateBrowser(WVWindowParent1.Handle);
      //参考:
      //ユーザーエージェントをWebView以外に変更するとGoogleログインも可能
      WVBrowser1.UserAgent:=
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'+
        ' AppleWebKit/537.36 (KHTML, like Gecko)'+
        ' Chrome/101.0.4951.64 Safari/537.36 Edg/101.0.1210.53';
    end
    else
    begin
      ShowMessage('WebView2初期化失敗');
    end;
  end;
end;


procedure TForm1.WVBrowser1AfterCreated(Sender: TObject);
begin
  //以下必須
  WVWindowParent1.UpdateSize;

  //ローカルの「files」ディレクトリを
  //「https://demo」に割り当てる
  WVBrowser1.CoreWebView2.SetVirtualHostNameToFolderMapping(
    'demo',
    PWideChar(ExtractFilePath(Application.ExeName)+'files'),
    COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND_ALLOW
  );

  //コンソールの使用を申請する
  WVBrowser1.CallDevToolsProtocolMethod(
    'Console.enable',
    '{}', 0
  );
  //コンソールにメッセージが出力された時に
  //[OnDevToolsProtocolEventReceived]イベントaEventID=1としてを発生させる
  WVBrowser1.SubscribeToDevToolsProtocolEvent('Console.messageAdded',1);

  //ローカルPCにある「.\files\index.html」を表示させる
  WVBrowser1.Navigate('https://demo/index.html');
end;


procedure TForm1.WVBrowser1DevToolsProtocolEventReceived(Sender: TObject;
  const aWebView: ICoreWebView2;
  const aArgs: ICoreWebView2DevToolsProtocolEventReceivedEventArgs;
  const aEventName: wvstring; aEventID: Integer);
type
  TJsonMsg=record
    column:Integer;
    level:String;
    line:Integer;
    source:String;
    text:String;
    url:String;
  end;
  TJsonMessage=record
    message:TJsonMsg;
  end;
var pwc:PWideChar;
    s:TJsonSerializer;
    res:TJsonMessage;
begin
  if aEventID=1 then
  begin
    aArgs.Get_ParameterObjectAsJson(pwc);
    s:=TJsonSerializer.Create;
    res:=s.Deserialize<TJsonMessage>(pwc);
    if res.message.text='event:disabled' then
    begin
      Memo1.Lines.Add('この端末は位置情報を取得できません');
      Button1.Enabled:=False;
    end
    else if res.message.text='event:loaded' then
    begin
      Button1.Enabled:=True;
    end
    else if pos('error:',res.message.text,1)=1 then
    begin
      Memo1.Lines.Add('エラー:'+res.message.text.Substring(6));
      Button1.Enabled:=True;
    end
    else if pos('gps:',res.message.text,1)=1 then
    begin
      Memo1.Lines.Add('緯度経度:'+res.message.text.Substring(4));
      //ar:=res.message.text.Substring(4).split([',']);
      Memo1.Lines.Add(
        'https://www.google.co.jp/maps/@'+
        res.message.text.Substring(4)+',18z?hl=ja&entry=ttu'
      );
      Button1.Enabled:=True;
    end
  end;
end;

initialization
var cachepath:string;
begin
  cachepath:=ExtractFilePath(Application.ExeName) + 'cache';
  //キャッシュを削除する
  if DirectoryExists(cachepath) then TDirectory.Delete(cachepath,true);
  // GlobalWebView2Loaderをロードして初期化
  GlobalWebView2Loader := TWVLoader.Create(nil);
  //キャッシュやクッキー等の保存場所を指定する
  GlobalWebView2Loader.UserDataFolder := cachepath;
  GlobalWebView2Loader.StartWebView2;
end;

end.

(5)「WebView2Loader.dll」ファイルを実行ファイルと同じフォルダ内にコピーする

「C:\Program Files (x86)\Embarcadero\Studio\22.0\Redist\win32\WebView2Loader.dll」
ファイルを、実行ファイルと同じフォルダ内(プロジェクト保存フォルダ\Win32\Debug)にコピーします

(A)「Debug」ビルトで
「Windows 32ビット」
プロジェクト保存フォルダ\Win32\Debug
(B)「Debug」ビルトで
「Windows 64ビット」
プロジェクト保存フォルダ\Win64\Debug
(C)「Release」ビルトで
「Windows 32ビット」
プロジェクト保存フォルダ\Win32\Release
(D)「Release」ビルトで
「Windows 64ビット」
プロジェクト保存フォルダ\Win64\Release

(6)実行する

パソコンにGPSモジュールが搭載されていない場合は、パソコンをインターネットに接続してください。
おおよその位置情報を表示してくれます。

「実行」⇒「実行」をクリックすると実行します。
しばらく待つと「位置情報取得(Button1)」ボタンが有効になります。

緯度経度を求めるアプリケーションの実行

「位置情報取得(Button1)」ボタンをクリックしてください。
現在地情報の使用を求めるダイアログが表示された場合は「許可」をクリックしてください。
位置情報の取得が成功した場合には緯度と経度が表示されます。

現在地情報の使用を求めるダイアログ
緯度と経度が表示されます