Android webview html5地理定位详解
|
2314次阅读|
作者:html5,css3
摘要:Android WebView从assets中加载html5页面,实现地理位置定位,有需要的朋友可以参考下。
今天调研一个html5页面的定位问题,发现在手机浏览器上html5是可以实现定位的,但是在webview中就无法定位了。而我居然以为html5的地理定位在webview中不可行。
第一步准备html5页面
html5页面代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<p id="demo">点击这个按钮,获得您的坐标:</p>
<button onclick="getLocation()">试一下</button>
<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>
04 | < meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8" > |
07 | < p id = "demo" >点击这个按钮,获得您的坐标:</ p > |
08 | < button onclick = "getLocation()" >试一下</ button > |
10 | var x=document.getElementById("demo"); |
13 | if (navigator.geolocation) |
15 | navigator.geolocation.watchPosition(showPosition); |
17 | else{x.innerHTML="Geolocation is not supported by this browser.";} |
19 | function showPosition(position) |
21 | x.innerHTML="Latitude: " + position.coords.latitude + |
22 | "< br />Longitude: " + position.coords.longitude; |
第二步设置android代码
后来又在网上查了查,发现,需要设置一些东西。设置websetting的属性:
01 | webView.setWebViewClient( new WebViewClient()); |
05 | WebSettings webSettings = webView.getSettings(); |
06 | webSettings.setJavaScriptEnabled( true ); |
25 | webSettings.setDomStorageEnabled( true ); |
26 | webView.setWebChromeClient( new WebChromeClient(){ |
30 | public void onGeolocationPermissionsShowPrompt(String origin, |
32 | callback.invoke(origin, true , false ); |
33 | super.onGeolocationPermissionsShowPrompt(origin, callback); |
问题解决!
特别试了试:
同时打开网络和GPS可以定位,获得的是经纬度信息。
只打开网络可以定位,只打开GPS也可以定位。
关闭网络和GPS也可以定位。
由此可见,是由地理位置定位所得,只能获得经纬度信息。
若要获得详细的地址信息,需要调用地图API实现。如下所示:
纬度:116.40387397,经度:39.91488908 详细地址:北京市天安门