在Google Maps自动完成地址API中,要根据国家和城市过滤地址,您需要在请求URL中设置components
参数,该参数可以限制自动完成建议的地理范围。以下是如何设置components
参数以根据国家和城市过滤地址的示例:
components
参数为您想要过滤的国家和城市的ISO代码。例如,如果您想要过滤美国的洛杉矶地址,可以构建以下URL:https://maps.googleapis.com/maps/api/place/autocomplete/json?input=您要搜索的地址&components=country:US|locality:Los+Angeles&key=YOUR_API_KEY
请将YOUR_API_KEY
替换为您的API密钥,并将您要搜索的地址
替换为您想要搜索的实际地址。
以下是一个使用JavaScript发送请求并处理响应的示例:
const axios = require('axios');
const apiKey = 'YOUR_API_KEY';
const input = '1600 Amphitheatre Parkway'; // 您要搜索的地址
const country = 'US';
const locality = 'Los Angeles';
axios.get(`https://maps.googleapis.com/maps/api/place/autocomplete/json?input=${encodeURIComponent(input)}&components=country:${country}|locality:${encodeURIComponent(locality)}&key=${apiKey}`)
.then(response => {
console.log(response.data.predictions);
})
.catch(error => {
console.error(error);
});
请确保将YOUR_API_KEY
替换为您的API密钥。
领取专属 10元无门槛券
手把手带您无忧上云