apiKey = $apiKey; $this->secretKey = $secretKey; } /** * 经纬度逆解析(坐标转地址) * @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' ]; // 生成签名 $params['sig'] = $this->generateSignature($params); // 发送请求 $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; } /** * 生成请求签名 * @param array $params 请求参数数组 * @return string 签名结果 */ private function generateSignature($params) { // 对参数进行排序 ksort($params); // 拼接URL参数 $paramStr = ''; foreach ($params as $key => $value) { $paramStr .= "&{$key}={$value}"; } $paramStr = ltrim($paramStr, '&'); // 拼接请求URL和密钥 $stringToSign = "{$this->apiUrl}?{$paramStr}{$this->secretKey}"; // 生成签名 return md5($stringToSign); } /** * 发送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; } }