Automating Google Maps in C# Web Browser (issue executing javascript properly)

倾然丶 夕夏残阳落幕 提交于 2020-02-07 05:40:05

问题


NOT using API

I am currently attempting to use a web browser in C# to load google maps and automatically focus on my current location, however, for some reason I cannot get this to work properly. The idea is simple. Load Google maps, and either execute the script to focus on my current location:

mapBrowser.Document.InvokeScript("mylocation.onButtonClick");

Or, invoke the button click through an HtmlElement:

HtmlElement myLocationButton = mapBrowser.Document.GetElementById("mylocation");
myLocationButton.InvokeMember("click");

But, of course neither of these methods actually work correctly, the coordinates returned are incorrent and the map never actually focuses. Any ideas on how I can fix this issue properly? The scripts aren't invoked until after the document is actually loaded:

private void mapBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        if(mapBrowser.Url.ToString() == "https://www.google.com/maps/preview/")
        {
            try
            {
                //HtmlElement myLocationButton = mapBrowser.Document.GetElementById("mylocation");
                //myLocationButton.InvokeMember("click");
                mapBrowser.Document.InvokeScript("mylocation.onButtonClick");
                //mapBrowser.Document.InvokeScript("focus:mylocation.main");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Invoking Script: " + ex.Message);
            }
        }
    }

so I don't believe that is the cause of my problem. Even more frustratingly, the auto-focus works fine if I click the button manually.

Any help is appreciated, thank you!

(NOTE, you may have to go into IE and allow Google maps access to your location in order to replicate this issue properly)


回答1:


I've had problem few times that WebBrowser control uses too old version of IE. You need to modify registry to get it to use newer version of IE. I tried "https://www.google.com/maps/preview/" with both IE 8 and 9 and it gave me an error, but it works on IE 10.

See: http://weblog.west-wind.com/posts/2011/May/21/Web-Browser-Control-Specifying-the-IE-Version



来源:https://stackoverflow.com/questions/25256997/automating-google-maps-in-c-sharp-web-browser-issue-executing-javascript-proper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!