can not find the variable location with reversegeocodeAsync

浪子不回头ぞ 提交于 2020-04-18 05:46:07

问题


Hello everyone who sees that question I need help in that and full of hope that someone is gonna help I am trying to get the exact location for the user to pass it finally in some other functionalities. I am using Expo init and expo-location

while using (reversegeocodeAsync({})) for the first render it's giving me the correct location but while testing it's crashing and giving an error and even works it's not making the data like after setting state it's not being available globally to use it

I tried different ways First : use all the functions inside the same page but it doesn't work

import React, {useState, useEffect, useMemo} from 'react';
import {View, Text, StyleSheet, FlatList } from 'react-native';
import { NavigationEvents } from 'react-navigation';
import TimeApi from '../compnents/TimeApi';
import * as Location from 'expo-location';


const LocationScren = () => {
  const [time, setsTime] = useState({});
  const [errorMsg, setErrorMsg] = useState('');
  const [location, setLocation ] = useState(null);
  const [city, setCity ] = useState();

    const getLocation = async () => {
        let {status} = await Location.requestPermissionsAsync();
        if (status !== 'granted') {
            setErrorMsg('Access to Location denied');
        }

        const location = await Location.getCurrentPositionAsync({});
        setLocation(location)
    }

    const getCity = async () => {
        const place = await Location.reverseGeocodeAsync({
            latitude : location.coords.latitude,
            longitude : location.coords.longitude
        });

        place.find( p => {setCity(p.city);
        })
    }


    const getTime = async () => {
        const response = await TimeApi.get(`/${city}.json`);
        setTime(response.data);
}

    useEffect(() => {
    getTime(), getLocation(), getCity();
    } , []);


    console.log(time);
    console.log(location);
    console.log(city);

    return (
        <View>
        <FlatList 
        data = {time.items}
        keyExtractor = {time => time.first}
        renderItem = {({item}) => {
            return (
                <View>
                    <Text>  {item.first} </Text>
                    <Text>  {item.secnd} </Text>
                    <Text>  {item.third} </Text>
                    <Text>  {item.fourth} </Text>
                    <Text>   {item.fifth} </Text>
                    <Text>  {item.sixth} </Text>
                </View>
            );
        }}
        />
        {errorMsg ? <Text> {errorMsg} </Text> : null }
        </View>
    );
}

const styles = StyleSheet.create({});
export default LocationScren;

in here in the first render it's giving errors, then work , then giving that error ( null is not an object (evaluating 'location.coords')] )

Then I create a context file and added my functions and still getting the same error exactly

import createDataContext from './createDataContext';
import * as Location from 'expo-location';

const mwaqeetReducer = (state,action) => {
    switch(action.type) {
        case 'get_location' : 
            return action.payload;
        case 'add_error' : 
            return {...state, errorMessage : action.error};
        case 'get_city' : 
            return { cityName : action.payload};
        default:
            return state;
    }
}

const getLocation = dispatch => async () => {
    let {status} = await Location.requestPermissionsAsync();
    if (status === !'granted') {
        dispatch({type: 'add_error' , error : 'Permission to access location denied'});
    }

    let location = await Location.getCurrentPositionAsync({});
    dispatch({type : 'get_location' , payload : location});
    console.log(location);    
}

const getCity = dispatch => async () => {
    let keys = {
        latitude : location.coords.latitude,
        longitude : location.coords.longitude
    }
    const place = await Location.reverseGeocodeAsync(keys);
        place.find( p => p.city);
    dispatch({type : 'get_city' , payload : place});
    console.log(place);
}

export const {Provider, Context} = createDataContext(
    mwaqeetReducer, {
         getLocation, getCity
    } , {
        errorMessage : '', location : {}, cityName : ''
    }
)

so, please I need help to get over that.


回答1:


You can try something like this.

  useEffect(() => {
    runFunction();
  } , []);
const runFunction = async () => {
        let {status} = await Location.requestPermissionsAsync();
        if (status !== 'granted') {
            setErrorMsg('Access to Location denied');
        }

        const location = await Location.getCurrentPositionAsync({});
        setLocation(location)

        const place = await Location.reverseGeocodeAsync({
            latitude : location.coords.latitude,
            longitude : location.coords.longitude
        });

        let city;
        place.find( p => {
          city = p.city
          setCity(p.city)
        });

        const response = await TimeApi.get(`/${city}.json`);
        setTime(response.data);

    }



来源:https://stackoverflow.com/questions/61163567/can-not-find-the-variable-location-with-reversegeocodeasync

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!