HTML5 Geolocation API 用于获得用户的地理位置。
<button id="btn">获取位置</button>
<p id="out"></p>
<script>
btn.onclick = () => {
navigator.geolocation.getCurrentPosition(
pos => {
out.textContent = `纬度:${pos.coords.latitude}, 经度:${pos.coords.longitude}`;
},
err => {
out.textContent = `定位失败:${err.message}`;
}
);
};
</script>
navigator.geolocation浏览器提供的全局对象,用来做定位。
这是整个 API 的入口。
getCurrentPosition():获取一次当前坐标pos对象:
{
"coords": {
"latitude": 35.689487,
"longitude": 139.691711,
"accuracy": 25,
"altitude": null,
"altitudeAccuracy": null,
"heading": null,
"speed": null
},
"timestamp": 1732310425123
}
否则浏览器会拒绝定位
比如按钮点击,否则有的浏览器会拦截。
可以加一个错误回调。