如何在 google 自动完成 api 中仅查找学校成绩?

How to find only school results in google autocomplete api?

我只想搜索 google 自动完成 api 中的学校。我已经尝试过,但它不会仅过滤特定于学校的搜索。我已从下面阅读 url

https://developers.google.com/places/web-service/autocomplete

但是它只有types个过滤结果的参数。

我只能搜索 google 附近的学校,但它需要我发送纬度和经度,但我想搜索所有学校,不管位置如何。

目前,地点 API 自动完成功能不支持按学校、餐厅等类型进行过滤。

Google 问题跟踪器中有一个功能请求,可以按 Places API 搜索中支持的类型过滤自动完成:

https://issuetracker.google.com/issues/35820774

如您所见,该功能请求是在 2011 年提交的。不幸的是,Google 似乎没有为此任务设置高优先级。我建议在功能请求中加注星标以添加您的投票。希望 Google 有一天会实施它。

这就是我发现对我有用的东西。不理想,但聊胜于无

https://maps.googleapis.com/maps/api/place/textsearch/json?key=MY-APP-KEY&query=shaheen%20public&types=school

您可以使用

https://maps.googleapis.com/maps/api/place/textsearch/json?key=MY-APP-KEY&query=shaheen%20public&types=school

在此处详细了解支持的类型。

https://developers.google.com/places/supported_types?csw=1

Google 地点自动完成 API 仍然不支持按类型过滤。我们使用的是一些变通方法。

归结为获取给定输入的自动完成预测,然后过滤结果以仅获取学校。

// types used in filtering autocomplete results
const schoolPlaceTypes = [
  'school',
  'secondary_school',
  'university',
]

// input event handler
// DEBOUNCE THIS
const searchSchool = async (key, query) => {
  const requestUrl = encodeURI(`https://maps.googleapis.com/maps/api/place/autocomplete/json?key=${key}&language=fr&input=${query}`)
  
  try {
    // fetch all predictions for a given input
    const response = await fetch(requestUrl, { method: 'GET' })
    const { predictions } = await response.json()
    // get all predictions that match at least on of the targeted types
    const results = predictions
      .filter(({ types }) => types.some(type => schoolPlaceTypes.includes(type)))
      // OPTIONAL: format filtered places to return only what is needed.
      .map(({ structured_formatting, place_id, types }) => ({
      place_id,
      name: structured_formatting.main_text,
      address: structured_formatting.secondary_text,
      types,
    }))

    return results
  }
  catch(e) {
    console.error(e)
    return []
  }
}