获取用户的位置和其权限在React Native中使用Expo。

huangapple go评论59阅读模式
英文:

Retrieve user's location and it's permission in React native via expo

问题

晚上好,我是React Native的新手,我遇到了一个问题,需要一点帮助。我只在Android平台上使用,并在我的物理设备(Android手机)上呈现输出。所以我有一个注册页面,其中包含一些输入字段,其中之一是带有右侧可点击图标的地址输入字段。当单击它时,会弹出提示,询问用户是否开启手机的定位功能。

我的问题是现在。由于我有一个登录屏幕上有可点击的“注册”文本。当我点击它时,它将重定向到注册页面,但提示将直接弹出。 获取用户的位置和其权限在React Native中使用Expo。

而我的期望输出是,在登录屏幕上点击“注册”文本后,提示不会显示,它将在点击地址输入字段内的可点击图标后显示。 获取用户的位置和其权限在React Native中使用Expo。

以下是我所做的。
//这是我的UI

<View style={styles.container}>
  <View>
    <MaterialCommunityIcons
      name='map-marker-radius'
      size={23}
      color="black"
      style={styles.phoneNumberIcon} />
    {address &&
     <TextInput
      placeholder='Address'
     
      placeholderTextColor='black'
      keyboardType='default'
      editable={false}>{address}</TextInput>
     
    }

    <TouchableOpacity style={globalStyles.btnClickEye} >
      {/* onPress={() => getPermisions()} */}
      <FontAwesome
        name='map-pin'
        size={22}
        color="black"
      />
    </TouchableOpacity>

  </View>

  
  {/* 请忽略这段代码,我只是测试一下我是否能定位 */}
  <View style={{  justifyContent: 'center', alignItems: 'center',marginTop:100}}>
    {location && (
      <Text>
        Latitude: {location.coords.latitude}, Longitude:{' '}
        {location.coords.longitude}
      </Text>
    )}
    {address && <Text>{address}</Text>}
   <Text>测试</Text>
  </View>

</View>

//这是我的函数

const [location, setLocation] = useState(null);
const [address, setAddress] = useState(null);
const [addresstext, setAddresstext] = useState('');
useEffect(() => {
  (async () => {
    let { status } = await Location.requestForegroundPermissionsAsync();
    if (status !== 'granted') {
      console.log('Permission to access location was denied');
      return;
    }

    let location = await Location.getCurrentPositionAsync({});
    setLocation(location);
    console.log(location);
    let address = await reverseGeocodeAsync({
      latitude: location.coords.latitude,
      longitude: location.coords.longitude,
    });
    setAddress(address[0].street+', '+ address[0].city);
  })();
}, []);

在此提前感谢您的帮助。

英文:

Good evening, I'm a newbie to React native and I have this problem and Im seeking for little help.
Im using only Android platform, and I render my output in my physical device(android).
So I have register page with some input field, one of them is the Address Input field with a Touchable Icon in the right. That when clicked a prompt will open asking user to on the phone's location.

My problem is right now is. Since I have a login screen with touchable "register" text in it. When I tap that, it will redirect to Register page but the prompt will popup directly.获取用户的位置和其权限在React Native中使用Expo。

While my expected output is, after tapping the "register" text in Login screen, the prompt will not show, it will show If I will click the touchable icon inside the Address input field. 获取用户的位置和其权限在React Native中使用Expo。

So this is what I've done.
//in this is my UI

 &lt;View style={styles.container}&gt;
      &lt;View&gt;
        &lt;MaterialCommunityIcons
          name=&#39;map-marker-radius&#39;
          size={23}
          color=&quot;black&quot;
          style={styles.phoneNumberIcon} /&gt;
        {address &amp;&amp; 
         &lt;TextInput
          placeholder=&#39;Address&#39;
         
          placeholderTextColor=&#39;black&#39;
          keyboardType=&#39;default&#39;
          editable={false} &gt;{address}&lt;/TextInput&gt;
         
        }
       

        &lt;TouchableOpacity style={globalStyles.btnClickEye} &gt;
          {/* onPress={(()=&gt; getPermisions())} */}
          &lt;FontAwesome
            name=&#39;map-pin&#39;
            size={22}
            color=&quot;black&quot;
          /&gt;
        &lt;/TouchableOpacity&gt;

      &lt;/View&gt;

      
      {/* just disregard this code, I just testing it if I locate */}
      &lt;View style={{  justifyContent: &#39;center&#39;, alignItems: &#39;center&#39; ,marginTop:100}}&gt;
        {location &amp;&amp; (
          &lt;Text&gt;
            Latitude: {location.coords.latitude}, Longitude:{&#39; &#39;}
            {location.coords.longitude}
          &lt;/Text&gt;
        )}
        {address &amp;&amp; &lt;Text&gt;{address}&lt;/Text&gt;}
       &lt;Text&gt; testing /Text&gt;
      &lt;/View&gt;

    &lt;/View&gt;

//this is my function

 const [location, setLocation] = useState(null);
  const [address, setAddress] = useState(null);
  const [addresstext, setAddresstext] = useState(&#39;&#39;);
  useEffect(() =&gt; {
    (async () =&gt; {
      let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== &#39;granted&#39;) {
        console.log(&#39;Permission to access location was denied&#39;);
        return;
      }

      let location = await Location.getCurrentPositionAsync({});
      setLocation(location);
      console.log(location);
      let address = await reverseGeocodeAsync({
        latitude: location.coords.latitude,
        longitude: location.coords.longitude,
      });
     setAddress(address[0].street+&#39;, &#39;+ address[0].city);
     
    })();
  }, []);

Thank you in advance friend.

答案1

得分: 1

如果我正确阅读了你的代码,你在useEffect钩子中请求了位置权限,该钩子在屏幕挂载时运行。

如果你将位置权限的请求从钩子中移至一个单独的函数中,然后在需要时调用该函数(就像你在Btn组件中调用getPermissions一样),那么它应该可以工作:

const getPermission = async() => {
  let { status } = await Location.requestForegroundPermissionsAsync();
  if (status !== 'granted') {
    console.log('Permission to access location was denied');
    return;
  }

  let location = await Location.getCurrentPositionAsync({});
  setLocation(location);
  console.log(location);
  let address = await reverseGeocodeAsync({
    latitude: location.coords.latitude,
    longitude: location.coords.longitude,
  });
  setAddress(address[0].street + ', ' + address[0].city);
}
英文:

If I read your code correctly you have the asking of the location permission in useEffect hook which is run on when the screen mounts.

If you move the asking of the location permission from hook to a separate function that is called (as you call getPermissions in Btn) it should work:

const getPermission = async() =&gt; {
  let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== &#39;granted&#39;) {
        console.log(&#39;Permission to access location was denied&#39;);
        return;
      }

  let location = await Location.getCurrentPositionAsync({});
  setLocation(location);
  console.log(location);
  let address = await reverseGeocodeAsync({
    latitude: location.coords.latitude,
    longitude: location.coords.longitude,
  });
 setAddress(address[0].street+&#39;, &#39;+ address[0].city);
}

huangapple
  • 本文由 发表于 2023年2月23日 22:27:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75546155.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定