---
# System prepended metadata

title: Laravel use google map place api輸入地址取得經緯度
tags: [PHP, ' Backend', ' Laravel']

---

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

# Laravel use google map place api輸入地址取得經緯度

## 註冊和啟用PLACE API

先到GCP註冊，前三個月免費
到[這裡搜尋PLACE API](https://console.cloud.google.com/marketplace/product/google/places-backend.googleapis.com?q=search&referrer=search&project=master-scope-341701)
![](https://i.imgur.com/YTS0zid.jpg)

找到之後點選啟用
![](https://i.imgur.com/c5PhDcb.jpg)

## 創建金鑰

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

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

## 撰寫程式碼

創建一個service檔案，使用Guzzle來打api

[Guzzle Docs](https://guzzle-cn.readthedocs.io/zh_CN/latest/index.html)

可以按照想要搜尋資料放入`$inputType`，可以查找資料請查看文檔

### 取得經緯度
```php=
<?php

namespace App\Http\Services;

use GuzzleHttp\Client;

class GoogleMapService
{
    protected $client;
    public function __construct()
    {
        $this->client = new Client();   
    }

    // 取得經緯度
    public function getPlaceCoods($address)
    {
        try {
            $input = $address;  // 輸入的地址
            // 搜尋取得名稱，營業時間，評價
            $inputType = "textquery&fields=formatted_address%2Cname%2Crating%2Copening_hours%2Cgeometry";
            $api_key = env("GOOGLE_PLACE_API"); // 將api key放到.env檔案，取出
            $url = "https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=$input&inputtype=$inputType&key=$api_key";

            $response = $this->client->request('GET', $url); // 打api
            $contents = $response->getBody()->getContents();
            $contents = json_decode($contents, TRUE); // 對json編碼
        } catch (\Throwable $th) {
            report($th);
            return $url;
        }
        
        // 判斷此地址有沒有經緯度或錯誤
        if (isset($contents['candidates'][0])) {
            return response()->json($contents['candidates'][0]['geometry']['location']);
        } else {
            return false;
        }
    }
}
?>
```

### 取得評論

評論官方表示只能取到五則

```php=
public function get_reviews($place_id)
{
    try {
        $api_key = env("GOOGLE_PLACE_API");
        $fields = 'name%2Crating%2Cformatted_phone_number%2Creviews%2Cuser_ratings_total';
        $language = 'zh-TW';
        $url = "https://maps.googleapis.com/maps/api/place/details/json?fields=$fields&place_id=$place_id&key=$api_key&language=$language";

        $response = $this->client->request('GET', $url);
        $contents = $response->getBody()->getContents();
        $contents = json_decode($contents, TRUE);
        // return $contents;
        if ($contents['status'] == 'OK') {
            $data['reviews'] = $contents['result']['reviews'];
            $data['rating'] = $contents['result']['rating'];
            $data['rating_count'] = $contents['result']['user_ratings_total'];
            return $data;
        } else {
            return false;
        }
    } catch (\Throwable $th) {
        report($th);
        return $url;
    }
}
```

[google place api docs](https://developers.google.com/maps/documentation/places/web-service/search-find-place#maps_http_places_findplacefromtext_mca-txt)