allocatr/application/admin/controller/AmapTrait.php
2025-06-11 17:14:31 +08:00

50 lines
1.3 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\admin\controller;;
use fast\Http;
use think\Env;
trait AmapTrait
{
/**
* 高德API Key使用时请赋值或者在类中覆盖此属性
* @var string
*/
protected $amapKey = null;
/**
* 调用高德逆地理编码 获取地址信息
*
* @param string $location 经纬度,格式 "经度,纬度"
* @param bool $returnAll 是否返回全部结果默认false只返回地址字符串
* @return array|string|false 返回数组全部数据或字符串详细地址失败返回false
*/
public function getAddressByKeyword(string $keyword)
{
$this->amapKey = Env::get('amap_key');
$url = 'https://restapi.amap.com/v5/place/text';
$params = [
'key' => $this->amapKey,
'keywords' => $keyword,
'page_size' => 1,
];
try {
$response = Http::get($url, $params);
$data = json_decode($response, true);
// dd($data);
if (isset($data['status']) && $data['status'] == '1') {
return $data['pois']['0'] ?? false;
}
} catch (\Exception $e) {
throw $e;
// 这里可以做日志记录
}
return false;
}
/**
* 还可以封装更多高德API调用方法
*/
}