jQuery 地理位置:无法读取未定义的 属性 'coords'

jQuery Geolocation : Cannot read property 'coords' of undefined

我已经浏览了几个小时来寻找解决方案。 本人知之甚少JavaScript,其实正在学习

我在获取用户的 GPS 位置时遇到问题。我想 : - 获取用户的位置 (jQuery)。 - 通过 Ajax > PHP.

将其传输到服务器端

这是我的 JS 代码:

$(document).ready(function () {
    initCoords();
});

function initCoords() {
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(updateLocation, errorHandler, {enableHighAccuracy: false, maximumAge: 60000, timeout: 27000});
    } else
    {
        alert('Wrong browser.');
    }
}

function updateLocation(position)
{
    var longitude=position.coords.longitude;
    var latitude=position.coords.latitude;
    console.log(longitude);
    $.ajax({
        url: "../../ajax/account/handlegeolocation",
        type: "post",
        dataType: "json",
        data: {"longitude": longitude, "latitude": latitude},
        success: function (response) {
            console.log(response.message);
        },
        error: function (xmlhttprequest, textstatus, message) {
            console.log(message);
        }
    }).then(function () {
        setTimeout(updateLocation, 30);
    });
}

function errorHandler(error)
{
    console.log('Geolocation error : code ' + error.code + ' - ' + error.message);
}

令我惊讶的是我在加载页面时看到的内容。 返回位置,但是JS说对象returns位置未定义

感谢您的帮助!

这是因为您没有传递来自

的位置对象
setTimeout(updateLocation, 30);

从超时调用函数 initCoords 将解决您的问题。

或者这是您的代码,经过一些编辑且没有任何错误。

$(document).ready(function () {
    initCoords();
});

function initCoords() {
    if (navigator.geolocation) {
        getGeoLocation();
    } else {
        alert('Wrong browser.');
    }
}
function getGeoLocation() {
    navigator.geolocation.getCurrentPosition(updateLocation, errorHandler, { enableHighAccuracy: false, maximumAge: 60000, timeout: 27000 });
}
function updateLocation(position) {
    var longitude = position.coords.longitude;
    var latitude = position.coords.latitude;
    $.ajax({
        url: "../../ajax/account/handlegeolocation",
        type: "post",
        dataType: "json",
        data: { "longitude": longitude, "latitude": latitude },
        success: function (response) {
            console.log(response.message);
        },
        error: function (xmlhttprequest, textstatus, message) {
            console.log(message);
        }
    }).then(function () {
        setTimeout(getGeoLocation, 30);
    });
}

function errorHandler(error) {
    console.log('Geolocation error : code ' + error.code + ' - ' + error.message);
}