Reactnative 获取位置
javascript
import Geolocation from '@react-native-community/geolocation';
javascript
const [coords, setCoords] = useState(null); // 存储经纬度
const [addressLoading, setAddressLoading] = useState(false);
const getLocation = () => {
setAddressLoading(true);
Geolocation.getCurrentPosition(
async (position) => {
console.log(position);
console.log(position.coords);
const { latitude, longitude } = position.coords;
setCoords({ latitude, longitude });
// 调用逆地理编码
await getAddressFromCoords(latitude, longitude);
},
(error) => {
console.log(error.code, error.message);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);
}
// 2. 逆地理编码:经纬度转具体地址
const getAddressFromCoords = async (latitude, longitude) => {
try {
// 高德逆地理编码 API 接口
const url = `https://restapi.amap.com/v3/geocode/regeo?output=json&location=${longitude},${latitude}&key=${AMAP_API_KEY}`;
const response = await fetch(url);
const result = await response.json();
if (result.status === '1') {
// 解析核心地址信息
const regeocode = result.regeocode;
const addressComponent = regeocode.addressComponent; // 地址组件(省/市/区/街道)
// const formattedAddress = regeocode.formatted_address; // 完整地址(如:浙江省杭州市西湖区文三路XX号)
// const neighborhood = addressComponent.neighborhood || {}; // 小区/社区
// const building = addressComponent.building || {}; // 楼栋
// 拼接更精准的地址(按需调整)
let detailedAddress = addressComponent.province + addressComponent.city + addressComponent.district;
// if (formattedAddress) detailedAddress += formattedAddress;
// if (neighborhood.name) detailedAddress += ` ${neighborhood.name}`;
// if (building.name) detailedAddress += ` ${building.name}`;
setAddress(detailedAddress || '暂无位置');
setAddressLoading(false);
} else {
setAddress(`暂无位置`);
setAddressLoading(false);
}
} catch (err) {
setAddress('暂无位置');
setAddressLoading(false);
console.error('逆地理编码失败:', err);
}
};
javascript
{/* 定位 */}
<TouchableOpacity style={[styles.row, { borderBottomWidth: 0 }]}
onPress={() => {
getLocation()
}}
>
<View style={styles.rowLeft}>
<Image
source={require('@/images/gajyIcon/setting-location.png')}
resizeMode="contain"
style={styles.icon}
/>
<Text style={styles.label}>定位</Text>
</View>
<View style={styles.rowRight}>
{/* <Text>{address}</Text> */}
<View style={styles.rowRight}>
{addressLoading ? (
// ActivityIndicator 是 React Native 内置的加载转圈组件
<ActivityIndicator
size="small" // 可选:small / large
color="#0066ff" // 自定义加载圈颜色
style={styles.loading} // 加载组件的样式
/>
) : (
<Text>{address}</Text>
)}
</View>
{/* <Image
source={require('@/images/gajyIcon/rightArr.png')}
resizeMode="contain"
style={styles.arrow}
/> */}
</View>
</TouchableOpacity>