gpt4 book ai didi

php - 每分钟将用户的地理位置发送到服务器

转载 作者:可可西里 更新时间:2023-11-01 08:07:03 34 4
gpt4 key购买 nike

我正在尝试编写一个应用程序,每分钟左右将用户的地理位置发送到 MYSQL 数据库。这是我现在拥有的代码,但它不起作用。我需要如何更改它才能使其正常工作?

JS:

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
</head>

<body>
<script>
setInterval ( "onPositionUpdate()", 10000 );
function onPositionUpdate(position)
{
var lat = position.coords.latitude;
var lng = position.coords.longitude;
jQuery.ajax({ type: "POST",
url: "myURL/location.php",
data: 'x='+lat+ '&y='+lng ,
cache: false,
});
}

if(navigator.geolocation)
navigator.geolocation.watchPosition(onPositionUpdate);
else
alert("navigator.geolocation is not available");



</script>
</body>
</html>

和PHP:

<?php
include 'config.php';

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

// new data

$x = @$_POST['x'];
$y = @$_POST['y'];
// query
$sql = "update locations set x=?, y=? where username = asd";
$q = $conn->prepare($sql);
$q->execute(array($x), ($y));
?>

而且我想这不是发送多个变量的正确方法,对吧? Firebug 的控制台显示我

 missing } after property list
[Break On This Error]

data: 'x='+lon+'&y='+lat;

当我只使用一个值时,它只将该变量 POST 一次到服务器,然后在控制台给出:

position is undefined
[Break On This Error]

var lat = position.coords.latitude;

最佳答案

你需要做类似的事情:

var currPosition;
navigator.geolocation.getCurrentPosition(function(position) {
updatePosition(position);
setInterval(function(){
var lat = currPosition.coords.latitude;
var lng = currPosition.coords.longitude;
jQuery.ajax({
type: "POST",
url: "myURL/location.php",
data: 'x='+lat+'&y='+lng,
cache: false
});
}, 1000);
}, errorCallback);

var watchID = navigator.geolocation.watchPosition(function(position) {
updatePosition(position);
});

function updatePosition( position ){
currPosition = position;
}

function errorCallback(error) {
var msg = "Can't get your location. Error = ";
if (error.code == 1)
msg += "PERMISSION_DENIED";
else if (error.code == 2)
msg += "POSITION_UNAVAILABLE";
else if (error.code == 3)
msg += "TIMEOUT";
msg += ", msg = "+error.message;

alert(msg);
}

关于php - 每分钟将用户的地理位置发送到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10612252/

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