JavaScript、PHP,兩經緯度坐標計算

JavaScript、PHP,兩經緯度坐標計算

JavaScript

function distance(lat1,lon1,lat2,lon2) {
 var R = 6371; // km (change this constant to get miles)
 var dLat = (lat2-lat1) * Math.PI / 180;
 var dLon = (lon2-lon1) * Math.PI / 180;
 var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
  Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) *
  Math.sin(dLon/2) * Math.sin(dLon/2);
 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
 var d = R * c;
 if (d>1) return Math.round(d)+"km";
 else if (d<=1) return Math.round(d*1000)+"m";
 return d;
}

http://maxtellyou.blogspot.tw/2012/09/calculate-distance-between-two-points.html

PHP

<?php
/**
*求两个已知经纬度之间的距离,单位为米
*@param lng1,lng2 经度
*@param lat1,lat2 纬度
*@return float 距离,单位米
*@author www.phpernote.com
**/
function getdistance($lng1,$lat1,$lng2,$lat2){
	//将角度转为狐度
	$radLat1=deg2rad($lat1);//deg2rad()函数将角度转换为弧度
	$radLat2=deg2rad($lat2);
	$radLng1=deg2rad($lng1);
	$radLng2=deg2rad($lng2);
	$a=$radLat1-$radLat2;
	$b=$radLng1-$radLng2;
	$s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137*1000;
	return $s;
}

http://www.phpernote.com/php-function/890.html