Home > Back-end >  How to get current location coordinates outside
How to get current location coordinates outside

Time:01-18

Firstly, I am very new at react native, therefore probably the question is basic. I am trying to get coordinates outside the getCurrentPosition function. I can get the console log of the details with below line:

Geolocation.getCurrentPosition(info => console.log(info));

The output is like that:

{"coords": {"accuracy": 20, "altitude": 0, "heading": 0, "latitude": 36.854074999999995, "longitude": 30.593996666666666, "speed": 0}, "mocked": false, "timestamp": 1642440006000}

But I couldn't find a way to take them outside. I want to use the result of this inside my functional component:

const Home = (props) => {
   return (
   <Text>Latitude is {latitude}</Text>
   <Text>Longitude is {longitude}</Text>
   )
}
export default Home

Can you help?

CodePudding user response:

You can use a useState() hook to achieve this. https://en.reactjs.org/docs/hooks-state.html

CodePudding user response:

You can try by setting the value to a state assuming you are using react hooks

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

Geolocation.getCurrentPosition(info => setLocation(info));

then

console.log(location.coords.latitude) //gives latitude
console.log(location.coords.longitude) //gives longitude
  •  Tags:  
  • Related