gpt4 book ai didi

javascript - jQuery 地理定位 : Cannot read property 'coords' of undefined

转载 作者:行者123 更新时间:2023-12-03 03:30:38 24 4
gpt4 key购买 nike

我已经浏览了几个小时来寻找解决方案。我对 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说返回位置的对象未定义。

Capture Results Jquery

感谢您的帮助!

最佳答案

这是因为您没有从

传递位置对象
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);
}

关于javascript - jQuery 地理定位 : Cannot read property 'coords' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46124994/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com