Home > other >  How to grab just the latitude/longitude expo location
How to grab just the latitude/longitude expo location

Time:01-28

I am using expo location to request the users permission as well as grab their latitude/longitude coordinates. I am struggling to find some insightful examples on the internet which leaves me to their docs here.

Using the example they provide, I am requesting permission and logging a return value that looks like LocationObjectCoords which you can see is rendered after allowing permissions. When looking at the docs, specifically getCurrentPositionAsync; it looks like it returns LocationObject which is just the coordinates and the time they were logged.

How can I return specifically latitude and longitude instead of everything else included in LocationObjectCoords?

Here is my code below as well as a snack example of my code. Run as IOS.

  const [location, setLocation] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);

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

      let location = await Location.getCurrentPositionAsync({});
      setLocation(location);
    })();
  }, []);

  let text = 'Waiting..';
  if (errorMsg) {
    text = errorMsg;
  } else if (location) {
    text = JSON.stringify(location);
  }

  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>{text}</Text>
    </View>
  );
}

CodePudding user response:

Everything is on your location variable, you just need to save your latitude and longitude separately. Check this out, working fine: https://snack.expo.dev/SXAmeusSa

Hope this works for you

  •  Tags:  
  • Related