js实现定位地址
使用Geolocation API获取当前位置
浏览器原生提供的navigator.geolocation对象可以获取设备的地理位置。调用getCurrentPosition()方法会返回经纬度坐标:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
console.log(`纬度: ${latitude}, 经度: ${longitude}`);
},
(error) => {
console.error('获取位置失败:', error.message);
}
);
} else {
console.error('浏览器不支持地理定位');
}
转换为实际地址(逆地理编码)
获取经纬度后,可通过第三方API(如Google Maps API或高德/百度地图API)转换为具体地址:
// 使用高德地图逆地理编码API示例
function getAddress(lng, lat) {
const key = '你的高德API密钥';
fetch(`https://restapi.amap.com/v3/geocode/regeo?key=${key}&location=${lng},${lat}`)
.then(response => response.json())
.then(data => {
const address = data.regeocode.formatted_address;
console.log('详细地址:', address);
});
}
持续监听位置变化
需要跟踪移动设备的位置时,可使用watchPosition()方法:
const watchId = navigator.geolocation.watchPosition(
(position) => {
console.log('当前位置:', position.coords);
},
(error) => {
console.error('监听失败:', error);
},
{ enableHighAccuracy: true, timeout: 5000 }
);
// 停止监听
// navigator.geolocation.clearWatch(watchId);
浏览器兼容性注意事项
- HTTPS环境下才能正常工作(本地开发除外)
- iOS 10+需要用户明确授权
- 部分国产浏览器可能需要特定内核模式
精度优化参数
getCurrentPosition()和watchPosition()可接受配置对象:
{
enableHighAccuracy: true, // 是否高精度
timeout: 10000, // 超时毫秒数
maximumAge: 300000 // 缓存位置的最大年龄
}





