Search code examples
google-mapslocationexpojmapviewer

Location.requestForegroundPermissionsAsync is not a function


I just try to use expo-location and I found that error Location.requestForegroundPermissionsAsync is not a function

this is my code

import * as Location from 'expo-location';

const setCurrentLocation = async() => {
        let { status } = await Location.requestForegroundPermissionsAsync();
        if (status !== 'granted') {
            setErrorMsg('Permission to access location was denied');
            return;
          }
          let location = await Location.getCurrentPositionAsync({});
          setLocation(location);
            if (errorMsg) {
                setCheckText(errorMsg)
            } else if (location) {
                setCheckText(JSON.stringify(location))
            }  
    }

Solution

  • To display the coordinates -

    1. Initialize your state like this
    import { useState } from "react";
    
    .
    .
    .
    
    const [location, setLocation] = useState(null);
    
    1. Define setCurrentLocation function as shown
    const setCurrentLocation = async () => {
      let { status } = await Location.requestForegroundPermissionsAsync();
    
      if (status !== 'granted') {
        setErrorMsg('Permission to access location was denied');
        return;
      }
    
      let location = await Location.getCurrentPositionAsync({});
      setLocation(location);
    }; 
    
    1. Then your render part will look something like this
    return (
      <View style={styles.container}>
        {location ? <Text>latitude = {location.coords.latitude}</Text> : null}
        {location ? <Text>longitude = {location.coords.longitude}</Text> : null}
      </View>
    );
    

    Working Example