需求描述
在HTML页面获取当前定位经纬度
参考代码
优先使用地理位置定位,定位失败时取百度定位,否则使用高德IP定位:
<!-- 引入百度地图API(需申请百度地图开发者账号,创建秘钥使用) -->
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=您的密钥"></script>
// 判断字符串是否为空
function isStrEmpty(str) {
return "undefined" === typeof str || str === null || str === "undefined" || str === "null" || str.toString().trim().length < 1;
}
var current_lng, current_lat; // 当前定位经度,当前定位纬度
var getCurrentPosition = function () {
console.log("定位中.."); // 此处可在页面增加定位加载效果提示用户
if (navigator.geolocation) { // 浏览器支持定位
navigator.geolocation.watchPosition( // 监听定位变更
function (pos) { // 成功回调函数,接受一个地理位置的对象作为参数(网页需配置https)
current_lng = pos.coords.longitude;
current_lat = pos.coords.latitude;
console.log("地理位置定位: " + current_lng + "," + current_lat); // 注意:此处经纬度为wgs84坐标
console.log("定位成功!"); // 此处可在页面增加定位成功提示
},
function (error) { // 出错时取百度地图定位(需引入引入百度地图API)
console.log("需开启定位权限!"); // 此处可在页面增加提示
var geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition(function (r) {
if (this.getStatus() == BMAP_STATUS_SUCCESS) {
current_lng = r.point.lng;
current_lat = r.point.lat;
console.log("百度地图定位: " + current_lng + "," + current_lat); // 注意:此处经纬度为百度坐标
console.log("定位成功!"); // 此处可在页面增加定位成功提示
}
});
},
{
enableHighAccuracy: true, // 是否获取高精度结果
timeout: 1000, // 超时,毫秒
maximumAge: 0 // 可以接受多少毫秒的缓存位置
});
} else { // 高德IP定位(精度低)
console.log("您的浏览器不支持定位..");
$.ajax({ // 需引入jQuery
type: "POST",
// 调用高德IP定位(需申请高德地图开发者账号,创建秘钥使用)
url: "https://restapi.amap.com/v3/ip?key=您的秘钥",
async: true, // 默认:异步请求
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "",
success: function (data) {
// console.log(data, JSON.stringify(data));
if ("rectangle" in data && !isStrEmpty(data.rectangle)) { // data.rectangle:IP所在经纬度范围
// data.rectangle:"116.0119343,39.66127144;116.7829835,40.2164962"
var locList = data.rectangle.split(";");
var lngSum = 0, latSum = 0;
for (var i in locList) {
var locInfos = locList[i].split(",");
lngSum = parseFloat(lngSum) + parseFloat(locInfos[0]);
latSum = parseFloat(latSum) + parseFloat(locInfos[1]);
}
// 取返回经纬度的平均值,保留6位小数
current_lng = parseFloat(lngSum / locList.length).toFixed(6);
current_lat = parseFloat(latSum / locList.length).toFixed(6);
console.log("高德地图定位: " + current_lng + "," + current_lat); // 定位误差巨大..经纬度坐标不同导致的偏差可忽略不计
console.log("定位成功!"); // 此处可在页面增加定位成功提示
}
}
});
}
};
tips
①要在HTML网页获取到较为精确的定位,需要给网页配置HTTPS,以及提示用户打开定位;
②使用百度/高德定位需申请相应的开发者账号,创建秘钥使用;
③每种方式取到的经纬度坐标不同,为了减少误差,需根据具体需求进行坐标转换
参考文档
[1] 地理位置定位(navigator.geolocation)
[2] 百度地图定位(BMap.Geolocation)
[3] 高德IP定位
[4] jQuery.ajax
[5] 配置HTTPS
[6] 坐标转换