Pārlūkot izejas kodu

修改高德获取经纬度的方法

dongxiaoqin 11 mēneši atpakaļ
vecāks
revīzija
2b59cb8269
1 mainītis faili ar 22 papildinājumiem un 9 dzēšanām
  1. 22 9
      app/common.php

+ 22 - 9
app/common.php

@@ -100,22 +100,35 @@ function get_address_lat_lng($address) {
     // 高德地图 API 密钥,需替换为你自己的密钥
     $apiKey = 'eff1cbbaf5dd3c1cdcad2c1ed97b85e5';
 
-    // 构建 API 请求 URL
-    $apiUrl = 'https://restapi.amap.com/v3/geocode/geo?';
+    // // 构建 API 请求 URL(地理编码接口:通过地址获取经纬度,目前是经常出错)
+    // $apiUrl = 'https://restapi.amap.com/v3/geocode/geo?';
+    // $params = [
+    //     'address' => $address,
+    //     'key' => $apiKey
+    // ];
+
+    // 构建 API 请求 URL(关键字搜索接口)
+    $apiUrl = 'https://restapi.amap.com/v3/place/text?';
     $params = [
-        'address' => $address,
-        'key' => $apiKey
+        'keywords' => $address,
+        'key' => $apiKey,
+        'offset' => 2, 
+        'page' => 1, // 页码,从1开始
     ];
+
     $requestUrl = $apiUrl . http_build_query($params);
     $data = http_request($requestUrl, [], []);
     // 检查 API 调用是否成功
-    if ($data['status'] === '1' && $data['count'] > 0) {
+    if ($data['status'] === '1' && $data['count'] > 0 && !empty($data['pois'])) {
         // 获取经纬度
-        $location = $data['geocodes'][0]['location'];
-        list($lon, $lat) = explode(',', $location);
+        // $location = $data['geocodes'][0]['location'];
+        // list($lon, $lat) = explode(',', $location);
+
+        $pois = current($data['pois']);
+        $location = explode(",",$pois['location']);
         return [
-            'lon' => $lon,
-            'lat' => $lat
+            'lon' => $location[0],
+            'lat' => $location[1],
         ];
     } else {
         return [];