Skip to content

현재 위치 가져오기

getCurrentLocation

getCurrentLocation 는 디바이스의 현재 위치 정보를 가져오는 함수예요. 위치 기반 서비스를 구현할 때 사용되고, 한 번만 호출되어 현재 위치를 즉시 반환해요. 예를 들어 지도 앱에서 사용자의 현재 위치를 한 번만 가져올 때, 날씨 앱에서 사용자의 위치를 기반으로 기상 정보를 제공할 때, 매장 찾기 기능에서 사용자의 위치를 기준으로 가까운 매장을 검색할 때 사용하면 유용해요.

시그니처

typescript
function getCurrentLocation(options: GetCurrentLocationOptions): Promise<Location>;

파라미터

  • options필수 · GetCurrentLocationOptions

    위치 정보를 가져올 때 사용하는 옵션 객체예요.

    • options.accuracyAccuracy

      위치 정보의 정확도 수준이에요. 정확도는 Accuracy 타입으로 설정돼요.

반환 값

  • Promise<Location>

    디바이스의 위치 정보가 담긴 객체를 반환해요. 자세한 내용은 Location을 참고해주세요.

예제

디바이스의 현재 위치 정보 가져오기

tsx
import { Accuracy, getCurrentLocation, Location } from '@apps-in-toss/web-framework';
import { Text, Button } from '@toss-design-system/mobile';
import { useState } from 'react';

// 현재 위치 정보를 가져와 화면에 표시하는 컴포넌트
function CurrentPosition() {
  const [position, setPosition] = useState<Location | null>(null);

  async function handleClick() {
    try {
      const response = await getCurrentLocation({ accuracy: Accuracy.Balanced });
      setPosition(response);
    } catch (error) {
      console.error('위치 정보를 가져오는 데 실패했어요:', error);
    }
  };

  return (
    <div>
      {position ? (
        <Text>
          위치: {position.coords.latitude}, {position.coords.longitude}
        </Text>
      ) : (
        <Text>위치 정보를 아직 가져오지 않았어요</Text>
      )}
      <Button size="medium" onClick={handleClick}>
        현재 위치 정보 가져오기
      </Button>
    </div>
  );
}
tsx
import { Accuracy, getCurrentLocation, Location } from '@apps-in-toss/framework';
import { Button, Text } from '@toss-design-system/react-native';
import { useState } from 'react';
import { View } from 'react-native';

// 현재 위치 정보를 가져와 화면에 표시하는 컴포넌트
function CurrentPosition() {
  const [position, setPosition] = useState<Location | null>(null);

  async function handlePress() {
    try {
      const response = await getCurrentLocation({ accuracy: Accuracy.Balanced });
      setPosition(response);
    } catch (error) {
      console.error('위치 정보를 가져오는 데 실패했어요:', error);
    }
  }

  return (
    <View>
      {position ? (
        <Text>
          위치: {position.coords.latitude}, {position.coords.longitude}
        </Text>
      ) : (
        <Text>위치 정보를 아직 가져오지 않았어요</Text>
      )}
      <Button onPress={handlePress}>현재 위치 정보 가져오기</Button>
    </View>
  );
}