// 使用浏览器的 Geolocation API 获取用户当前位置
if (navigator.geolocation) {
// 如果浏览器支持地理定位
navigator.geolocation.getCurrentPosition(success, error);
} else {
// 浏览器不支持地理定位
console.log("Geolocation is not supported by this browser.");
}
function success(position) {
// 成功获取位置信息时调用
const latitude = position.coords.latitude; // 纬度
const longitude = position.coords.longitude; // 经度
console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
}
function error() {
// 获取位置信息失败时调用
console.log("Unable to retrieve your location.");
}
navigator.geolocation
:用于检测浏览器是否支持地理定位功能。getCurrentPosition(success, error)
:尝试获取用户的当前地理位置。它接受两个回调函数,一个是成功时调用的 success
函数,另一个是失败时调用的 error
函数。position.coords.latitude
和 position.coords.longitude
:分别表示获取到的纬度和经度信息。error
回调函数,并输出相应的错误信息。如果你在使用这段代码时遇到问题,请确保浏览器已经允许访问地理位置信息。
上一篇:js 代码加密
下一篇:js 监听url变化
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站