【问题标题】:navigator.geolocation.getCurrentPosition() is not getting a response from googleapinavigator.geolocation.getCurrentPosition() 没有从 googleapi 得到响应
【发布时间】:2019-05-03 18:07:24
【问题描述】:

我正在使用 react 在 localhost:3000 上获取地理位置。我看到另一个人在他们的本地主机上获取了地理位置坐标,但即使在 Chrome 上启用了允许位置访问,我也无法这样做。

我尝试在 react 中同时使用钩子和类语法。我启用了允许访问。我最终使用了一个 ip 地址 api 来获得一个大致位置,但是由于地理定位应该可以工作(至少这是我被告知的),我至少希望看到它工作,所以我可以使用 https 来实现它未来。错误日志甚至没有被触发,而前三个日志在组件安装时被触发。这是我尝试过的代码,我已经尽可能简单了:


const App = props => {

  useEffect(() => {
    console.log('hello')
    console.log(navigator)
    console.log(navigator.geolocation)
    if ("geolocation" in navigator) {
      navigator.geolocation.getCurrentPosition((position) => {
        console.log(position)
      }, (error) => {
       console.log(error)
      })
    } else {
      console.log('error')
    }
  }, [])
  return (
      <div>
        <h3>Please Login.</h3>
      </div>
    )
}

export default App

我希望收到来自 googleapi 的回复。

编辑:

我添加了错误回调并打印出来:

消息:“'https://www.googleapis.com/' 的网络位置提供商:未收到响应。”

【问题讨论】:

    标签: reactjs navigator w3c-geolocation


    【解决方案1】:

    添加可选的错误回调来处理错误(如果用户拒绝位置权限)

    navigator.geolocation.getCurrentPosition(success[, error[, [options]])
    

    你只检查它是否在导航器中!!!

    如果用户拒绝位置权限,则错误回调将处理它...

    可能的选项是(参考来自 mdn)

    {
      enableHighAccuracy: true, 
      maximumAge        : 30000, 
      timeout           : 27000
    }
    

    【讨论】:

    • 它不需要两个参数,它们是可选参数。 (success[, error[, [options]])
    • 是的,但如果用户拒绝位置权限,第二个参数就是要处理的那个
    • 不说它需要两个参数,只是说添加可选的错误回调来处理错误。
    • 已编辑.. 无论如何,您将在每次状态更改时获取位置!只是指向那里
    • 编辑后的代码,它抛出了以下错误并删除了 url:消息:“'google api url'的网络位置提供程序:未收到响应。”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 2016-12-14
    相关资源
    最近更新 更多