---
# System prepended metadata

title: Laravel google api反向地址查找
tags: [PHP, ' Backend', ' Laravel']

---

---
tags: PHP, Laravel, Backend
---

# Laravel google api反向地址查找

## 註冊以及啟用Geocoding API

先到GCP註冊，前三個月免費，然後申請api

### 創建金鑰

點選API和服務->點選憑證->建立憑證->API金鑰
![](https://i.imgur.com/2RgNHXQ.jpg)
這樣子就建立成功囉

點選限制金鑰，可以將它選擇只用來使用Geocoding API
![](https://i.imgur.com/jp6Oz2t.jpg)


### 啟用服務

到[Geocoding API](https://console.cloud.google.com/marketplace/product/google/geocoding-backend.googleapis.com?q=search&referrer=search&project=master-scope-341701)點擊啟用

![](https://i.imgur.com/KcuAFX1.jpg)

## 撰寫程式碼

### env

修改`.env`檔案，加上以下程式碼
`GOOGLE_API=YOUR_API_KEY`

### 利用經緯度取得地址

`Geocoding API`有以下參數可選

* language — 返回結果的語言
* location_type — 一種或多種位置類型的過濾器
* result_type — 一種或多種地址類型的過濾器

必填參數為

* latlng — 填入 經度,緯度 中間不能有空格 
* key — 你的google api key

以下範例`result_type`選用`street_address`表示返回準確的街道地址。

接下來我們使用 [Guzzle HTTP client](https://docs.guzzlephp.org/en/stable/)對`GOOGLE API`發出請求，而`Illuminate\Http\Client\Response`類實現了 `PHPArrayAccess`接口，所以可以直接訪問 `JSON` 響應數據。

```php=
use Illuminate\Support\Facades\Http;

public function get_address($lat, $lng)
{
    try {
        $language = 'zh-TW';
        $result_type = 'street_address';
        $api_key = env("GOOGLE_API");
        $url = "https://maps.googleapis.com/maps/api/geocode/json";
        $response = Http::get($url, [
            'latlng' => "$lat,$lng",
            'key' => $api_key,
            'language' => $language,
            'result_type' => $result_type,
        ]);
        if ($response->ok()) {
            $contents = $response->json();
            if ($contents['status'] == 'OK') {
                $data['name'] = $contents['results'][0]['formatted_address'];
                return $data;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } catch (\Throwable $th) {
        report($th);
        return $url;
    }
}
```

### Response

以台南火車站經緯度為例返回資料

```json=
{
    "plus_code": {
        "compound_code": "X6W7+R5Q 台灣台南市東區",
        "global_code": "7QJ2X6W7+R5Q"
    },
    "results": [
        {
            "address_components": [
                {
                    "long_name": "4",
                    "short_name": "4",
                    "types": [
                        "street_number"
                    ]
                },
                {
                    "long_name": "北門路二段",
                    "short_name": "北門路二段",
                    "types": [
                        "route"
                    ]
                },
                {
                    "long_name": "成大里",
                    "short_name": "成大里",
                    "types": [
                        "administrative_area_level_4",
                        "political"
                    ]
                },
                {
                    "long_name": "東區",
                    "short_name": "東區",
                    "types": [
                        "administrative_area_level_3",
                        "political"
                    ]
                },
                {
                    "long_name": "台南市",
                    "short_name": "台南市",
                    "types": [
                        "administrative_area_level_1",
                        "political"
                    ]
                },
                {
                    "long_name": "台灣",
                    "short_name": "TW",
                    "types": [
                        "country",
                        "political"
                    ]
                },
                {
                    "long_name": "701",
                    "short_name": "701",
                    "types": [
                        "postal_code"
                    ]
                }
            ],
            "formatted_address": "701台灣台南市東區北門路二段4號",
            "geometry": {
                "location": {
                    "lat": 22.9971305,
                    "lng": 120.2129885
                },
                "location_type": "ROOFTOP",
                "viewport": {
                    "northeast": {
                        "lat": 22.9984794802915,
                        "lng": 120.2143374802915
                    },
                    "southwest": {
                        "lat": 22.99578151970849,
                        "lng": 120.2116395197085
                    }
                }
            },
            "place_id": "ChIJs1S-8Ix2bjQRAJqtZowd7UQ",
            "plus_code": {
                "compound_code": "X6W7+V5 台灣台南市東區",
                "global_code": "7QJ2X6W7+V5"
            },
            "types": [
                "street_address"
            ]
        }
    ],
    "status": "OK"
}
```