Stack Overflow Asked by scriobh on January 5, 2022
I’m a newbie to React. Trying to get location coordinates in a page and want to display the latitude and longitude but not sure how to get the value from getCurrentPostion
function which is being called in useEffect
hook here. Could anyone please help?
Here’s a gist of my code.
const getCurrentPosition = async () => {
const {
coords: { latitude, longitude },
} = await Geolocation.getCurrentPosition();
return { latitude, longitude };
};
const TestComponent = () => {
useEffect(() => {
getCurrentPosition().then((res) => console.log('res', res));
});
return (
<IonPage>
<IonContent>
<div>Coordinates ( Yet to be displayed ) </div>
</IonContent>
</IonPage>
);
};
const TestComponent = () => {
const [coordinates, setCoordinates] =
useState({latitude:"", longitude:""});
const getCurrentPosition = async () => {
const {
coords: { latitude, longitude },
} = await Geolocation.getCurrentPosition();
setCoordinates({latitude, longitude})
};
useEffect(() => {
getCurrentPosition();
});
return (
<IonPage>
<IonContent>
<div>Coordinates {coordinates.latitude}</div>
</IonContent>
</IonPage>
);
};
Answered by Martin Červenka on January 5, 2022
Those values should live on the state somewhere. So for example:
const TestComponent = () => {
const [coord, setCoords] = useState(null);
useEffect(() => {
getCurrentPosition().then((res) => {
setCoords(res);
}
});
// Now you have access too coords here
if (!coords) return <div>Loading..<div> // handle waiting for the request
return (
<IonPage>
<IonContent>
<div>Coordinates { coords.latitude } { coords.longitude } </div>
</IonContent>
</IonPage>
);
};
Answered by BravoZulu on January 5, 2022
1 Asked on August 31, 2020 by b-jarvis
2 Asked on August 30, 2020 by kay
0 Asked on August 30, 2020 by sansel
2 Asked on August 29, 2020 by artportraitdesign1
0 Asked on August 28, 2020 by prakash-kumar
2 Asked on August 28, 2020 by kim
3 Asked on August 28, 2020 by adam-sewell
1 Asked on August 28, 2020 by loopinfility
1 Asked on August 26, 2020 by philip-kearns
1 Asked on August 26, 2020 by shawn
2 Asked on August 22, 2020 by very_human
1 Asked on August 22, 2020 by sundar_ima
2 Asked on August 21, 2020 by shrinath-shankar
1 Asked on August 20, 2020 by baudoin-michael
0 Asked on August 20, 2020 by 0x5453
1 Asked on August 19, 2020 by randomthinker
11 Asked on August 19, 2020 by tams
Get help from others!
Recent Questions
Recent Answers
© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP