好用的地址转径纬度
当我们在结算两者之间距离时 地址转径纬度非常头疼
1.根据经纬度取得地址:
请求地址:
http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=30.68093376455154,104.06552381979525&output=json&pois=1&ak=你的ak
在此之前
框架中获取到经纬度的方法
这里我用Laravel 5.8框架举例 Guzzle-http用于发起HTTP请求 Guzzle-http链接: https://guzzle-cn.readthedocs.io/
1、首选在Laravel中安装Guzzle-http插件,安装命令↓↓↓↓↓↓
composer require guzzlehttp/guzzle
使用guzzle来发起GET请求 引入类
use GuzzleHttp\Client;
2、在laravel5.8框架中,在config目录下定义,gaode.php 配置文件,代码如下。
return [
'geocode' => 'http://restapi.amap.com/v3/geocode/geo?key=xxxxxxxxxxxxxxxx&address=%s&city=%s'
];
3、在这里我是才用了添加信息成功后,进行地址转换操作,后修改数据库的经纬度字段中的内容。
经度:longitude 纬度:latitude
public function store(FangRequest $request) {
$dopost = $request->except(['_token', 'file']);
$model = Fang::create($dopost);
$client = new Client(['timeout' => 5]);
$url = config('gaode.geocode');
$url = sprintf($url, $model->fang_addr, $model->fang_province);
$response = $client->get($url);
$body = (string)$response->getBody();
$arr = json_decode($body, true);
if (count($arr['geocodes']) > 0) {
$locationArr = explode(',', $arr['geocodes'][0]['location']);
$model->update([
'longitude' => $locationArr[0],
'latitude' => $locationArr[1]
]);
}
return redirect(route('admin.fang.index'))->with('success','房源信息添加成功');
}
/测量两地距离也送给大家
public static function transition($data)
{
foreach ($data as &$v){
$addr = $v['cnpaddr'];
$url = sprintf(config('gaode.url'),$addr);
$client = new Client(['timeout' => 5,'verify' => false]);
$response = $client->get($url);
$json = (string)$response->getBody();
$v['lng'] = substr(explode('lng":',$json)[1],0,10);
$v['lat'] = substr(explode('lat":',$json)[1],0,10);
}
return $data;
}
public static function distance($data,$lat,$lng)
{
foreach ($data as &$v){
$lng1=$v['lng'];
$lat1=$v['lat'];
$lng2=$lng;
$lat2=$lat;
$EARTH_RADIUS = 6378137;
$RAD = pi() / 180.0;
$radLat1 = $lat1 * $RAD;
$radLat2 = $lat2 * $RAD;
$a = $radLat1 - $radLat2;
$b = ($lng1 - $lng2) * $RAD;
$s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
$s = $s * $EARTH_RADIUS;
$s = round(round($s * 10000) / 10000000,3);
$v['distance']=(int)explode('.',$s)[0];
}
return $data;
}
最后变力一下数组就好,加个例子
public function showCity(){
$pag=input('pag',0);
$pag1=$pag*config('page.pages');
$lng=input('lng');
$lat=input('lat');
$cineplexs = Cineplexs::all();
$data = \Api\Common\Common::transition($cineplexs);
$res = \Api\Common\Common::distance($data,$lat,$lng);
foreach ($res as $k=>$v){
$flight = Cineplexs::find((int)$v['id']);
$flight->sort = $v['distance'];
$flight->save();
}
$movie=Movies::all();
$cineplexs=Cineplexs::listmovie($pag1);
return self::json(1,$pag,[$movie,$cineplexs]);
}
转载: https://blog.csdn.net/qq_38256963/article/details/78731142 https://www.jianshu.com/p/815cc898b4ea
|