[Weather App] 위치정보

woodstock·2024년 1월 1일
0
post-thumbnail

Location

Expo API Reference - Location

npx expo install expo-location
import * as Location from "expo-location";

권한요청

Location.requestForegroundPermissionsAsync()
앱이 포그라운드에 있는 동안 사용자에게 위치에 대한 권한을 부여하도록 요청

// 권한 요청에 대한 코드는 한 번만 실행
useEffect(() => {
  ask();
}, []);
// 권한을 요청하는 코드
const ask = async () => {
  const permission = await Location.requestForegroundPermissionsAsync();
  console.log(permission);
};

유저가 권한요청을 거절했을 때

// `granted`가 `false`라면, `ok`도 `false`가 되게하기
const [ok, setOk] = useState(true);

const ask = async () => {
  const { granted } = await Location.requestForegroundPermissionsAsync();
  if (!granted) {
    setOk(false);
  }
};

현재위치 가져오기

Location.getCurrentPositionAsync(options)
사용자의 현재 위치를 한 번만 제공하도록 요청하며, 특정 옵션을 통해 위치 정보의 정확도와 같은 세부 사항을 설정할 수 있다.


const ask = async () => {
// ... 생략
  const location = await Location.getCurrentPositionAsync({ accuracy: 5 });
  console.log(location);
};


역지오코딩

Location.reverseGeocodeAsync(location, options)
지리적 좌표(위도 및 경도)를 입력으로 받아 그 위치에 해당하는 우편 주소나 지명 등의 가독 가능한 주소 정보로 변환하는 기능으로 이러한 변환 과정을 역지오코딩이라고 한다.


const ask = async () => {
// ...생략
  const { coords: { latitude, longitude },} = await Location.getCurrentPositionAsync({ accuracy: 5 });
  
  const location = await Location.reverseGeocodeAsync({latitude, longitude,},{ useGoogleMaps: false });
  console.log(location);
};


console.log(location[0].city);


// 가져온 위치를 저장하고 사용하기
const [city, setCity] = useState("불러오는 중..");

const ask = async () => {
    const { granted } = await Location.requestForegroundPermissionsAsync();
    if (!granted) {
      setOk(false);
    }
    const {
      coords: { latitude, longitude },
    } = await Location.getCurrentPositionAsync({ accuracy: 5 });
    const location = await Location.reverseGeocodeAsync(
      {
        latitude,
        longitude,
      },
      { useGoogleMaps: false }
    );
    setCity(location[0].city);
  };
<Text style={styles.cityName}>{city}</Text>

profile
해내는 사람

0개의 댓글

관련 채용 정보