先到 GCP 註冊,前三個月免費 到這裡搜尋 PLACE API
找到之後點選啟用
點選 API 和服務->點選憑證->建立憑證->API 金鑰 這樣子就建立成功囉
點選限制金鑰,可以將它選擇只用來使用 place api
創建一個 service 檔案,使用 Guzzle 來打 api
<?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;
}
}
}
?>