目录
2)通过高德地图调用(chrome本地可用,手机需要https)
概述
获取经纬度坐标有两种方式:1)通过html原生调用(手机可用);(2)通过高德地图调用;
可直接复制代码使用,高德需要准备key
因为浏览器对于获取位置信息有限制,所以需要使用HTTPS加密链接。
1)通过html原生调用 (仅手机可用)
扫码查看HTML原生获取坐标DEMO

https://demo.goodthink.wang:8443/position/yuansheng.html
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>原生H5页面获取手机坐标</title>
<meta name="viewport" content="initial-scale=1.0,
maximum-scale=1.0, user-scalable=no" />
</head>
<body>
<p id="msg"></p>
<div id="Text">位置:</div>
</body>
<script type="text/javascript">
var str="不支持定位功能";
if (navigator.geolocation){
str="支持定位功能,如果没有获取到坐标可能没有使用https加密链接。";
console.log(str);
document.getElementById("msg").innerHTML = str;
navigator.geolocation.getCurrentPosition( function (position) {
str+="<p>获取定位</p>";
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);
}
</script>
</html>
2)通过高德地图调用(chrome本地可用,手机需要https)
扫码查看高德获取坐标DEMO

高德H5页面获取手机坐标(本地文件可用,手机需要https)
使用高德请自行申请Key
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- 引用高德地图JS API脚本 -->
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.3&key=您申请的key值"></script>
<title>高德H5页面获取手机坐标(本地文件可用,手机需要https)</title>
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<script type="text/javascript">
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 +
'<br>精度范围:' + obj.accuracy +
'米<br>定位结果的来源:' + obj.location_type +
'<br>状态信息:' + obj.info +
'<br>地址:' + obj.formattedAddress +
'<hr>地址信息:' + JSON.stringify(obj.addressComponent, null, 4);
document.getElementById("message").innerHTML = str;
}
function onError(obj) {
alert(obj.info + '--' + obj.message);
console.log(obj);
}
</script>
</head>
<body>
<div id=message></div>
</body>
</html>