目录
概述
1)通过html原生调用 (手机可用)
2)通过高德地图调用(chrome本地可用,手机需要https)
概述
获取经纬度坐标有两种方式:1)通过html原生调用(手机可用);(2)通过高德地图调用;
可直接复制代码使用,高德需要准备key
因为浏览器对于获取位置信息有限制,所以需要使用HTTPS加密链接。
私人服务器偶尔出问题。我会不定期修复,或通过点击这里打开或添加QQ110146324提醒我。
1)通过html原生调用 (仅手机可用)
扫码查看HTML原生获取坐标DEMO
https://demo.goodthink.wang:8443/position/yuansheng.html
var str="不支持定位功能";
if (navigator.geolocation){
str="支持定位功能,如果没有获取到坐标可能没有使用https加密链接。";
console.log(str);
document.getElementById("msg").innerHTML = str;
navigator.geolocation.getCurrentPosition( function (position) {
str+="
获取定位
";console.log(str);
document.getElementById("msg").innerHTML = str;
latitude = position.coords.latitude;//获取纬度
longitude = position.coords.longitude;//获取经度
str="位置:"+longitude+","+latitude
document.getElementById("Text").innerHTML = str;
});
}else{
console.log(str);
document.getElementById("Text").innerHTML = str;
alert(str);
}
2)通过高德地图调用(chrome本地可用,手机需要https)
扫码查看高德获取坐标DEMO
高德H5页面获取手机坐标(本地文件可用,手机需要https)
使用高德请自行申请Key
var mapObj = new AMap.Map('');
mapObj.plugin('AMap.Geolocation', function () {
let geolocation = new AMap.Geolocation({
enableHighAccuracy: true, // 是否使用高精度定位,默认:true
timeout: 10000, // 超过10秒后停止定位,默认:无穷大
maximumAge: 0, // 定位结果缓存0毫秒,默认:0
convert: true, // 自动偏移坐标,偏移后的坐标为高德坐标,默认:true
showButton: false, // 显示定位按钮,默认:true
buttonPosition: 'LB', // 定位按钮停靠位置,默认:'LB',左下角
buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
showMarker: true, // 定位成功后在定位到的位置显示点标记,默认:true
showCircle: true, // 定位成功后用圆圈表示定位精度范围,默认:true
panToLocation: true, // 定位成功后将定位到的位置作为地图中心点,默认:true
zoomToAccuracy:true // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
});
mapObj.addControl(geolocation);
geolocation.getCurrentPosition();
AMap.event.addListener(geolocation, 'complete', onComplete); // 返回定位信息
AMap.event.addListener(geolocation, 'error', onError); // 返回定位出错信息
});
function onComplete(obj){
var str = '经纬度:' + obj.position +
'
精度范围:' + obj.accuracy +
'米
定位结果的来源:' + obj.location_type +
'
状态信息:' + obj.info +
'
地址:' + obj.formattedAddress +
'
地址信息:' + JSON.stringify(obj.addressComponent, null, 4);
document.getElementById("message").innerHTML = str;
}
function onError(obj) {
alert(obj.info + '--' + obj.message);
console.log(obj);
}