将纬度和经度转换为公里

Convert Latitude and Longitude into kms

我正在构建应用程序,使用以下代码

获取用户的 latitudelongitude
<!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);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    } }

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

</body> </html>

现在我想把它转换成公里,这样我就可以与其他纬度和经度进行比较,并以公里为单位计算它们之间的差异。

考虑到纬度和经度是一个特定的点,您不能将其直接转换为千米,这是一个距离,即分隔 两个 点的长度。

但是你可以用数学公式得到两个坐标 (lat+long) 之间的距离。 我不是很擅长数学,但你可以通过在 Google 上简单搜索找到这样的公式: here is the first result

您可能还会发现有关此主题的有用信息: How to convert latitude or longitude to meters?

This Script is usefull for you, but its in php

function distance($lat1, $lon1, $lat2, $lon2, $unit) {

      $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;
     }
  }

Function to use

  echo distance(32.9697, -96.80322, 29.46786, -98.53506, "M") . " Miles<br>";
  echo distance(32.9697, -96.80322, 29.46786, -98.53506, "K") . " Kilometers<br>";
  echo distance(32.9697, -96.80322, 29.46786, -98.53506, "N") . " Nautical Miles<br>";

您要找的是 Haversine formula; there's a PHP implementation here