Android WebView 支持H5的定位Js

在mainActivity.java类onCreate()方法下添加

//启用数据库 
 webview.getSettings().setDatabaseEnabled(true); 
 String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath(); 
//启用地理定位 
webview.getSettings().setGeolocationEnabled(true); 
//设置定位的数据库路径 
webview.getSettings().setGeolocationDatabasePath(dir); 
//最重要的方法,一定要设置,这就是出不来的主要原因
webview.getSettings().setDomStorageEnabled(true);
//配置权限(同样在WebChromeClient中实现) 
webview.setWebChromeClient(new WebChromeClient() { 
@Override 
public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) { 
callback.invoke(origin, true, true); 
super.onGeolocationPermissionsShowPrompt(origin, callback); 

});

在AndroidManifest.xml中添加权限

配置权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

在html5页面添加

<script type="text/javascript">

$(function(){
if (navigator.geolocation) {
// 想干嘛就干嘛
var options = {
enableHighAccuracy: true, 
maximumAge : 10000, 
timeout : 100000
};

//html5定时回调
var watchID = navigator.geolocation.watchPosition(showLocation, errorHandler, options);
}else{
alert("不支持");
}
})
//---------回调成功
function showLocation(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
alert( "您所在的位置: 经度" + lat + ",纬度" + lng );
if(typeof position.address !== "undefined"){
var country = position.address.country;
var province = position.address.region;
var city = position.address.city;
alert(' 您位于 ' + country + province + '省' + city +'市');
}
}
//回调失败
function errorHandler(error) {
alert(error.code);
switch(error.code){
case error.TIMEOUT :
alert( " 连接超时,请重试 " );
break;
case error.PERMISSION_DENIED :
alert( " 您拒绝了使用位置共享服务,查询已取消 " );
break;
case error.POSITION_UNAVAILABLE : 
alert( " 亲爱的火星网友,非常抱歉,我们暂时无法为您所在的星球提供位置服务 " );
break;

}
</script>

posted @ 2017-08-11 11:18  風巽千龍  阅读(663)  评论(0)    收藏  举报