使用javascript计算两个邮政编码之间的距离

calculating the distance between two postcodes using javascript

本文关键字:邮政编码 两个 之间 距离 javascript 计算 使用      更新时间:2023-12-30

我正在计算两个邮政编码之间的距离。一个邮政编码坐标是通用的,但另一个邮政代码存储在我需要获取的数据库中。下面的代码无法计算出通用邮政编码和我输入的邮政编码之间的距离。

var x = getDistanceFromLatLonInKm(52.482799000000000, -2.000643000000000, 52.48463500000000, -1.980759000000000);
function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2){
  console.log(lat1, lon1, lat2, lon2); 
var distanceFromSpecificPoint = getDistanceFromLatLonInKm.bind(null, 52.486637, -1.890952); 
  var R = 6371; // Radius of the earth in km 
  var dLat = deg2rad(lat2 - lat1); // deg2rad below 
  var dLon = deg2rad(lon2 - lon1);
  var a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c; // Distance in km 
  return d;
}
function deg2rad(deg) {
  return deg * (Math.PI / 180)
}

document.getElementById('result').textContent = x;
console.log(x)
</script>

如上所述,您可以简单地从服务器端的数据库中获取值,并使用您想要的任何服务器端web框架。我在这里给出的例子是Classic ASP,纯粹是为了向您展示值的输入位置。然后在服务器端,数据库值是常量,您只为一个点输入lat/lon,并获得与数据库lat/lon的距离(此处为常量LAT1/LON1)。dbModel将是服务器端的某个对象,它是从数据库中填充的。然后,您可以从该对象中获取纬度/经度值,以便通过服务器端脚本插入到网页中。

function getDistanceFromLatLonInKm(lat, lon) {
    const EARTH_RADIUS = 6371; // Radius of the earth in km 
    // Here's where you would add the value dynamically from the DB.
    // I'm using classic ASP here just as an example. You'll have to
    // amend for your particular server side web framework, be it
    // JSP, MVC, etc.
    const LAT1 = <%=dbModel.getLatitude()%>;
    const LON1 = <%=dbModel.getLongitude()%>;
    console.log(LAT1, LON1, lat, lon);
    var dLat = deg2rad(lat - LAT1);
    var dLon = deg2rad(lon - LON1);
    var a = Math.pow(Math.sin(dLat / 2), 2) + Math.cos(deg2rad(LAT1)) * Math.cos(deg2rad(LON1)) * Math.pow(Math.sin(dLon / 2), 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = EARTH_RADIUS * c; // Distance in km 
    return d;
}
function deg2rad(deg) {
    return deg * (Math.PI / 180);
}

或者,如果您不要求它像这样是动态的,只需从数据库中获取静态值,并在此处输入它们作为LAT1和LON1的值。

例如

    const LAT1 = 52.482799;
    const LON1 = -2.000643;

那就这样调用你的函数。。。

var distance = getDistanceFromLatLonInKm(52.48463500000000, -1.980759000000000);

进行PAF查找:

FreeMapTools

谷歌地图。只需搜索您的邮政编码,然后从URL中获取纬度/经度。