【问题标题】:How to get user city location in react native?如何在 React Native 中获取用户城市位置?
【发布时间】:2023-02-05 11:21:04
【问题描述】:

如何在 React Native 中获取用户城市位置?早些时候我正在使用 expo 为 android 开发一个应用程序,但由于某些原因,我在 react native cli 中重建了它,所以我如何在 react native cli 中做同样的事情?我想获取用户城市名称,然后将该城市名称发送到后端,我为您提供了我的博览会代码,我如何才能在 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}`);
    });

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    您可以使用react-native-get-location包来获取用户的latitudelongitude。然后你可以通过发送纬度和经度使用openstreetmap获取城市名称。

    【讨论】: