首页 > 解决方案 > Location.requestForegroundPermissionsAsync 不是函数

问题描述

我只是尝试使用 expo-location,发现错误 Location.requestForegroundPermissionsAsync is not a function

这是我的代码

import * as Location from 'expo-location';

const setCurrentLocation = async() => {
        let { status } = await Location.requestForegroundPermissionsAsync();
        if (status !== 'granted') {
            setErrorMsg('Permission to access location was denied');
            return;
          }
          let location = await Location.getCurrentPositionAsync({});
          setLocation(location);
            if (errorMsg) {
                setCheckText(errorMsg)
            } else if (location) {
                setCheckText(JSON.stringify(location))
            }  
    }

标签: google-mapslocationexpojmapviewer

解决方案


要显示坐标 -

state像这样初始化你

  const [location, setLocation] = React.useState(null);

让你的setCurrentLocation功能像这样

  const setCurrentLocation = async () => {
    let { status } = await Location.requestForegroundPermissionsAsync();
    if (status !== 'granted') {
      setErrorMsg('Permission to access location was denied');
      return;
    }
    let location = await Location.getCurrentPositionAsync({});
    setLocation(location);
  }; 

然后你的return部分看起来像这样

return (
    <View style={styles.container}>
      {location ? <Text>latitude = {location.coords.latitude}</Text> : null}
      {location ? <Text>longitude = {location.coords.longitude}</Text> : null}
    </View>
  );

工作示例


推荐阅读