当前位置: 首页 > Web前端 > HTML5

H5如何唤起百度地图App

时间:2023-04-05 17:56:56 HTML5

最近接手一个需求,需要混合开发。前端用h5做完后,页面嵌入ios和android,需要百度地图的地图导航。具体功能如下:如果移动端(ios、android)安装了百度地图,点击导航按钮即可调出百度地图APP;否则打开web端百度地图导航需要用到的百度地图API文档链接如下:http://lbsyun.baidu.com/index...初始代码://尝试唤起百度地图appwindow.location.href=scheme;变种超时=600;varstartTime=Date.now();vart=setTimeout(function(){varendTime=Date.now();//百度地图app启动成功后,再返回h5页面,此时endTime-startTime必须大于timeout+200;如果激活失败,打开web端百度地图导航if(!startTime||(endTime-startTime)<(timeout+200)){window.location.href='http://api.map.baidu.com/direction'+queryStr+'&output=html';}},超时);问题:以上代码在android机上运行正常,但是在ios端一直执行setTimeout定时器,所以如果是在ios端,即使app在后台,它的h5代码还是会执行。因此,我们需要改变方法。大致思路是:采用轮询的方式,尽量在600ms内唤醒百度地图应用。唤醒失败后判断h5是在前台还是后台。如果在前台,打开网页端百度地图应用。定时器在200ms后清零,无论唤醒成功与否。修改代码:varstartTime=Date.now();变量计数=0;var结束时间=0;vart=setInterval(function(){count+=1;endTime=Date.now()-startTime;if(endTime>800){clearInterval(t);}if(count<30)return;if(!(文档.hidden||document.webkitHidden)){window.location.href='http://api.map.baidu.com/direction'+queryStr+'&output=html';}},20);完整代码:functionwakeBaidu(){vargeolocation=newBMap.Geolocation();geolocation.getCurrentPosition(function(result){if(this.getStatus()==BMAP_STATUS_SUCCESS){varlatCurrent=result.point.lat;//获取纬度varlngCurrent=result.point.lng;//获取经度if(latCurrent&&lngCurrent){varscheme='';//urlObject是我地址栏的查询参数对象varqueryStr='?origin=name:mylocation|latlng:'+latCurrent+','+lngCurrent+'&destination='+urlObject.lat+','+urlObject.lng+'&region='+urlObject.city+'&coord_type=bd09ll&mode=driving';if(isIOS()){//ios端scheme='baidumap://map/direction'+queryStr;}else{//android端scheme='bdapp://map/direction'+queryStr;}//主要实现代码window.location.href=scheme;varstartTime=Date.now();变量计数=0;var结束时间=0;vart=setInterval(function(){count+=1;endTime=Date.now()-startTime;if(endTime>800){clearInterval(t);}if(count<30)return;if(!(document.hidden||document.webkitHidden)){window.location.href='http://api.map.baidu.com/direction'+queryStr+'&output=html';}},20);window.onblur=function(){clearInterval(t);};}else{alert('无法获取位置,请检查手机位置设置');}}});}