如何在react native中获取城市位置


import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import * as Location from 'expo-location'
import Permissions from "expo-permissions";
export default function App() {
const [address, setAddress] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
useEffect(() => {
console.log(errorMsg)
console.log(address)
}, []);
const _getLocationAsync = async () => {
let { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== "granted") {
setErrorMsg = "Permission to access location was denied";
}
const location = await Location.reverseGeocodeAsync({});
const address = await Location.reverseGeocodeAsync(location.coords);
address;
_getLocationAsync();
};
let text = "Waiting...";
if (errorMsg) {
text = setErrorMsg;
} else if (address) {
text = setAddress[0].city;
}
return (
<View style={styles.container}>
<Text style={styles.text}>{text}</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#bcbcbc',
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 20
}
});

我有这个代码来获取react native中的城市位置,但我不知道我还应该做什么来获取位置。我尝试了一段时间,但我改变了很多事情,不知道我到底做了什么。。。如果有人能在这里帮我一点,我将不胜感激

我使用了来自'@react native comunity/Geolocation'的Geolocation,它返回纬度和经度。

Geolocation.getCurrentPosition(async (info) => {
const location = await getLocation(
info.coords.latitude,
info.coords.longitude,
);
...

并使用谷歌地图api对进行地理编码

export const getLocation = async (lat: number, long: number) => {
const apiKey = 'my api key'
return Api.get(
`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${long}&key=${apiKey}`,
);
};

希望这对你有效

最新更新