辅助H5定位
更新时间:2019年06月03日
百度地图Android定位SDK自V7.3版本起,面向广大开发者提供了辅助H5定位的能力。
辅助H5定位指的是开发者在自己的App中使用百度地图JavaScript API实现Web页面开发时,可调用集成在App中的百度地图定位SDK来获取更精准的位置信息。
1第一步,准备工作
在使用定位SDK进行具体开发工作之前,需获取密钥(AK),并对开发工程进行环境配置工作。详细介绍请参考项目创建部分的说明。
此外,Google在Android 6.0中引入了动态权限获取机制,开发者在使用定位SDK之前,请详细了解关于Android 6.0系统开发须知。2第二步,初始化LocationClient类
请在主线程中声明LocationClient类对象,该对象初始化需传入Context类型参数。推荐使用getApplicationConext()方法获取全进程有效的Context。
核心代码段如下:
mLocationClient = new LocationClient(getApplicationContext()); //声明LocationClient类
3第三步,加载WebView控件
核心代码如下:
contentWebView = (WebView) findViewById(R.id.webview);
4第四步,设置WebView属性
核心代码如下:
contentWebView.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); } public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } }); contentWebView.setWebChromeClient(new WebChromeClient() { // 处理javascript中的alert public boolean onJsAlert(WebView view, String url, String message, final JsResult result) { return true; } // 处理javascript中的confirm public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) { return true; } // 处理定位权限请求 @Override public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) { callback.invoke(origin, true, false); super.onGeolocationPermissionsShowPrompt(origin, callback); } @Override // 设置网页加载的进度条 public void onProgressChanged(WebView view, int newProgress) { TestJSLocation.this.getWindow().setFeatureInt( Window.FEATURE_PROGRESS, newProgress * 100); super.onProgressChanged(view, newProgress); } // 设置应用程序的标题title public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); } }); contentWebView.loadUrl("file:///android_asset/web.html");
5第五步,开启辅助定位
调用如下方法,开启辅助H5定位:
mLocationClient.start(); mLocationClient.enableAssistantLocation(contentWebView);
同时,在H5页面中使用定位接口,并开启辅助定位。 JavaScript API端代码参考如下:
var map = new BMap.Map("allmap"); var point = new BMap.Point(116.331398, 39.897445); map.centerAndZoom(point, 12); var geolocation = new BMap.Geolocation(); // 开启辅助定位 geolocation.enableSDKLocation(); geolocation.getCurrentPosition(function(r){ if (this.getStatus() === BMAP_STATUS_SUCCESS) { var mk = new BMap.Marker(r.point); map.addOverlay(mk); map.panTo(r.point); } });
6第六步,获取位置信息
请参考百度地图JavaScript API对应章节的介绍。
7第七步,关闭辅助定位
完成辅助H5定位功能之后,可调用如下代码关闭SDK端辅助H5定位功能。
mLocationClient.disableAssistantLocation();