错误处理 Google 放置 Api。如果api键被限制输入变为空白

Error handling Google Place Api. If the api key is restricted input becomes blank

我已将 Google 地址自动完成功能添加到我的 Reactjs 应用中。 它工作正常,但我意识到,例如,如果我限制我的 API 键,输入将变为灰色,并且根本无法添加任何输入。 如果没有该输入,该应用程序将根本无法运行,因此我正在寻找一种条件来检查 api 键是否正常工作,但到目前为止我找不到任何东西。

const googleUrl = `https://maps.googleapis.com/maps/api/js?key=${process.env.REACT_APP_GOOGLE_API_KEY}&libraries=places`;

 {googleUrl && <Script url={googleUrl} onLoad={handleScriptLoad} />}
            <input
              type="text"
              name="where"
              placeholder="Where do you want to eat?"
              value={where}
              onChange={handleChange}
              id="autocomplete"
            />

完整代码 https://github.com/mugg84/RestaurantFinder.git 在 DisplaySearchBar.js 你可以找到上面提到的输入。

感谢您的帮助!

如果您想收听身份验证失败,您需要使用 gm_authFailure()。 它的文档位于本页底部: https://developers.google.com/maps/documentation/javascript/events

在我的组件中我添加了这行并且输入不再被禁用

  // If google API authentication problem
  window.gm_authFailure = () => {
    document.getElementById('autocomplete').disabled = false;
    document.getElementById('autocomplete').placeholder =
      'Where do you want to eat?';
    document.getElementById('autocomplete').style.backgroundImage = '';
    document.getElementById('autocomplete').style.paddingLeft = '1rem';
  };