2012-05-16 6 views
3

사용자의 위치 정보를 MYSQL 데이터베이스에 1 분마다 전송하는 애플리케이션을 작성하려고합니다. 이 코드는 지금 가지고 있지만 작동하지 않습니다. 이 기능을 사용하려면 어떻게 변경해야합니까?매분마다 사용자의 geolocation을 서버에 보냅니다.

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)); 
?> 

그리고, 이것은 여러 변수를 보낼 수있는 올바른 방법이 아니다 가정이있다? 나는 단지 하나 개의 값을 사용하는 경우 방화범의 콘솔이 나에게

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; 

답변

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

관련 문제