萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 串接 Google Maps Geocoding API:地址轉座標與靜態地圖嵌入

Google Maps Platform 提供強大的 Geocoding API (地址↔座標轉換) 與 Maps Static API (靜態地圖圖片)。本文示範 PHP 後端串接完整流程:取得 API Key、地址轉經緯度、錯誤處理、靜態地圖圖片嵌入、快取優化與成本控制。

前置準備

  1. 建立 Google Cloud 專案
  2. 啟用 Geocoding API 與 Maps Static API
  3. 建立 API Key,設定 HTTP Referrer / IP 限制
  4. 啟用帳單 (免費額度:Geocoding $200/月 ≈ 40,000 次請求)

步驟一:地址轉經緯度 (Geocoding)

<?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 "地址解析失敗"; } ?>

步驟二:嵌入靜態地圖圖片 (Static Maps)

<?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="" placeholder="輸入地址、地標、店名..." required>
            <button type="submit">查詢</button>
        </form>

        <?php if ($error): ?>
            <div class="error"><?= $error ?></div>
        <?php elseif ($geo): ?>
            <div class="info">
                格式化地址:
座標:,
Place ID: </div> <img class="map-img" src="" alt="地圖位置"> <?php endif; ?> </div> </body></html>

進階優化與成本控制

1. 結果快取 (Redis/Memcached/檔案)

<?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;
}

2. 批次地理編碼 (Batch Geocoding)

Geocoding API 不支援批次,但可自行併發請求 (注意 QPS 限制:50 req/sec/專案):

function geocodeBatch(array $addresses, string $apiKey, int $concurrency = 10): array
{
    $results = [];
    $chPool = [];
    // 使用 curl_multi 並發請求...
    return $results;
}

3. 成本監控

  • 在 Google Cloud Console 設定預算告警
  • 記錄每日 API 呼叫次數,寫入資料庫/日誌
  • 實作客戶端快取:相同地址 30 天內不重複請求

常見錯誤代碼對照

Status原因處理
ZERO_RESULTS找不到對應地址提示用戶修正地址、嘗試模糊比對
OVER_QUERY_LIMIT超過免費額度或 QPS 限制啟用帳單、實作快取、指數退避重試
REQUEST_DENIEDAPI Key 限制、未啟用 API、帳單問題檢查 Cloud Console 設定
INVALID_REQUEST參數缺失 (address/components)檢查請求參數建構
UNKNOWN_ERROR伺服器端暫時錯誤指數退避重試 (1s, 2s, 4s...)
copyright © 萬盛學電腦網 all rights reserved