有什么方法可以使用 React 从 googleplacesautocomplete api 上的用户输入中仅获取城市和国家/地区?

Is there any way to fetch only city and country from user input on googleplacesautocomplete api using react?

我无法使用 react 从 googleautocomplete 组件输出城市和国家。

执行此操作的方法是在 Google Places Autocomplete 组件上指定 types 参数。但是,限制是您只能真正指定类型的选项之一:

You may restrict results from a Place Autocomplete request to be of a certain type by passing a types parameter. The parameter specifies a type or a type collection, as listed in the supported types below. If nothing is specified, all types are returned. In general only a single type is allowed. The exception is that you can safely mix the geocode and establishment types, but note that this will have the same effect as specifying no types.

来源:https://developers.google.com/places/web-service/autocomplete#place_types

因此,针对您的情况,最好的选择可能是使用 (regions) 类型集合,但这不仅仅包括城市和国家/地区,例如社区。另一种选择是使用 (cities) 类型集合,它只包含城市。

如果你想要一些预制的东西来完成这个,我也强烈推荐 react-geosuggest 库,因为你可以将它们作为参数传递并自己设置样式。

<Geosuggest
  types={['(regions)']}
/>

编辑

我想我可能有点误解了这个问题。如果您想弄清楚如何从您从地点 API 获得的响应中获取街道地址、城市和国家/地区,您将不得不提交额外的请求。

用户从列表中选择地点后,您必须从原始请求中获取 place_id 并提交 Place Details request. One of the fields in the response will be address_component which has this very strange format. I posted an example of what this full format looks like here

我制作了一个简单的转换器函数,它将return地址的基本组成部分以易于管理的格式显示:

// ---------------------------------------------------------------------- //
// https://developers.google.com/maps/documentation/geocoding/intro#Types //
// ---------------------------------------------------------------------- //

// returns:

// {
//   address_1
//   address_2
//   city
//   state_code
//   zip_code
//   country
// }

function convertAddressComponents(addrComp) {
  let newAddr = {};
  let address_1 = [];
  addrComp.forEach((el, i) => {
    if (el.types.includes("post_box")) {
      address_1.push(el.long_name);
    } else if (el.types.includes("street_number")) {
      address_1.push(el.long_name);
    } else if (el.types.includes("route")) {
      address_1.push(el.long_name);
    } else if (el.types.includes("subpremise")) {
      newAddr.address_2 = el.long_name;
    } else if (el.types.includes("locality")) {
      newAddr.city = el.long_name;
    } else if (el.types.includes("administrative_area_level_1")) {
      newAddr.state_code = el.short_name;
    } else if (el.types.includes("postal_code")) {
      newAddr.zip_code = el.short_name;
    } else if (el.types.includes("country")) {
      newAddr.country = el.long_name;
    }
  });
  newAddr.address_1 = address_1.join(" ");

  return newAddr;
}

请随意修改它以满足您的需要。