javascript - 如何访问 react-native-maps 中的坐标?
问题描述
我正在尝试通过使用 react-native-maps 中的“coords”道具在我的 react native 应用程序中使用用户的当前位置。
问题是当我尝试 console.log currentLocation.coords 时出现错误:
TypeError: null is not an object (evaluating 'currentLocation.coords')
但是当我 console.log currentLocation 时,我可以在响应中看到 coords 道具。
Object {
"coords": Object {
"accuracy": 5,
"altitude": 5,
"altitudeAccuracy": 5,
"heading": 0,
"latitude": 13.184791,
"longtitude": 55.735991,
"speed": 0,
},
"timestamp": 1000000,
}
const locationReducer = (state, action) => {
switch (action.type) {
case 'add_current_location':
return { ...state, currentLocation: action.payload }
default:
return state;
}
};
const startRecording = dispatch => () => {};
const stopRecording = dispatch => () => {};
const addLocation = dispatch => (location) => {
dispatch({ type: 'add_current_location', payload: location })
};
export const { Context, Provider } = createDataContext(
locationReducer,
{ startRecording, stopRecording, addLocation },
{ recording: false, locations: [], currentLocation: null }
);
const Map = () => {
const { state: { currentLocation } } = useContext(LocationContext);
console.log(currentLocation.coords);
if (!currentLocation) {
return <ActivityIndicator size="large" style={{ marginTop: 200 }} />;
};
return (
<MapView
style={styles.map}
initialRegion={{
...currentLocation.coords,
latitudeDelta: 0.01,
longitudeDelta: 0.01
}}
>
</MapView>
);
};
const TrackCreateScreen = () => {
const { addLocation } = useContext(LocationContext);
const [err, setErr] = useState(null);
const startWatching = async () => {
try {
await requestPermissionsAsync();
await watchPositionAsync({
accuracy: Accuracy.BestForNavigation,
timeInterval: 1000,
distanceInterval: 10
}, (location) => {
addLocation(location);
});
} catch (e) {
setErr(e);
}
};
useEffect(() => {
startWatching();
}, []);
如何访问坐标?(我需要使用经度和纬度)
解决方案
我使用“react-native-location”来获取用户的当前位置。在subscribeToLocationUpdates
中,我正在获取纬度和经度,如下所示。
let requestBody = await getPlaceNameFromLocation(locations[0].latitude, locations[0].longitude)
如您所见,我正在获取在您的情况下可能存在问题的位置数组。请检查。因为数组也是对象。
推荐阅读
- python - 为什么最后一个函数没有执行?
- php - PHP 7.3 使用 PDO SQLSRV 返回奇怪的结果
- html - 如何在表单中定位 div 类?
- r - R 无法识别阿拉伯语
- sql-server - 同一数据库中的分片映射管理器和查询节点
- anylogic - How to optimize the makespan?
- python - How to exchange variables between different python files?
- visual-studio - How to include 'Solution Items' files in multi-project solution template
- typescript - 如何为解构对象中的嵌套函数编写类型?
- swift - swift optional chaining - can it fail?