Files
2025-07-27 12:22:34 +08:00

80 lines
2.2 KiB
PHP

<?php
defined('BASEPATH') or exit('No direct script access allowed');
class TcGeocoder
{
private $apiKey = 'EMKBZ-WEZCQ-SG25I-GKL2T-NJD27-MNFPC';
private $apiUrl = 'https://apis.map.qq.com/ws/geocoder/v1/';
public function __construct($apiKey = '')
{
if (!empty($apiKey)) {
$this->apiKey = $apiKey;
}
}
/**
* 经纬度逆解析(坐标转地址)
* @param float $latitude 纬度
* @param float $longitude 经度
* @param int $getPoi 是否返回周边POI信息,0-不返回,1-返回
* @return array|bool 返回解析结果数组或false(失败时)
*/
public function reverseGeocode($latitude, $longitude, $getPoi = 0)
{
// 构建请求参数
$params = [
'location' => "{$latitude},{$longitude}",
'key' => $this->apiKey,
'get_poi' => $getPoi,
'output' => 'json'
];
// 发送请求
$response = $this->sendRequest($params);
// 处理响应
if ($response) {
$result = json_decode($response, true);
if ($result && isset($result['status']) && $result['status'] === 0) {
return $result['result'];
} else {
error_log("逆地址解析失败: " . json_encode($result));
return false;
}
}
return false;
}
/**
* 发送HTTP请求
* @param array $params 请求参数
* @return string|bool 响应内容或false(失败时)
*/
private function sendRequest($params)
{
// 构建URL
$url = $this->apiUrl . '?' . http_build_query($params);
// 初始化cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// 执行请求
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
// 错误处理
if ($error) {
error_log("cURL请求错误: $error");
return false;
}
return $response;
}
}