Home > database >  How to get user city location in react native?
How to get user city location in react native?

Time:02-06

How to get the user city location in react native? earlier I was developing an app for android in using expo but due to some reasons, I rebuilt it in react native cli so how can I do the same in react native cli? i want to get user city name and then send that city name to backend i provide you my expo code how can i function this same in react native cli?

  const [userdata, setUserdata] = useState(null);
    const [location, setLocation] = useState(null);
    const [errorMsg, setErrorMsg] = useState(null);
    const [city, setCity] = useState(null);

useEffect(() => {
    getUserData();
    getLocation();
}, []);

const getUserData = useCallback(async () => {
    try {
        const userDataString = await AsyncStorage.getItem('user');
        const userData = JSON.parse(userDataString);
        setUserdata(userData);
    } catch (err) {
        alert(err);
    }
}, []);

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

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

        let city = await Location.reverseGeocodeAsync(location.coords);
        setCity(city[0].city);
    } catch (err) {
        console.error(err);
    }
}, []);

const sendCity = useCallback(async () => {
    try {
        const response = await fetch('https://backnedurl.com/GetCity', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                city: city,
                username: userdata.user.username
            }),
        });
        const data = await response.json();
        console.log('Success:', data);
    } catch (err) {
        console.error('Error:', err);
    }
}, [userdata, city]);

useEffect(() => {
    if (userdata && city) {
        sendCity();
    }
}, [userdata, city, sendCity]);

AsyncStorage.getAllKeys()
    .then((keys) => {
        keys.forEach((key) => {
            AsyncStorage.getItem(key)
                .then((value) => {
                    console.log(`${key}: ${value}`);
                })
                .catch((error) => {
                    console.log(`Error retrieving data for key ${key}: ${error}`);
                });
        });
    })
    .catch((error) => {
        console.log(`Error retrieving keys: ${error}`);
    });

CodePudding user response:

You can use react-native-get-location package to get latitude and longitude of the user. Then you can get city name using openstreetmap by sending lat and long.

  • Related