Google Maps Platform 提供強大的 Geocoding API (地址↔座標轉換) 與 Maps Static API (靜態地圖圖片)。本文示範 PHP 後端串接完整流程:取得 API Key、地址轉經緯度、錯誤處理、靜態地圖圖片嵌入、快取優化與成本控制。
<?php
function geocodeAddress(string $address, string $apiKey): ?array
{
$url = 'https://maps.googleapis.com/maps/api/geocode/json';
$params = [
'address' => $address,
'key' => $apiKey,
'language' => 'zh-TW', // 繁體中文回傳
'region' => 'tw', // 偏向台灣結果
];
$query = http_build_query($params);
$response = @file_get_contents($url . '?' . $query);
if ($response === false) {
error_log("Geocoding request failed: " . error_get_last()['message']);
return null;
}
$data = json_decode($response, true);
if (($data['status'] ?? '') !== 'OK') {
error_log("Geocoding API error: {$data['status']} - {$data['error_message'] ?? ''}");
return null;
}
$result = $data['results'][0];
$location = $result['geometry']['location'];
$formatted = $result['formatted_address'];
return [
'lat' => $location['lat'],
'lng' => $location['lng'],
'formatted_address' => $formatted,
'place_id' => $result['place_id'] ?? null,
'types' => $result['types'] ?? [],
];
}
// 使用範例
$apiKey = 'YOUR_API_KEY';
$address = '台北市信義區市府路1號'; // 台北101
$geo = geocodeAddress($address, $apiKey);
if ($geo) {
echo "地址: {$geo['formatted_address']}
";
echo "座標: {$geo['lat']}, {$geo['lng']}
";
// 輸出: 25.033964, 121.564468
} else {
echo "地址解析失敗";
}
?>
<?php
function buildStaticMapUrl(array $geo, string $apiKey, array $options = []): string
{
$defaults = [
'zoom' => 16,
'size' => '600x400',
'maptype' => 'roadmap', // roadmap, satellite, hybrid, terrain
'markers' => "color:red|label:A|{$geo['lat']},{$geo['lng']}",
'scale' => 2, // 2x 高解析度 (適合 Retina)
'format' => 'png',
];
$opts = array_merge($defaults, $options);
$params = array_merge($opts, ['key' => $apiKey]);
return 'https://maps.googleapis.com/maps/api/staticmap?' . http_build_query($params);
}
// 使用
$mapUrl = buildStaticMapUrl($geo, $apiKey, ['zoom' => 15, 'size' => '800x500']);
echo '<img src="' . htmlspecialchars($mapUrl) . '" alt="地圖" width="800" height="500">';
?>
<?php
// map_page.php
$apiKey = 'YOUR_API_KEY';
$address = $_GET['address'] ?? '台北市信義區市府路1號';
$geo = null;
$mapUrl = '';
$error = '';
if ($address) {
$geo = geocodeAddress($address, $apiKey);
if ($geo) {
$mapUrl = buildStaticMapUrl($geo, $apiKey);
} else {
$error = '無法解析地址,請嘗試更詳細的地址';
}
}
?>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>Google Maps 地址查詢</title>
<style>
.container { max-width: 800px; margin: 2rem auto; padding: 0 1rem; font-family: sans-serif; }
.form-group { display: flex; gap: 8px; margin-bottom: 1rem; flex-wrap: wrap; }
input[type="text"] { flex: 1; min-width: 200px; padding: 8px 12px; font-size: 1rem; }
button { padding: 8px 16px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
button:hover { background: #0056b3; }
.map-img { max-width: 100%; height: auto; border: 1px solid #ddd; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
.error { color: #dc3545; margin: 1rem 0; }
.info { background: #f8f9fa; padding: 1rem; border-radius: 4px; margin-bottom: 1rem; font-size: 0.9rem; }
</style>
</head>
<body>
<div class="container">
<h1>地址查詢地圖</h1>
<form method="get" class="form-group">
<input type="text" name="address" value="= htmlspecialchars($address) ?>" placeholder="輸入地址、地標、店名..." required>
<button type="submit">查詢</button>
</form>
<?php if ($error): ?>
<div class="error"><?= $error ?></div>
<?php elseif ($geo): ?>
<div class="info">
格式化地址:= htmlspecialchars($geo['formatted_address']) ?>
座標:= $geo['lat'] ?>, = $geo['lng'] ?>
Place ID:= $geo['place_id'] ?? 'N/A' ?>
</div>
<img class="map-img" src="= htmlspecialchars($mapUrl) ?>" alt="地圖位置">
<?php endif; ?>
</div>
</body></html>
<?php
function geocodeCached(string $address, string $apiKey, $redis): ?array
{
$cacheKey = 'geocode:' . md5(strtolower(trim($address)));
if ($cached = $redis->get($cacheKey)) {
return json_decode($cached, true);
}
$result = geocodeAddress($address, $apiKey);
if ($result) {
$redis->setex($cacheKey, 30 * 86400, json_encode($result)); // 快取 30 天
}
return $result;
}
Geocoding API 不支援批次,但可自行併發請求 (注意 QPS 限制:50 req/sec/專案):
function geocodeBatch(array $addresses, string $apiKey, int $concurrency = 10): array
{
$results = [];
$chPool = [];
// 使用 curl_multi 並發請求...
return $results;
}
| Status | 原因 | 處理 |
|---|---|---|
| ZERO_RESULTS | 找不到對應地址 | 提示用戶修正地址、嘗試模糊比對 |
| OVER_QUERY_LIMIT | 超過免費額度或 QPS 限制 | 啟用帳單、實作快取、指數退避重試 |
| REQUEST_DENIED | API Key 限制、未啟用 API、帳單問題 | 檢查 Cloud Console 設定 |
| INVALID_REQUEST | 參數缺失 (address/components) | 檢查請求參數建構 |
| UNKNOWN_ERROR | 伺服器端暫時錯誤 | 指數退避重試 (1s, 2s, 4s...) |