我在我的 react-native 项目中使用 expo-location lib 的
getCurrentPositionAsync
:
result = await Location.getCurrentPositionAsync();
获取当前的GPS位置。
现在
result
变量将保存这个 JSON 对象:
Object {
"coords": Object {
"accuracy": 603,
"altitude": 0,
"altitudeAccuracy": 0,
"heading": 0,
"latitude": 37.421988,
"longitude": -122.0840207,
"speed": 0,
},
"mocked": false,
"timestamp": 1677233557987,
}
我需要使用状态函数将
latitude
和longitude
值从result
变量保存到状态变量location
:
setLocation({latitude, longitude});
所以当我跑步时:
console.log(location);
它会显示这个:
Object {
"latitude": 37.421988,
"longitude": -122.0840207,
}
现在我唯一的成功就是这样做:
const latitude = result['coords'].latitude;
const longitude = result['coords'].longitude;
setLocation({latitude, longitude});
我的问题是 - 是否有更直接的方法来做到这一点? 喜欢:
setLocation({result['coords'].latitude, result['coords'].longitude});
因为这行不通。
谢谢。
您在尝试设置位置状态时错过了按键。这应该有效:
setLocation({
latitude: result['coords'].latitude,
longitude: result['coords'].longitude,
});
或者,您可以使用解构从 result.coords 对象中提取纬度和经度值:
const { latitude, longitude } = result.coords;
setLocation({ latitude, longitude });
这是实现相同结果的更简洁的方法。