我正在尝试在xamarin表单应用程序中启用webview以获取Android设备的当前GPS坐标 . 目前webview /网站将在手机或笔记本电脑上的Chrome浏览器中打开时返回GPS坐标,但在应用程序内则不会 . 尝试尽可能简单地工作并在之后进行扩展 .
代码到目前为止:XAML页面:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="UITrial.Page2"
BackgroundColor = "#f0f0ea">
<Label Text="{Binding MainText}" VerticalOptions="Center" HorizontalOptions="Center" />
<WebView Source="https://danu6.it.nuigalway.ie/OliverInternetProgramming/project/Loginproject.html" />
</ContentPage>
HTML PAGE:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.watchPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";}
}
function showPosition(position) {
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
2 回答
您需要在Droid项目中使用自定义
WebChromeClient
forWebView
. 请参阅Android WebView Geolocation .在Xamarin.Forms中,您可以按照以下步骤完成此操作:
并在Xaml中使用它:
GeoWebView
创建自定义渲染器,如下所示:AndroidManifest.xml
:然后,您将正确地在webview中获取您的位置 .
干杯埃尔维斯设法使一切工作,不得不做一些小改动,所以将发布我做的所有细节:
在App.xaml.cs中:
}
在MainPage.xaml中确保您的网站是“https”
正如Elvis所说,然后需要在PLC项目中创建自定义控件 . 右键单击并添加新的“Class”来执行此操作 .
然后在Droid类中创建自定义渲染 . 最初有一些错误,主要是缺少'using'指令以及'assembly'中需要的关键字 .
在这些变化之后,一切都很完美再次感谢猫王!