首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何访问react-native-map中的coords?

如何访问react-native-map中的coords?
EN

Stack Overflow用户
提问于 2019-11-16 03:23:45
回答 1查看 61关注 0票数 0

我正在尝试通过使用react - native -map中的'coords‘属性在我的react原生应用程序中使用用户的当前位置。

问题是,当我尝试console.log currentLocation.coords时,我得到了错误:

代码语言:javascript
复制
TypeError: null is not an object (evaluating 'currentLocation.coords')

但是当我console.log currentLocation的时候,我可以看到响应中的和弦支点。

代码语言:javascript
复制
Object {
  "coords": Object {
    "accuracy": 5,
    "altitude": 5,
    "altitudeAccuracy": 5,
    "heading": 0,
    "latitude": 13.184791,
    "longtitude": 55.735991,
    "speed": 0,
  },
  "timestamp": 1000000,
}
代码语言:javascript
复制
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 }
);
代码语言:javascript
复制
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>
    );
};
代码语言:javascript
复制
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();
}, []);

我怎样才能访问coords?(我需要使用经度和纬度)

EN

回答 1

Stack Overflow用户

发布于 2019-11-16 03:38:38

我使用了'react-native- location‘来获取用户的当前位置。在subscribeToLocationUpdates中,我获取纬度和经度,如下所示。

代码语言:javascript
复制
 let requestBody = await getPlaceNameFromLocation(locations[0].latitude, locations[0].longitude)

如您所见,我正在获取位置数组,这在您的情况下可能会出现问题。请查收。As数组也是object。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58883429

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档