js如何获取当前经纬度

JavaScript 可以通过 Geolocation API 获取设备的位置信息,包括经纬度等。可以使用以下代码获取当前位置的经纬度:

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        console.log("Latitude: " + latitude + " Longitude: " + longitude);
    });
} else {
    console.log("Geolocation is not supported by this browser.");
}

上述代码会首先检查浏览器是否支持 Geolocation API,如果支持,则调用 getCurrentPosition 方法获取当前位置信息。getCurrentPosition 方法接收两个参数:成功获取位置信息的回调函数和失败时的回调函数。在上述代码中,我们传入了一个回调函数,其中 position.coords.latitude 和 position.coords.longitude 分别表示设备的纬度和经度。

需要注意的是,为了使用 Geolocation API,需要使用 https 协议或本地测试的时候可使用 localhost 协议。在非安全连接下(http),浏览器会阻止该 API 进行使用。

猜你喜欢

转载自blog.csdn.net/qq_19820589/article/details/131015264