Google Places API 是一项提供地点搜索和详细信息的服务,允许开发者访问 Google 庞大的地点数据库。国家/地区过滤是指限制 API 返回结果仅来自特定国家或地区。
要仅过滤一个国家/地区的 Google Places API 结果,可以通过以下几种方式实现:
components
参数在 API 请求中添加 components
参数,指定国家代码:
const request = {
query: 'restaurants',
fields: ['name', 'geometry'],
components: 'country:us' // 仅返回美国的结果
};
region
参数const request = {
query: 'restaurants',
fields: ['name', 'geometry'],
region: 'us' // 偏向美国的结果
};
结合 location
和 radius
或 bounds
参数:
const request = {
query: 'restaurants',
fields: ['name', 'geometry'],
location: {lat: 37.7749, lng: -122.4194}, // 旧金山坐标
radius: 50000 // 50公里半径
};
问题1:过滤不生效
问题2:结果太少
问题3:API返回错误
const {Client} = require('@googlemaps/google-maps-services-js');
const client = new Client({});
async function searchPlacesInCountry(query, countryCode) {
try {
const response = await client.textSearch({
params: {
query: query,
key: 'YOUR_API_KEY',
components: `country:${countryCode}`
},
timeout: 1000
});
return response.data.results;
} catch (error) {
console.error('Error:', error);
return [];
}
}
// 使用示例:搜索法国的餐厅
searchPlacesInCountry('restaurant', 'fr')
.then(results => console.log(results));
注意:使用前需要安装Google Maps Services JS库 (npm install @googlemaps/google-maps-services-js
) 并替换 YOUR_API_KEY
为有效API密钥。
没有搜到相关的文章