我想在我的应用程序中放置一个按钮,按下该按钮时会返回手机的当前地址。
我能够正确返回的纬度和经度,并将这些数据转换为我得到的 react-native-geocoder 库的地址。
我当前的代码如下所示:
import React, { Component } from 'react';
import { View, Text, Button } from 'react-native';
import Geocoder from 'react-native-geocoder';
// 0.4.8
class GeolocationExample extends Component {
constructor(props) {
super(props);
this.state = {
latitude: null,
longitude: null,
error: null,
};
}
refresh = () => {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
};
render() {
Geocoder.geocodePosition(this.state.latitude,this.state.longitude)
return (
<View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Latitude: {this.state.latitude}</Text>
<Text>Longitude: {this.state.longitude}</Text>
{this.state.error ? <Text>Error: {this.state.error}</Text> : null}
<Button
style={{ marginTop: 30 }}
onPress={() => { this.refresh(); }}
title="Refresh"
/>
</View>
);
}
}
export default GeolocationExample;
根据我在 Geocoder.geocodePosition(this.state.latitude,this.state.longitude)
中的理解,将返回地址,但我不明白如何从那里获取这些数据。
Snack 中的代码: https ://snack.expo.io/rJhYwaG2Z
原文由 Magas 发布,翻译遵循 CC BY-SA 4.0 许可协议
您不需要从 LatLon 进行反向地理编码的库,您可以直接调用 Google Maps API,例如:
(记得提供您的 Google Maps API 密钥!!)
结果对象将具有该 LatLon 的所有地址组件。
示例结果