Google地理编码API是一种将地址转换为地理坐标(地理编码)或将地理坐标转换为地址(反向地理编码)的服务。它允许开发者将人类可读的地址转换为机器可读的经纬度坐标,反之亦然。
当您收到REQUEST_DENIED响应时,通常表示您的请求被Google服务器拒绝。这可能有以下几个原因:
确保您的API密钥具有访问地理编码API的权限。可以在API密钥的"应用程序限制"和"API限制"部分进行设置。
确保您的请求URL格式正确。基本地理编码请求格式如下:
https://maps.googleapis.com/maps/api/geocode/json?address=YOUR_ADDRESS&key=YOUR_API_KEY
REQUEST_DENIED响应通常包含更多详细信息,如:
{
"error_message": "This API project is not authorized to use this API.",
"results": [],
"status": "REQUEST_DENIED"
}
仔细阅读error_message以获取更具体的错误信息。
以下是使用Google地理编码API的正确方式示例:
const axios = require('axios');
async function geocodeAddress(address) {
const apiKey = 'YOUR_VALID_API_KEY';
const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(address)}&key=${apiKey}`;
try {
const response = await axios.get(url);
if(response.data.status === 'OK') {
return response.data.results[0].geometry.location;
} else {
console.error('Geocoding failed:', response.data.status, response.data.error_message);
return null;
}
} catch (error) {
console.error('Error during geocoding:', error);
return null;
}
}
// 使用示例
geocodeAddress('1600 Amphitheatre Parkway, Mountain View, CA')
.then(location => console.log('Location:', location));
如果问题持续存在,您可以考虑以下替代方案:
为避免将来出现REQUEST_DENIED错误: