在PHP变量中存储和使用Javascript值

时间:2018-12-13 04:12:59

标签: javascript php jquery html html5

我有以下脚本,可以访问设备的HTML 5地理位置,然后使用PHP计算KM中两个GEO位置坐标之间的距离。现在的问题是,我在处理JavaScript方面没有好手。所以我在这里遇到麻烦。我希望从HTML 5地理位置接收到的纬度和经度值反映在$userLatPos$userLonPos中。我怎样才能做到这一点?

<?php
function distance($lat1, $lon1, $lat2, $lon2, $unit) {
  if(($lat1 == $lat2) && ($lon1 == $lon2)){
    return 0;
  }else{
    $theta = $lon1 - $lon2;
    $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 == "K") {
      return ($miles * 1.609344);
    } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
      return $miles;
    }
  }
}

$userLatPos = ''; // Latitude position from the JavaScript below
$userLonPos = ''; // Longitude position from the JavaScript below

$distance = distance($userLatPos, $userLonPos, 22.5830, 88.3373, "K");

echo "Distance: ".number_format($distance,2,".","")."";
?>
<!DOCTYPE html>
<html>
  <body>
  <p>Click the button to get your coordinates.</p>
  <button onclick="getLocation()">Try It</button>
  <p id="demo"></p>

  <script>
    var x = document.getElementById("demo");
    function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showError);
      } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
      }
    }

    function showPosition(position) {
      x.innerHTML = "Latitude: " + position.coords.latitude +
      "<br>Longitude: " + position.coords.longitude;
    }

    function showError(error) {
      switch(error.code) {
        case error.PERMISSION_DENIED:
          x.innerHTML = "User denied the request for Geolocation."
          break;
        case error.POSITION_UNAVAILABLE:
          x.innerHTML = "Location information is unavailable."
          break;
        case error.TIMEOUT:
          x.innerHTML = "The request to get user location timed out."
          break;
        case error.UNKNOWN_ERROR:
          x.innerHTML = "An unknown error occurred."
          break;
      }
    }
  </script>
  </body>
</html>

0 个答案:

没有答案