【发布时间】:2015-06-04 07:32:42
【问题描述】:
当我在浏览器中运行 html 页面时一切正常。但在 WPF WebBrowser 中不起作用。元素没有值。
/// <summary>
/// Interaction logic for GeoDialog.xaml
/// </summary>
public partial class GeoDialog : Window
{
public GeoDialog()
{
InitializeComponent();
coord.LoadCompleted += webBrowser_LoadCompleted;
coord.Loaded += delegate
{
coord.Navigate(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Location.html");
};
//GetPosition();
}
private void webBrowser_LoadCompleted(object sender, NavigationEventArgs e)
{
string latitude = "";
string longitude = "";
string error = "";
var htmlDocument = coord.Document as HTMLDocument;
var latitudeEl = htmlDocument.getElementById("latitude");
var longitudeEl = htmlDocument.getElementById("longitude");
var errorEl = htmlDocument.getElementById("error");
latitude = latitudeEl.getAttribute("value");
longitude = longitudeEl.getAttribute("value");
error = errorEl.getAttribute("value");
if (String.IsNullOrEmpty(error))
{
MessageBox.Show(String.Format("Latitude: {0} Longitude: {1}", latitude, longitude));
}
else
MessageBox.Show(String.Format("Error: {0}", error));
}
}
Location.html 以下标记:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<meta http-equiv="X-UA-Compatible" content="IE=10" />
<script type="text/javascript">
window.onload = function () {
var latitude = document.getElementById("latitude");
var longitude = document.getElementById("longitude");
var error = document.getElementById("error");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error, options);
}
}
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(position) {
latitude.value = position.coords.latitude;
longitude.value = position.coords.longitude;
};
function error(err) {
error.value = 'ERROR(' + err.code + '): ' + err.message;
};
function showPosition(position) {
latitude.value = position.coords.latitude;
longitude.value = position.coords.longitude;
}
getLocation();
}
</script>
</head>
<body>
<input type="hidden" id="latitude" />
<input type="hidden" id="longitude" />
<input type="hidden" id="error" />
</body>
</html>
也许还有其他选项可以确定地理坐标。
【问题讨论】:
-
我对此可能是错的,但问题可能是当你在 js 中声明你的变量时:纬度、经度等会创建一个寻找该元素的占位符,但在 C# 中是创建一个局部变量并将元素的值分配给所述变量。在这种情况下,您可以声明一个类成员以通过引用而不是值来访问元素:
private string Latitude { get { return document.getElementById(...).innerHtml; } set { document.getElementById(...).innerHtml = value; } }这有意义吗?
标签: c# wpf geolocation