![](/img/trans.png)
[英]Send current gps coordinates to mySQL database using google maps api
[英]Find distance from current location using gps coordinates
我試圖找出距我當前位置的特定gps點的距離。 所以我有一個HTML文件,可以計算並顯示當前位置。 然后,通過GET消息將坐標發送到服務器。 服務器中的php文件具有計算距離的功能。 但是,沒有從php文件顯示echo
顯。 這是我的實現:
HTML文件
<!DOCTYPE HTML>
<html>
<head>
<script>
var lat;
var lng;
function clicked(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(success,error);
}
else{
document.getElementById("hello").innerHTML = "Not supported";
}
function success(position){
lat = position.coords.latitude;
lng = position.coords.longitude;
document.getElementById("hello").innerHTML = "lat :"+lat+"<br>long :"+lng;
}
function error(err){
document.getElementById("hello").innerHTML = "Error Code: "+error.code;
if(err.code == 1){
document.getElementById("hello").innerHTML = "Access denied";
}
if(err.code == 2){
document.getElementById("hello").innerHTML = "Position unavailable";
}
}
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("list").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","queryRestaurantsList.php?lat="+lat+"&lng="+lng,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div onclick="clicked()">Click Me!</div>
<div id="hello"></div>
<div id="list"></div>
</body>
</html>
PHP文件
<?
mysql_connect($host,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
echo "HEllo WOrld!";
function distance($lat1,$lng1,$lat2,$lng2,$unit){
$theta = $lng1 - $lng2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == "M") {
return (($miles * 1.609344)/1000);
}
}
//Check if POST array is empty or not
$lat1 = $_GET['lat'];
$lng1 = $_GET['lng'];
echo $lat1;
echo $lng1;
$query = "SELECT RestaurantID,Latitude,Longitude FROM RGeoLocation"
$result = mysql_query($query) or die("Unable to execute query");
$i = 0;
$answer = array();
while ($row = mysql_fetch_array($result)){
$lat2 = row['Latitude'];
$lng2 = row['Longitude'];
$id = row['RestaurantID'];
$answer[$i] = distance($lat1,$lng1,$lat2,$lng2,"M")
$i++;
}
echo $answer;
?>
據我所知,您需要使用第二個參數為false的xmlhttp.open(這將導致腳本暫停並等待響應)。 然后,您需要從Java中寫入xmlhttp.responseText,而xmlhttp.repsonseText應該包含php腳本的輸出。
因此,這實際上不是關於GPS距離計算的問題-而是有關PHP基本原理的問題。
在您的PHP腳本中,$ answer是一個數組。 您不能像字符串或整數那樣簡單地回顯數組。
也許您應該發送以JSON編碼的響應:
echo json_encode($answer);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.