【问题标题】:How to get user location in react-native如何在 react-native 中获取用户位置
【发布时间】:2021-04-09 22:43:33
【问题描述】:

我想显示用户当前位置。我能够获得用户的纬度和经度。然后我使用react-native-geocoding 来获取用户位置地名。但是我在执行此操作时遇到错误。

下面是我的代码:

const getCity = () => {
    console.log("get city func");
    Geocoder.init("MY_API_KEY");
    Geocoder.from(28.6139, 77.2090).then(json => {
        var addressComponent = json.results[0].address_components[0];
        console.log(addressComponent);
    })
        .catch(error => console.warn(error));
}

<TouchableOpacity onPress={getCity}>
    <Text style={styles.title}>Location Screen</Text>
</TouchableOpacity>

我收到错误:

code: 4, message: "Error from the server while geocoding. The receive…s 'origin' field. Check it for more informations.", origin: {…}}
code: 4
message: "Error from the server while geocoding. The received datas are in the error's 'origin' field. Check it for more informations."
origin:
error_message: "This API project is not authorized to use this API."
results: []
status: "REQUEST_DENIED"
__proto__: Object
__proto__: Object

我不知道我在这里做错了什么。另外,如果还有其他方法可以获取用户的位置名称,请提出建议。

【问题讨论】:

    标签: react-native geolocation react-native-android react-native-ios reverse-geocoding


    【解决方案1】:

    看起来像授权问题,与无效密钥有关。尝试在文件或应用程序的根级别调用Geocoder.init(API_KEY),而不是在函数定义本身中。

    Geocoder.init("MY_API_KEY");
    
    const getCity = () => {
      console.log("get city func");
      Geocoder.from(28.6139, 77.2090).then(json => {
        var addressComponent = json.results[0].address_components[0];
        console.log(addressComponent);
      })
        .catch(error => console.warn(error));
    }
    
    <TouchableOpacity onPress={getCity}>
      <Text style={styles.title}>Location Screen</Text>
    </TouchableOpacity>
    

    【讨论】: