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

时间:2016-04-05 14:27:21

标签: javascript geocoding distance haversine

我想弄清楚两个邮政编码之间的距离。一个邮政编码坐标是通用的,但是其他邮政编码存储在我需要获取的数据库中。下面的代码没有计算出通用邮政编码和我输入的邮政编码之间的距离。

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>

1 个答案:

答案 0 :(得分:0)

如上所述,您只需从服务器端的数据库中获取值,并使用您希望的任何服务器端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的值。

E.g。

    const LAT1 = 52.482799;
    const LON1 = -2.000643;

然后就这样调用你的函数......

var distance = getDistanceFromLatLonInKm(52.48463500000000, -1.980759000000000);

要执行PAF查找:

FreeMapTools

Google Maps。只需搜索您的邮政编码,然后从网址中获取纬度/经度。

相关问题