如何使用 expo-location 从用户当前位置检索用户所在的城市?

How can I retrieve the city a user is in from their current position using expo-location?

当用户在我的应用程序屏幕上时,我想从他们的当前位置获取城市。

我已经尝试使用 expo-location 中的 getCurrentPositionAsync 功能,但它不起作用。

这是我正在尝试的代码:

     export default class Ranking extends Component {
      constructor(props) {
        super(props);
        this.state = {
          location: {},
          errorMsg:'',
          },
        };
      }
    
      _getLocationAsync = async () => {
        let { status } = await Permissions.askAsync(Permissions.LOCATION);
        if (status !== "granted") {
          this.setState({
            errorMsg: "Permission to access location was denied"
          });
        }
        let location = await Location.getCurrentPositionAsync({});
        this.setState({ location });
        };
    
      UNSAFE_componentWillMount() {
        this._getLocationAsync();
      }
    
      render() {
        let text = 'Waiting...';
         if (this.state.errorMsg) {
           text = this.state.errorMsg;
         } else if (location) {
           text = JSON.stringify(location);
       }
    
    return (
      <View>
         <Text>{text}</Text>
      </View>
        );
      }
    }

您可以使用 Location.reverseGeocodeAsync(location) 函数获取邮政地址,该地址的 city 字段与您传入的位置相对应。

此函数将位置对象作为参数,该对象具有 latitudelongitude 属性.

https://docs.expo.io/versions/latest/sdk/location/#locationreversegeocodeasynclocation.


通过查看您的示例,您可以将 location.coords 作为参数传递给 Location.reverseGeocodeAsync 并检索城市名称,如下所示:

class Ranking extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      address: null,
      errorMsg: null,
    };
  }

  _getLocationAsync = async () => {
    let { status } = await Permissions.askAsync(Permissions.LOCATION);
    if (status !== 'granted') {
      this.setState({
        errorMsg: 'Permission to access location was denied',
      });
    }
    const location = await Location.getCurrentPositionAsync({});
    const address = await Location.reverseGeocodeAsync(location.coords);
    this.setState({ address });
  };

  componentDidMount() {
    this._getLocationAsync();
  }

  render() {
    let text = 'Waiting...';
    if (this.state.errorMsg) {
      text = this.state.errorMsg;
    } else if (this.state.address) {
      text = this.state.address[0].city;
    }
    return (
      <View>
        <Text>{text}</Text>
      </View>
    );
  }
}

也使用 componentDidMount 而不是 componentWillMountcomponentWillMount 被视为“遗产”。

https://reactjs.org/docs/react-component.html#legacy-lifecycle-methods.