最近接手了一個需求,要求混合式開發,前端做好 h5 后將頁面嵌入到 ios 和 android 中,需要用到百度地圖的地圖導航。具體功能點如下:
如果手機端(ios, android)安裝了百度地圖,點擊導航按鈕,喚起百度地圖 app
否則,打開 web 端百度地圖導航
需要用到的百度地圖的 api 文檔鏈接如下:http://lbsyun.baidu.com/index.php?title=uri/api/ios
最開始的代碼:
// 嘗試喚起百度地圖 app window.location.href = scheme; var timeout = 600; var startTime = Date.now(); var t = setTimeout(function () { var endTime = 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'; } }, timeout);
問題:
上面這段代碼在 android 機器上運行是沒有問題的,可是在 ios 上卻始終執行了 setTimeout 這個計時器,所以如果在 ios 端,即使 app 處于后臺,它的 h5 代碼還是會執行。
所以需要換一種方式,總的思路是:
修改后的代碼:
var startTime = Date.now(); var count = 0; var endTime = 0; var t = 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);
完整的代碼:
function wakeBaidu() { var geolocation = new BMap.Geolocation(); geolocation.getCurrentPosition(function (result) { if (this.getStatus() == BMAP_STATUS_SUCCESS) { var latCurrent = result.point.lat; //獲取到的緯度 var lngCurrent = result.point.lng; //獲取到的經度 if (latCurrent && lngCurrent) { var scheme = ''; // urlObject 是我這邊地址欄查詢參數對象 var queryStr = '?origin=name:我的位置|latlng:' + latCurrent + ',' + lngCurrent + '&destination=' + urlObject.lat + ',' + urlObject.lng + '®ion=' + 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; var startTime = Date.now(); var count = 0; var endTime = 0; var t = 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('獲取不到定位,請檢查手機定位設置'); } } }); }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答