Places API (New)でエラーが出続ける
ここまでの状況をQiitaへの質問形式でまとめました:
解決したいこと
Google Apps Script (GAS) で住所分析システムを開発しています。求職者の住所から最寄り駅を検索し、通勤時間に基づいて事業所をフィルタリングする機能を実装中です。現在、Google Places API を使用して最寄り駅を検索する際にエラーが発生しています。このエラーの解決方法を教えてください。
発生している問題・エラー
駅が見つかりませんでした: REQUEST_DENIED - This API project is not authorized to use this API.
該当するソースコード
/**
* 最寄り駅を検索する関数
*/
function findNearestStation() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const seekerSheet = ss.getSheetByName('求職者');
if (!seekerSheet) {
SpreadsheetApp.getUi().alert('求職者シートが見つかりません。まず住所を正規化してください。');
return;
}
const apiKey = getApiKey();
if (!apiKey) {
SpreadsheetApp.getUi().alert('Google API キーが設定されていません。設定シートに入力してください。');
return;
}
// 正規化された住所データを取得
const dataRange = seekerSheet.getRange(2, 3, seekerSheet.getLastRow() - 1, 2);
const locations = dataRange.getValues();
// 各住所の最寄り駅を検索
locations.forEach((location, index) => {
const lat = location[0];
const lng = location[1];
if (!lat || !lng) return; // 座標がない行はスキップ
try {
// 最寄りの駅やバス停を検索
const placesUrl = `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${lat},${lng}&radius=2000&type=transit_station&key=${apiKey}&language=ja`;
const response = UrlFetchApp.fetch(placesUrl);
const result = JSON.parse(response.getContentText());
if (result.status === 'OK' && result.results.length > 0) {
// 最も近い駅を取得
const nearestStation = result.results[0];
const stationName = nearestStation.name;
const stationLocation = nearestStation.geometry.location;
// 駅までの距離を計算(メートル単位)
const distance = calculateDistance(lat, lng, stationLocation.lat, stationLocation.lng);
// 最寄り駅情報をシートに書き込む
seekerSheet.getRange(index + 2, 5).setValue(stationName);
seekerSheet.getRange(index + 2, 6).setValue(distance);
} else {
seekerSheet.getRange(index + 2, 5).setValue('駅が見つかりませんでした: ' + result.status);
// エラーメッセージをより詳細に記録
if (result.error_message) {
Logger.log('詳細エラー: ' + result.error_message);
seekerSheet.getRange(index + 2, 5).setValue('駅が見つかりませんでした: ' + result.status + ' - ' + result.error_message);
}
}
} catch (e) {
seekerSheet.getRange(index + 2, 5).setValue('エラー: ' + e.toString());
}
// API制限を考慮して少し待機
Utilities.sleep(200);
});
SpreadsheetApp.getUi().alert('最寄り駅の検索が完了しました。');
}
自分で試したこと
- Google Cloud Platform で「Places API (New)」を有効化しました
- APIキーが正しく設定シートに入力されていることを確認しました
- Geocoding API では正常に住所の正規化ができているため、APIキー自体は機能していると考えられます
- APIキーに設定されている制限を確認しましたが、特に制限は設けていません
- Google Cloud Platform で支払いアカウントが有効であることを確認しました
エラーメッセージを詳細に表示するようコードを修正したところ、「This API project is not authorized to use this API.」というメッセージが表示されました。このことから、プロジェクトがPlaces APIを使用する権限がないことが原因と思われますが、APIは有効化済みのため解決方法がわかりません。