Home > php教程 > php手册 > php利用百度api计算两地距离的代码

php利用百度api计算两地距离的代码

WBOY
Release: 2016-05-26 08:19:50
Original
1176 people have browsed it

两地距离我们通常用到最多的就是调用百度地图的api来实现了,但有时我们并不需要这接口了只需要简单的处理一即可,这时可以利用php来实现,具体如下.

目前在做一个交友项目,需要知道两个用户之间的距离,百度了一下,操作如下,我们最容易获取到用户地理位置的信息就是ip。

我们通过百度api获取用户经纬度,用ip获取经纬度api:

http://developer.baidu.com/map/index.php?title=webapi/ip-api
Copy after login

得到经纬两个用户经纬度之后就可以计算两用户之间的距离了,计算如下:

/**  
* @desc 根据两点间的经纬度计算距离  
* @param float $lat 纬度值  
* @param float $lng 经度值  
*/ 
function getDistance($lat1, $lng1, $lat2, $lng2)  
{
$earthRadius = 6367000; //approximate radius of earth in meters  
$lat1 = ($lat1 * pi() ) / 180;  
$lng1 = ($lng1 * pi() ) / 180;  
$lat2 = ($lat2 * pi() ) / 180;  
$lng2 = ($lng2 * pi() ) / 180;  
$calcLongitude = $lng2 - $lng1;  
$calcLatitude = $lat2 - $lat1;  
$stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);  
$stepTwo = 2 * asin(min(1, sqrt($stepOne)));  
$calculatedDistance = $earthRadius * $stepTwo;  
return round($calculatedDistance);  
}
Copy after login

代码未经测试,测试后再更新本篇文章告知结果.


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template