一、第一種方法使用百度定位
1.在public處放入
<script type="text/javascript"src="https://api.map.baidu.com/api?v=3.0&type=webgl&ak=您的密鑰"></script>
密鑰生成方法網上有許多
2.在方法里使用
let that = this; var geolocation = new BMapGL.Geolocation(); // 開啟SDK輔助定位 geolocation.enableSDKLocation(); geolocation.getCurrentPosition(function(res) { console.log(res, "獲取定位");
if (res.accuracy == null) {
that.load = false;
console.log("定位失敗,請開啟定位!");
//用戶拒絕地理位置授權
return;
}
});
這樣就可以得到定位了
二、使用h5的定位
1.在方法里使用
let that = this; var location_lon = ""; var location_lat = ""; // 經度,緯度 if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { location_lon = position.coords.longitude; location_lat = position.coords.latitude; console.log(location_lon, location_lat, "獲取定位"); }); } else { alert("您的設備不支持定位功能"); }
這樣就可以得到定位了
其它:定位不准的問題
我們可以先使用h5的定位來獲取經緯度,然后通過百度來進行經緯度轉換
1,查看百度經緯度轉換api文檔
https://lbsyun.baidu.com/index.php?title=webapi/guide/changeposition
2,這就可以知道通過請求百度api地址可以進行轉換(注:如使用其它請求方式可能出現跨域問題)
貼入代碼
此處,先要下載 npm i jsonp --save-dev
然后在頁面中引用import jsonp from 'jsonp'
getLocation() { //方法二 H5 獲取當前地理位置得到經緯度 let that = this; if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( this.showLocation, this.locationError ); } else { alert("您的設備不支持定位功能"); } }, showLocation(position) { var x = position.coords.longitude; var y = position.coords.latitude; console.log(x, y, "h5定位");
//coords:需轉換的源坐標,多組坐標以“;”分隔
(經度,緯度)
//from :源坐標類型
//to:目標坐標類型
jsonp( `https://api.map.baidu.com/geoconv/v1/?coords=${x},${y}&from=1&to=5&ak=你的密鑰`, null, (err, data) => { if (err) { console.error(err.message); } else { console.log(data); } } ); }, locationError(error) { switch (error.code) { case error.PERMISSION_DENIED: alert("用戶拒絕地理定位請求。"); break; case error.POSITION_UNAVAILABLE: alert("位置信息不可用。"); break; case error.TIMEOUT: alert("獲取用戶位置的請求超時。"); break; case error.UNKNOWN_ERROR: alert("發生未知錯誤。"); break; } },
我們使用定位后需要把頁面放在服務器上也就是hhtps域名上才能定位