js 实现定位
使用 Geolocation API 获取当前位置
在 JavaScript 中,可以使用 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);
使用地图 API 显示位置
结合地图 API(如 Google Maps 或 Leaflet),可以将获取的位置显示在地图上。

<!DOCTYPE html>
<html>
<head>
<title>Location Map</title>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
</head>
<body>
<div id="map" style="height: 400px; width: 100%;"></div>
<script>
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
const map = new google.maps.Map(document.getElementById("map"), {
center: { lat: position.coords.latitude, lng: position.coords.longitude },
zoom: 15
});
new google.maps.Marker({
position: { lat: position.coords.latitude, lng: position.coords.longitude },
map: map
});
},
(error) => {
console.error(`Error: ${error.message}`);
}
);
}
</script>
</body>
</html>
处理权限问题
现代浏览器要求用户明确授权地理位置访问权限。如果用户拒绝权限,需要在错误回调中处理。
navigator.geolocation.getCurrentPosition(
(position) => {
console.log("Location access granted.");
},
(error) => {
if (error.code === error.PERMISSION_DENIED) {
console.error("User denied location access.");
}
}
);
使用 IP 地址作为备选方案
如果用户拒绝地理位置权限,可以使用 IP 地址作为备选方案(精度较低)。可以通过第三方 API(如 ipapi.co)获取大致位置。
fetch("https://ipapi.co/json/")
.then(response => response.json())
.then(data => {
console.log(`Approximate location: ${data.city}, ${data.country}`);
})
.catch(error => {
console.error("Error fetching IP location:", error);
});






