百度地图浏览器API 获取GPS定位是根据调用浏览器核心获取GPS,部分手机型号定位不准,主要是因为部分手机采用的是GOOGLE GPS坐标格式、部分手机用的是原生坐标格式。这两种格式百度地图无法判断,默认是按照原生坐标格式,进行转换成百度地图的坐标格式,而后再进行展示。所以改用h5自带地理定位了。
/**
* @description 定位
* @param {获取到经纬度要执行的函数} fun
*/
export default function getLocation (fun) {
// 检测是否支持地理定位
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function name(position) {
console.log(position.coords.longitude, position.coords.latitude);
setTimeout(() => {
translatePoint(
new window.BMap.Point(position.coords.longitude, position.coords.latitude)
,fun);
}, 1000);
}, showError);
}
else{
console.warn('您的设备不支持地理定位');
}
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
console.warn('您拒绝对获取地理位置的请求', 1);
break;
case error.POSITION_UNAVAILABLE:
console.warn('位置信息是不可用的', 1);
break;
case error.TIMEOUT:
console.warn('请求您的地理位置超时', 1);
break;
case error.UNKNOWN_ERROR:
console.warn('未知错误', 1);
break;
default:
break;
}
}
/**
* @description gps坐标转换为百度坐标
* @param {gps坐标} p
* @param {拿到百度坐标之后执行的自定义回调函数} fun
*/
function translatePoint(p, fun) {
const convertor = new window.BMap.Convertor();
const pointArr = [];
pointArr.push(p);
convertor.translate(pointArr, 1,5, function name(params) {
translateCallback(params, fun);
}); // 转换方法,参数的含义见下方链接
}
function translateCallback(data, fun) {
if(data.status === 0) {
fun(data.points[0]);
}
}用法:
import getLocation from '@path';
getLocation(fun); // fun是拿到定位后需要执行的操作
fun = (e) => {
console.log(e); // 定位点坐标
}坐标转换方法详解 => 服务文档