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
2 Asked on January 3, 2022 by haifeng-zhang
1 Asked on January 3, 2022 by zoh
1 Asked on January 3, 2022 by tmc
0 Asked on January 3, 2022
1 Asked on January 3, 2022
2 Asked on January 3, 2022 by cecil-ward
4 Asked on January 3, 2022 by hattricknz
2 Asked on January 3, 2022 by rich-shipley
5 Asked on January 3, 2022 by yiqing-wang
1 Asked on January 3, 2022
1 Asked on January 3, 2022
4 Asked on January 3, 2022 by nesh
2 Asked on January 3, 2022
1 Asked on January 3, 2022 by somekoder
2 Asked on January 3, 2022 by mohammad-23
1 Asked on January 3, 2022 by thomas-bouasli
Get help from others!
Recent Answers
Recent Questions
© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP