js 实现定位
使用 Geolocation API 获取当前位置
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: ${latitude}, Longitude: ${longitude}`);
},
(error) => {
console.error("Error getting location:", error.message);
}
);
} else {
console.error("Geolocation is not supported by this browser.");
}
监听位置变化
如果需要持续跟踪位置变化(如导航应用),可以使用 watchPosition() 方法。它会返回一个 ID,用于后续清除监听。
const watchId = navigator.geolocation.watchPosition(
(position) => {
console.log(`New position: ${position.coords.latitude}, ${position.coords.longitude}`);
},
(error) => {
console.error("Error watching position:", error.message);
}
);
// 清除监听
// navigator.geolocation.clearWatch(watchId);
高精度定位配置
通过 enableHighAccuracy 选项可以请求更高精度的定位(可能增加功耗或延迟),同时可以设置超时时间(timeout)和缓存有效期(maximumAge)。
navigator.geolocation.getCurrentPosition(
(position) => { /* 处理位置 */ },
(error) => { /* 处理错误 */ },
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
}
);
反向地理编码(坐标转地址)
获取经纬度后,可以通过第三方 API(如 Google Maps API 或 OpenStreetMap)将坐标转换为具体地址。以下是使用 Google Maps Geocoding API 的示例:
async function getAddress(latitude, longitude) {
const apiKey = "YOUR_API_KEY";
const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}&key=${apiKey}`;
try {
const response = await fetch(url);
const data = await response.json();
if (data.results && data.results.length > 0) {
return data.results[0].formatted_address;
}
} catch (error) {
console.error("Geocoding error:", error);
}
}
注意事项
- 用户权限:浏览器会提示用户授权定位权限,需确保应用场景合理。
- HTTPS 要求:大多数浏览器仅在 HTTPS 环境下允许定位(本地开发除外)。
- 备用方案:对于不支持 Geolocation API 的场景,可以通过 IP 地址粗略定位(精度较低)。
- 错误处理:需处理用户拒绝授权(
PERMISSION_DENIED)或定位失败(POSITION_UNAVAILABLE)等情况。







