js 实现定位
使用 Geolocation API 获取当前位置
浏览器原生提供的 navigator.geolocation 接口可直接获取用户地理位置。需用户授权后生效:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
console.log(`纬度: ${latitude}, 经度: ${longitude}`);
},
(error) => {
console.error(`定位错误: ${error.message}`);
}
);
} else {
console.error("浏览器不支持地理定位");
}
通过 IP 地址粗略定位
当用户拒绝共享精确位置时,可通过第三方 IP 定位服务获取大致位置。例如使用 ipapi.co:
fetch('https://ipapi.co/json/')
.then(response => response.json())
.then(data => {
console.log(`国家: ${data.country_name}, 城市: ${data.city}`);
});
高德/百度地图 SDK 集成
国内项目建议使用地图厂商的 SDK 实现精确定位:
// 高德地图示例
AMap.plugin('AMap.Geolocation', () => {
const geolocation = new AMap.Geolocation();
geolocation.getCurrentPosition((status, result) => {
if (status === 'complete') {
console.log(result.position);
} else {
console.error(result.message);
}
});
});
监听位置变化
持续跟踪用户移动需使用 watchPosition,适用于导航类应用:
const watchId = navigator.geolocation.watchPosition(
(position) => {
console.log(position.coords.speed); // 获取移动速度
},
null,
{ enableHighAccuracy: true }
);
// 停止监听
// navigator.geolocation.clearWatch(watchId);
注意事项
- HTTPS 协议下 Geolocation API 才能正常工作
- 移动端定位精度通常高于桌面端
- 部分浏览器会隐藏精确坐标(如 iOS Safari 默认模糊定位)
- 国内地图 SDK 需申请对应的开发者密钥







