从TWebBrowser中的GoogleMaps获取纬度经度 [英] Getting Latitude Longitude from GoogleMaps in TWebBrowser

查看:135
本文介绍了从TWebBrowser中的GoogleMaps获取纬度经度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将地址传递给Google地图,我可以显示地图并在TWebBrowser中放置一个标记,但我也试图将纬度和经度坐标返回到我的Delphi Win32应用程序。我需要添加什么?

  private 
{Private declarations}
HTMLWindow2:IHTMLWindow2;
fAddress:String;
public
{公共声明}
构造函数create(AOwner:TComponent; AAddress:string);重新引入;
end;

var
ViewMaps:TViewMaps;
标志:OLEVariant;
地址,MapType:string;
Title,Lat,Lng:AnsiString;

执行

使用ShredMain,ActiveX,MaintForm_u,NewSchedule;

{$ R * .dfm}

构造函数TViewMaps.create(AOwner:TComponent; AAddress:string);
begin
继承创建(AOwner);
fAddress:= AAddress; // fAddress现在存储为变量
end;

const
HTMLStr:AnsiString =
'< html> '+
'< head> '+
'< meta name =viewportcontent =initial-scale = 1.0,user-scalable = yes/> '+
//'< meta http-equiv =X-UA-Compatiblecontent =IE = edge/>'+
'< input type =hiddenid = latvalue =/>'+
'< input type =hiddenid =lngvalue =/>'+
''+
'< script type =text / javascriptsrc =http://maps.google.com/maps/api/js?v=3.22>< / script> '+
'< script type =text / javascript> '+
''+
''+
'var geocoder; '+
'var map; '+
'var trafficLayer;'+
'var bikeLayer;'+
'var markersArray = [];'+
''+
''+
'function initialize(){'+
'geocoder = new google.maps.Geocoder();'+
'var latlng = new google.maps.LatLng(40.714776,-74.019213); '+
'var myOptions = {'+
'zoom:11,'+
'center:latlng,'+
'mapTypeId:google.maps.MapTypeId.ROADMAP' +
'}; '+
'map = new google.maps.Map(document.getElementById(map_canvas),myOptions); '+
'trafficLayer = new google.maps.TrafficLayer();'+
'bikeLayer = new google.maps.BicyclingLayer();'+
'map.set(streetViewControl ,假);'+
'}'+
''+
''+
'function codeAddress(address){'+
'if(geocoder) {'+
'geocoder.geocode({address:address},function(results,status){'+
'if(status == google.maps.GeocoderStatus.OK){'+
'map.setCenter(results [0] .geometry.location);'+
'PutMarker(results [0] .geometry.location.lat(),results [0] .geometry.location.lng ),results [0] .geometry.location.lat()+,+ results [0] .geometry.location.lng());'+
'document.getElementById(lat)。value = results [0] .geometry.location.lat;'+
'document.getElementById(lng).value = results [0] .geometry.location.lng;'+
'} else {'+
'alert(由于以下原因,Geocode不成功:+ status);'+
'}'+
'});'+
'}'+
'}'+
''+
''+
'函数GotoLatLng(Lat,Lang){'+
'var latlng = new google.maps.LatLng(Lat,Lang);'+
'地图。 setCenter(latlng);'+
'PutMarker(Lat,Lang,Lat +,+ Lang);'+
'}'+
''+
''+
'function ClearMarkers(){'+
'if(markersArray){'+
'for(i in markersArray){'+
'markersArray [i] .setMap(空值); '+
'}'+
'}'+
'}'+
''+
'函数PutMarker(Lat,Lang,Msg){'+
'var latlng = new google.maps.LatLng(Lat,Lang);'+
'var marker = new google.maps.Marker({'+
'position:latlng,' +
'map:map,'+
'title:Msg +(+ Lat +,+ Lang +)'+
'});'+
' markersArray.push(标记); '+
'}'+
''+
''+
'function TrafficOn(){trafficLayer.setMap(map); }'+
''+
'function TrafficOff(){trafficLayer.setMap(null); }'+
''+''+
'function BicyclingOn(){bikeLayer.setMap(map); }'+
''+
'function StreetViewOn(){map.set(')}'+ $ b $''+
'function BicyclingOff(){bikeLayer.setMap(null) (streetViewControl,true); }'+
''+
'function StreetViewOff(){map.set(streetViewControl,false); }'+
''+
''+'< / script> '+
'< / head> '+
'< body onload =initialize()> '+
'< div id =map_canvasstyle =width:100%; height:100%>< / div> '+
'< / body> '+
'< / html> ;

程序TViewMaps.OnShow(发件人:TObject);
var
aStream:TMemoryStream;
HtmlElement:IHtmlElement;
sLat,sLng:string;

begin
WebBrowser1.Navigate('about:blank');
MemoAddress.Lines.Text:= NewServiceForm.MapAddress;
如果已分配(WebBrowser1.Document),则
开始
aStream:= TMemoryStream.Create;
尝试
aStream.WriteBuffer(指针(HTMLStr)^,长度(HTMLStr));
aStream.Seek(0,soFromBeginning);
(WebBrowser1.Document as IPersistStreamInit).Load(TStreamAdapter.Create(aStream));
终于
aStream.Free;
end;
HTMLWindow2:=(WebBrowser1.Document as IHTMLDocument2).parentWindow;
end;

,而WebBrowser1.ReadyState<> READYSTATE_COMPLETE //等待google
begin
sleep(0);
application.processmessages;
end;
// 05/11/2016 - 在地图上显示地址
fAddress:= StringReplace(StringReplace(Trim(fAddress),#13,'',[rfReplaceAll]),#10,'' ,[rfReplaceAll]);

HTMLWindow2.execScript(Format('codeAddress(%s)',[QuotedStr(fAddress)]),'JavaScript');

HtmlElement:=(WebBrowser1.document as IHTMLDocument3).getElementById('lat');
sLat:= HtmlElement.getAttribute('value',0);
HtmlElement:=(WebBrowser1.document as IHTMLDocument3).getElementById('lng');
sLng:= HtmlElement.getAttribute('value',0);

LatitudeEdit.Text:= sLat;
LongitudeEdit.Text:= sLng;

end;

我将Lat和Lng定义为AnsiString,但sLat和sLng在我的OnShow中被本地定义为String事件。经度和纬度的两个Tedit框为空白。我将错误的变量传递给他们吗?
解决方案

为了获得你的Delphi代码中可用的坐标,你需要存储html(DOM)中的值,然后从Delphi代码中提取它们。首先,您可以创建隐藏字段,以在Body标记之间的HTML中存储javascript值:

 < input type =隐藏id =latvalue =0/> 
< input type =hiddenid =lngvalue =0/>

然后在您的javascript函数中,设置隐藏值:

  document.getElementById(lat)。value = results [0] .geometry.location.lat; 
document.getElementById(lng)。value = results [0] .geometry.location.lng;

然后在Delphi应用程序中获取值,使用如下所示:

  var 
lat,lng:string;
HtmlElement:IHtmlElement;
begin
HtmlElement:=(Webbrowser1.document as IHTMLDocument3).getElementById('lat');
lat:= HtmlElement.getAttribute('value',0);
HtmlElement:=(Webbrowser1.document as IHTMLDocument3).getElementById('lng');
lng:= HtmlElement.getAttribute('value',0);
end;

在这里我重写了你的整个单元。请特别注意对HTMLStr常量的更改,特别是codeAddress函数,它使用标记来获取纬度/经度值。

  unit fmViewMaps; 

接口

使用
对话框,OleCtrls,MSHTML,SHDocVw, StdCtrls中;

类型

TLocation =记录
Lat:String;
Lng:String;
结果:string;
end;

TFrmViewMaps = class(TForm)
WebBrowser1:TWebBrowser;
LatitudeEdit:TEdit;
LongitudeEdit:TEdit;
程序FormShow(发件人:TObject);
私人
{私人申报}
fAddress:string;
HTMLWindow2:IHTMLWindow2;
程序LoadGoogleApi;
函数GoogleApiReady:boolean;
过程ExecuteScript(AScript:string);
函数GetElementByID(AElementID:string):IHTMLElement;
函数GetElementValue(ElementID:string):string;
函数GetGeocode(地址:字符串):TLocation;
public
{公共声明}
构造函数create(AOwner:TComponent; AAddress:string);重新引入;
end;

var
FrmViewMaps:TFrmViewMaps;

实现

使用ActiveX;

{$ R * .dfm}

const
HTMLStr:AnsiString =
'< html> '+
'< head> '+
'< meta name =viewportcontent =initial-scale = 1.0,user-scalable = yes/> '+
''+
'< script type =text / javascriptsrc =http://maps.google.com/maps/api/js?v=3.22><< ; /脚本> '+
'< script type =text / javascript> '+
''+
''+
'var geocoder; '+
'var map; '+
'var trafficLayer;'+
'var bikeLayer;'+
'var markersArray = [];'+
''+
''+
'function initialize(){'+
'geocoder = new google.maps.Geocoder();'+
'var latlng = new google.maps.LatLng(40.714776,-74.019213); '+
'var myOptions = {'+
'zoom:11,'+
'center:latlng,'+
'mapTypeId:google.maps.MapTypeId.ROADMAP' +
'}; '+
'map = new google.maps.Map(document.getElementById(map_canvas),myOptions); '+
'trafficLayer = new google.maps.TrafficLayer();'+
'bikeLayer = new google.maps.BicyclingLayer();'+
'map.set(streetViewControl ,假);'+
'}'+
''+
''+
'function codeAddress(address){'+
'if(geocoder) {'+
'geocoder.geocode({address:address},function(results,status){'+
'if(status == google.maps.GeocoderStatus.OK){'+
'map.setCenter(results [0] .geometry.location);'+
'var myLatlng = new google.maps.LatLng(results [0] .geometry.location.lat(),results [0 ] .geometry.location.lng());'+
'var marker = new google.maps.Marker({'+
'position:myLatlng,'+
'title: ','+
'map:map'+
'});'+
'markersArray.push(marker);'+
'document.getElementById(hiddenlat ).value = myLatlng.lat();'+
document.getElementById(hiddenlng)。value = myLatlng.lng();'+
''+
'} else {'+
'document.getElementById(hiddenlat)。值=错误; '+
'document.getElementById(hiddenlng)。value =error; '+
'alert(Geocode不成功,原因如下:+ status);'+
'}'+
'});'+
'} '+
'}'+
''+
''+
''+
'函数GotoLatLng(Lat,Lang){'+
'lat latng = new google.maps.LatLng(Lat,Lang);'+
'map.setCenter(latlng);'+
'PutMarker(Lat,Lang,Lat +,+ Lang) ;'+
'}'+
''+
''+
'function ClearMarkers(){'+
'if(markersArray){'+ $ (我在markersArray中){'+
'markersArray [i] .setMap(null); b $ b' '+
'}'+
'}'+
'}'+
''+
'函数PutMarker(Lat,Lang,Msg){'+
'var latlng = new google.maps.LatLng(Lat,Lang);'+
'var marker = new google.maps.Marker({'+
'position:latlng,' +
'map:map,'+
'title:Msg +(+ Lat +,+ Lang +)'+
'});'+
' markersArray.push(标记); '+
'}'+
''+
''+
'function TrafficOn(){trafficLayer.setMap(map); }'+
''+
'function TrafficOff(){trafficLayer.setMap(null); }'+
''+''+
'function BicyclingOn(){bikeLayer.setMap(map); }'+
''+
'function StreetViewOn(){map.set(')}'+ $ b $''+
'function BicyclingOff(){bikeLayer.setMap(null) (streetViewControl,true); }'+
''+
'function StreetViewOff(){map.set(streetViewControl,false); }'+
''+
''+'< / script> '+
'< / head> '+
'< body onload =initialize()> '+
'< div id =map_canvasstyle =width:100%; height:100%>< / div> '+
'< input type =hiddenid =hiddenlatvalue =0/>'+
'< input type =hiddenid =hiddenlngvalue = 0/>'+
'< / body> '+
'< / html> ;


构造函数TFrmViewMaps.create(AOwner:TComponent; AAddress:string);
begin
继承创建(AOwner);
fAddress:= AAddress;
end;

过程TFrmViewMaps.LoadGoogleApi;
var
aStream:TMemoryStream;
begin
WebBrowser1.Navigate('about:blank'); //将位置设置为空页面

如果已分配(WebBrowser1.Document),则
begin
aStream:= TMemoryStream.Create; //创建一个TStream来从字符串中加载页面
try
aStream.WriteBuffer(指针(HTMLStr)^,Length(HTMLStr));
aStream.Seek(0,soFromBeginning);
(WebBrowser1.Document as IPersistStreamInit).Load(TStreamAdapter.Create(aStream));
终于
aStream.Free;
end;
HTMLWindow2:=(WebBrowser1.Document as IHTMLDocument2).parentWindow;
end;

,而WebBrowser1.ReadyState<> READYSTATE_COMPLETE //等待google
begin
sleep(0);
application.processmessages;
end;

end;

函数TFrmViewMaps.GoogleApiReady:boolean;
begin
result:=(HTMLWindow2<> nil);
end;

过程TFrmViewMaps.ExecuteScript(AScript:string);
begin
HTMLWindow2.execScript(AScript,'JavaScript');
end;

函数TFrmViewMaps.GetElementByID(AElementID:string):IHTMLElement;
begin
result:=(WebBrowser1.Document as IHTMLDocument3).getElementByID(AElementID);
end;

函数TFrmViewMaps.GetElementValue(ElementID:string):string;
var
HtmlElement:IHTMLElement;
begin
HtmlElement:= GetElementByID(ElementID);
结果:= HtmlElement.getAttribute('value',0);
end;

过程RemoveInvalidGeoLookupChars(var AString:string);
begin
AString:= StringReplace(StringReplace(Trim(AString),#13,'',[rfReplaceAll]),#10,'',[rfReplaceAll]);
//删除无效字符
AString:= StringReplace(AString,#39,#32,[rfReplaceAll]); //单引号
AString:= StringReplace(AString,#34,#32,[rfReplaceAll]); //双引号
end;

函数TFrmViewMaps.GetGeocode(Address:string):TLocation;
var
i:integer;
begin
result.Lat:='0';
result.Lng:='0';
LatitudeEdit.text:='0';
LongitudeEdit.text:='0';
result.Result:='OK';
application.processmessages;
RemoveInvalidGeoLookupChars(address);
application.processmessages;
ExecuteScript(格式('codeAddress(%s)',[QuotedStr(address)]));

while(GetElementValue('hiddenlat')='0')do
application.processmessages;

result.Lat:= GetElementValue('hiddenlat');
result.lng:= GetElementValue('hiddenlng');
end;

程序TFrmViewMaps.FormShow(Sender:TObject);
var
位置:TLocation;
begin
LoadGoogleApi;
位置:= GetGeoCode(fAddress);
LatitudeEdit.Text:= Location.Lat;
LongitudeEdit.Text:= Location.Lng;
end;

结束。

要从另一个表单对地址进行地址解析,请使用以下语法:

  frmViewMaps:= TFrmViewMaps.create(self,'One Microsoft Way,Redmond,WA 98052'); 
尝试
frmViewMaps.showmodal;
finally
frmViewMaps.destroy;
end;


I'm passing an address to Google Maps and I'm able to display a map and place a marker in TWebBrowser, but I'm trying to also return the Latitude and Longitude coordinates to my Delphi Win32 app. What do I need to add?

  private
    { Private declarations }
    HTMLWindow2: IHTMLWindow2;
    fAddress: String;
  public
    { Public declarations }
    constructor create(AOwner: TComponent; AAddress: string); reintroduce;
  end;

var
  ViewMaps                     : TViewMaps;
  Flags                        : OLEVariant;
  address, MapType             : string;
  Title, Lat, Lng              : AnsiString;

implementation

Uses ShredMain, ActiveX, MaintForm_u, NewSchedule;

{$R *.dfm}

constructor TViewMaps.create(AOwner: TComponent; AAddress: string);
begin
  inherited create(AOwner);
  fAddress := AAddress; // fAddress is now stored to form variable
end;

const
HTMLStr: AnsiString =
'<html> '+
'<head> '+
'<meta name="viewport" content="initial-scale=1.0, user-scalable=yes" /> '+
//'<meta http-equiv="X-UA-Compatible" content="IE=edge" />'+
'<input type="hidden" id="lat" value="" />'+
'<input type="hidden" id="lng" value="" />'+
''+
'<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.22"></script> '+
'<script type="text/javascript"> '+
''+
''+
'  var geocoder; '+
'  var map;  '+
'  var trafficLayer;'+
'  var bikeLayer;'+
'  var markersArray = [];'+
''+
''+
'  function initialize() { '+
'    geocoder = new google.maps.Geocoder();'+
'    var latlng = new google.maps.LatLng(40.714776,-74.019213); '+
'    var myOptions = { '+
'      zoom: 11, '+
'      center: latlng, '+
'      mapTypeId: google.maps.MapTypeId.ROADMAP '+
'    }; '+
'    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); '+
'    trafficLayer = new google.maps.TrafficLayer();'+
'    bikeLayer = new google.maps.BicyclingLayer();'+
'    map.set("streetViewControl", false);'+
'  } '+
''+
''+
'  function codeAddress(address) { '+
'    if (geocoder) {'+
'      geocoder.geocode( { address: address}, function(results, status) { '+
'        if (status == google.maps.GeocoderStatus.OK) {'+
'          map.setCenter(results[0].geometry.location);'+
'          PutMarker(results[0].geometry.location.lat(), results[0].geometry.location.lng(), results[0].geometry.location.lat()+","+results[0].geometry.location.lng());'+
'          document.getElementById("lat").value = results[0].geometry.location.lat;'+
'          document.getElementById("lng").value = results[0].geometry.location.lng;'+
'        } else {'+
'          alert("Geocode was not successful for the following reason: " + status);'+
'        }'+
'      });'+
'    }'+
'  }'+
''+
''+
'  function GotoLatLng(Lat, Lang) { '+
'   var latlng = new google.maps.LatLng(Lat,Lang);'+
'   map.setCenter(latlng);'+
'   PutMarker(Lat, Lang, Lat+","+Lang);'+
'  }'+
''+
''+
'function ClearMarkers() {  '+
'  if (markersArray) {        '+
'    for (i in markersArray) {  '+
'      markersArray[i].setMap(null); '+
'    } '+
'  } '+
'}  '+
''+
'  function PutMarker(Lat, Lang, Msg) { '+
'   var latlng = new google.maps.LatLng(Lat,Lang);'+
'   var marker = new google.maps.Marker({'+
'      position: latlng, '+
'      map: map,'+
'      title: Msg+" ("+Lat+","+Lang+")"'+
'  });'+
' markersArray.push(marker); '+
'  }'+
''+
''+
'  function TrafficOn()   { trafficLayer.setMap(map); }'+
''+
'  function TrafficOff()  { trafficLayer.setMap(null); }'+
''+''+
'  function BicyclingOn() { bikeLayer.setMap(map); }'+
''+
'  function BicyclingOff(){ bikeLayer.setMap(null);}'+
''+
'  function StreetViewOn() { map.set("streetViewControl", true); }'+
''+
'  function StreetViewOff() { map.set("streetViewControl", false); }'+
''+
''+'</script> '+
'</head> '+
'<body onload="initialize()"> '+
'  <div id="map_canvas" style="width:100%; height:100%"></div> '+
'</body> '+
'</html> ';

procedure TViewMaps.OnShow(Sender: TObject);
var
  aStream: TMemoryStream;
  HtmlElement: IHtmlElement;
  sLat, sLng: string;

begin
  WebBrowser1.Navigate('about:blank');
  MemoAddress.Lines.Text := NewServiceForm.MapAddress;
  if Assigned(WebBrowser1.Document) then
  begin
    aStream := TMemoryStream.Create;
    try
      aStream.WriteBuffer(Pointer(HTMLStr)^, Length(HTMLStr));
      aStream.Seek(0, soFromBeginning);
      (WebBrowser1.Document as IPersistStreamInit).Load(TStreamAdapter.Create(aStream));
    finally
      aStream.Free;
    end;
    HTMLWindow2 := (WebBrowser1.Document as IHTMLDocument2).parentWindow;
  end;

  while WebBrowser1.ReadyState <> READYSTATE_COMPLETE do // wait for google
  begin
    sleep(0);
    application.processmessages;
  end;
  // 05/11/2016 - Show the address on the map
  fAddress := StringReplace(StringReplace(Trim(fAddress), #13, ' ', [rfReplaceAll]), #10, ' ', [rfReplaceAll]);

  HTMLWindow2.execScript(Format('codeAddress(%s)',[QuotedStr(fAddress)]), 'JavaScript');

  HtmlElement := (WebBrowser1.document as IHTMLDocument3).getElementById('lat');
  sLat  := HtmlElement.getAttribute('value', 0);
  HtmlElement := (WebBrowser1.document as IHTMLDocument3).getElementById('lng');
  sLng  := HtmlElement.getAttribute('value', 0);

  LatitudeEdit.Text := sLat;
  LongitudeEdit.Text := sLng;

end;

I have Lat and Lng defined as AnsiString, but sLat and sLng are defined as String locally in my OnShow event. My two Tedit boxes for Longitude and Latitude are blank. Am I passing the wrong variable to them?

解决方案

In order to get the coordinates available within your Delphi code, you need to store the values in the html (DOM), then extract them from your Delphi code. To start, you can create hidden fields to store the javascript values in your HTML between Body tag:

  <input type="hidden" id="lat" value="0" />
  <input type="hidden" id="lng" value="0" />

Then in your javascript function, set the hidden values:

document.getElementById("lat").value = results[0].geometry.location.lat;
document.getElementById("lng").value = results[0].geometry.location.lng;

Then to obtain the values in your Delphi application, use something like:

var
  lat, lng: string;
  HtmlElement: IHtmlElement;
begin
  HtmlElement := (Webbrowser1.document as IHTMLDocument3).getElementById('lat');
  lat  := HtmlElement.getAttribute('value', 0);
  HtmlElement := (Webbrowser1.document as IHTMLDocument3).getElementById('lng');
  lng  := HtmlElement.getAttribute('value', 0);
end;

Here I've rewritten your entire unit. Please take special notice to the changes to your HTMLStr constant, especially the codeAddress function, which uses a marker to obtain the lat/lng values.

unit fmViewMaps;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs,OleCtrls, MSHTML, SHDocVw, StdCtrls;

type

  TLocation = Record
    Lat: String;
    Lng: String;
    Result: string;
  end;

  TFrmViewMaps = class(TForm)
    WebBrowser1: TWebBrowser;
    LatitudeEdit: TEdit;
    LongitudeEdit: TEdit;
    procedure FormShow(Sender: TObject);
  private
    { Private declarations }
    fAddress: string;
    HTMLWindow2: IHTMLWindow2;
    procedure LoadGoogleApi;
    function GoogleApiReady: boolean;
    procedure ExecuteScript(AScript: string);
    function GetElementByID(AElementID: string): IHTMLElement;
    function GetElementValue(ElementID: string): string;
    function GetGeocode(Address: string): TLocation;
  public
    { Public declarations }
    constructor create(AOwner: TComponent; AAddress: string); reintroduce;
  end;

var
  FrmViewMaps: TFrmViewMaps;

implementation

uses  ActiveX;

{$R *.dfm}

const
HTMLStr: AnsiString =
'<html> '+
'<head> '+
'<meta name="viewport" content="initial-scale=1.0, user-scalable=yes" /> '+
''+
'<script type="text/javascript" src="http://maps.google.com/maps/api/js?  v=3.22"></script> '+
'<script type="text/javascript"> '+
''+
''+
'  var geocoder; '+
'  var map;  '+
'  var trafficLayer;'+
'  var bikeLayer;'+
'  var markersArray = [];'+
''+
''+
'  function initialize() { '+
'    geocoder = new google.maps.Geocoder();'+
'    var latlng = new google.maps.LatLng(40.714776,-74.019213); '+
'    var myOptions = { '+
'      zoom: 11, '+
'      center: latlng, '+
'      mapTypeId: google.maps.MapTypeId.ROADMAP '+
'    }; '+
'    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); '+
'    trafficLayer = new google.maps.TrafficLayer();'+
'    bikeLayer = new google.maps.BicyclingLayer();'+
'    map.set("streetViewControl", false);'+
'  } '+
''+
''+
'  function codeAddress(address) { '+
'    if (geocoder) {'+
'      geocoder.geocode( { address: address}, function(results, status) { '+
'        if (status == google.maps.GeocoderStatus.OK) {'+
'          map.setCenter(results[0].geometry.location);'+
'          var myLatlng = new google.maps.LatLng( results[0].geometry.location.lat(), results[0].geometry.location.lng()); '+
'          var marker = new google.maps.Marker({ '+
'            position: myLatlng, '+
'            title: "", '+
'            map: map '+
'          }); '+
'        markersArray.push(marker); '+
'        document.getElementById("hiddenlat").value = myLatlng.lat(); '+
'        document.getElementById("hiddenlng").value = myLatlng.lng(); '+
' '+
'        } else {'+
'            document.getElementById("hiddenlat").value = "error"; '+
'            document.getElementById("hiddenlng").value = "error"; '+
'           alert("Geocode was not successful for the following reason: " +    status);'+
'        }'+
'      });'+
'    }'+
'  }'+
''+
''+
''+
'  function GotoLatLng(Lat, Lang) { '+
'   var latlng = new google.maps.LatLng(Lat,Lang);'+
'   map.setCenter(latlng);'+
'   PutMarker(Lat, Lang, Lat+","+Lang);'+
'  }'+
''+
''+
'function ClearMarkers() {  '+
'  if (markersArray) {        '+
'    for (i in markersArray) {  '+
'      markersArray[i].setMap(null); '+
'    } '+
'  } '+
'}  '+
''+
'  function PutMarker(Lat, Lang, Msg) { '+
'   var latlng = new google.maps.LatLng(Lat,Lang);'+
'   var marker = new google.maps.Marker({'+
'      position: latlng, '+
'      map: map,'+
'      title: Msg+" ("+Lat+","+Lang+")"'+
'  });'+
' markersArray.push(marker); '+
'  }'+
''+
''+
'  function TrafficOn()   { trafficLayer.setMap(map); }'+
''+
'  function TrafficOff()  { trafficLayer.setMap(null); }'+
''+''+
'  function BicyclingOn() { bikeLayer.setMap(map); }'+
''+
'  function BicyclingOff(){ bikeLayer.setMap(null);}'+
''+
'  function StreetViewOn() { map.set("streetViewControl", true); }'+
''+
'  function StreetViewOff() { map.set("streetViewControl", false); }'+
''+
''+'</script> '+
'</head> '+
'<body onload="initialize()"> '+
'  <div id="map_canvas" style="width:100%; height:100%"></div> '+
'<input type="hidden" id="hiddenlat" value="0" />'+
'<input type="hidden" id="hiddenlng" value="0" />'+
'</body> '+
'</html> ';


constructor TFrmViewMaps.create(AOwner: TComponent; AAddress: string);
begin
  inherited create(AOwner);
  fAddress := AAddress;
end;

procedure TFrmViewMaps.LoadGoogleApi;
var
  aStream: TMemoryStream;
begin
  WebBrowser1.Navigate('about:blank'); //Set the location to an empty page

  if Assigned(WebBrowser1.Document) then
  begin
    aStream := TMemoryStream.Create; //create a TStream to load the Page from the string   
    try
      aStream.WriteBuffer(Pointer(HTMLStr)^, Length(HTMLStr));
      aStream.Seek(0, soFromBeginning);
      (WebBrowser1.Document as IPersistStreamInit).Load(TStreamAdapter.Create(aStream));
    finally
      aStream.Free;
    end;
    HTMLWindow2 := (WebBrowser1.Document as IHTMLDocument2).parentWindow;
  end;

  while WebBrowser1.ReadyState <> READYSTATE_COMPLETE do // wait for google
  begin
    sleep(0);
    application.processmessages;
  end;

end;

function TFrmViewMaps.GoogleApiReady: boolean;
begin
  result := (HTMLWindow2 <> nil);
end;

procedure TFrmViewMaps.ExecuteScript(AScript: string);
begin
  HTMLWindow2.execScript(AScript, 'JavaScript');
end;

function TFrmViewMaps.GetElementByID(AElementID: string): IHTMLElement;
begin
  result := (WebBrowser1.Document as IHTMLDocument3).getElementByID(AElementID);
end;

function TFrmViewMaps.GetElementValue(ElementID: string): string;
var
  HtmlElement: IHTMLElement;
begin
  HtmlElement := GetElementByID(ElementID);
  result := HtmlElement.getAttribute('value', 0);
end;

procedure RemoveInvalidGeoLookupChars(var AString: string);
begin
  AString := StringReplace(StringReplace(Trim(AString), #13, ' ', [rfReplaceAll]), #10, ' ', [rfReplaceAll]);
  // remove invalid chars
  AString := StringReplace(AString, #39, #32, [rfReplaceAll]);  // single quotes
  AString := StringReplace(AString, #34, #32, [rfReplaceAll]);  // double quotes
end;

function TFrmViewMaps.GetGeocode(Address: string): TLocation;
var
  i: integer;
begin
  result.Lat := '0';
  result.Lng := '0';
  LatitudeEdit.text := '0';
  LongitudeEdit.text := '0';
  result.Result := 'OK';
  application.processmessages;
  RemoveInvalidGeoLookupChars(address);
  application.processmessages;
  ExecuteScript(Format('codeAddress(%s)',[QuotedStr(address)]));

  while (GetElementValue('hiddenlat') = '0') do
    application.processmessages;

  result.Lat := GetElementValue('hiddenlat');
  result.lng := GetElementValue('hiddenlng');
end;

procedure TFrmViewMaps.FormShow(Sender: TObject);
var
  Location: TLocation;
begin
  LoadGoogleApi;
  Location := GetGeoCode(fAddress);
  LatitudeEdit.Text := Location.Lat;
  LongitudeEdit.Text := Location.Lng;
end;

end.

To geocode an address from another form, use the following syntax:

frmViewMaps:= TFrmViewMaps.create(self, 'One Microsoft Way, Redmond, WA 98052');
try
  frmViewMaps.showmodal;
finally
  frmViewMaps.destroy;
end;

这篇关于从TWebBrowser中的GoogleMaps获取纬度经度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆