2012-05-16 82 views
3

我正在嘗試編寫一個應用程序,每分鐘左右將用戶的地理位置發送到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; 

當我只用一個數值,它職位,變量服務器只有一次,該控制檯後得出:

position is undefined 
[Break On This Error] 

var lat = position.coords.latitude; 

回答

4

你需要做的是這樣的:

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); 
} 
+0

我該如何發送每分鐘的位置? setInterval(「updatePosition()」,60000);? – user1323294

+1

爲什麼你需要每分鐘發送一次位置?它會自動發送它改變 – sally

+0

哦,好的。控制檯顯示它只發布一次,所以我認爲它只會發送一次位置。但是,謝謝,這將工作 – user1323294

相關問題