//先全部转成经纬度,然后计算距离
private function userDistance($list)
{
$user_ip = CommonClass::getRealIp();//获取客户端IP
if ($user_ip != '127.0.0.1') {
$user_ip = CommonClass:: get_lat_and_lng_ByIP($user_ip);
foreach ($list as $k => $v) {
$list[$k]['distance'] = number_format((CommonClass::getDistance($user_ip['lat'], $user_ip['lng'], $v['lat'], $v['lng'])) / 1000, 1);
$list[$k]['distance'] = str_replace(',', '', $list[$k]['distance']);
}
}
return $list;
}
//根据地址获取经纬度
private function address($data)
{
foreach ($data as $k => $v) {
if (empty($v['province_name']) || empty($v['city_name'])) {
$data[$k]['lat'] = '';
$data[$k]['lng'] = '';
} else {
$address = CommonClass:: addresstolatlag($v['province_name'] . $v['city_name'] . $v['area_name'] . $v['address']);
$data[$k]['lat'] = $address['lat'];
$data[$k]['lng'] = $address['lng'];
}
}
return $data;
}
//根据IP获取经纬度
static function get_lat_and_lng_ByIP($ip)
{
if (empty($ip)) {
return 'IP不能为空';
}
$content = file_get_contents("http://api.map.baidu.com/location/ip?ak=y5p0BQ0IeG5IeWdOcyXGMEizLT86jUVK&services=&t=20170717103214&ip={$ip}&coor=bd09ll");
$json = json_decode($content, true);
$lng = $json['content']['point']['x'];//提取经度数据
$lat = $json['content']['point']['y'];//提取纬度数据
$arr = ['lng' => $lng, 'lat' => $lat];
return $arr;
}
//根据地址获取经纬度
static function addresstolatlag($address)
{
$newdata = urlencode($address);
$url = "http://api.map.baidu.com/geocoder/v2/?address={$newdata}&output=json&ak=Ikk6ShdO60DGbRhbOCSm4rpmhWwqoQxi";
$address_data = file_get_contents($url);
$json_data = json_decode($address_data);
$lng = $json_data->result->location->lng;
$lat = $json_data->result->location->lat;
$arr = ['lng' => $lng, 'lat' => $lat];;
return $arr;
}
纯用php计算距离和经纬度,不用集成地图在数据库存经纬度的好处,但是如果提供给app数据,还是要存经纬度
之前发现 同市根据ip定位算距离都为0,但是自从百度api账号升级成开发者账号之后,距离突然出现,估计是百度地图升级或者是开发者账号的特殊权益定位更精确