Laravel 使用 google place api 輸入地址取得經緯度
註冊和啟用 PLACE API
先到 GCP 註冊,前三個月免費
到這裡搜尋 PLACE API
找到之後點選啟用
創建金鑰
點選 API 和服務->點選憑證->建立憑證->API 金鑰
這樣子就建立成功囉
點選限制金鑰,可以將它選擇只用來使用 place api
撰寫程式碼
創建一個 service 檔案,使用 Guzzle 來打 api
Guzzle Docs
可以按照想要搜尋資料放入$inputType
,可以查找資料請查看文檔
取得經緯度
<?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"); $url = "https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=$input&inputtype=$inputType&key=$api_key";
$response = $this->client->request('GET', $url); $contents = $response->getBody()->getContents(); $contents = json_decode($contents, TRUE); } catch (\Throwable $th) { report($th); return $url; }
if (isset($contents['candidates'][0])) { return response()->json($contents['candidates'][0]['geometry']['location']); } else { return false; } } } ?>
|
取得評論
評論只能取到五比資料
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); 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
Laravel 使用 google place api輸入地址取得經緯度