> For the complete documentation index, see [llms.txt](https://developers-apps-in-toss.toss.im/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers-apps-in-toss.toss.im/documentation/api-and-sdk-zh/common/permission/location.md).

# 位置

{% hint style="info" %}
**需要设置权限**

`getCurrentLocation`在使用之前需要设置位置权限。请先查看权限设置指南。
{% endhint %}

***

### 1. 获取当前位置

**SDK 函数：** `getCurrentLocation`

这是一个只获取设备当前位置一次的函数。用于在地图上显示用户位置，或搜索附近门店时很有用。

**签名**

```typescript
function getCurrentLocation(options: { accuracy: Accuracy }): Promise<Location>;
```

**参数**

* **options** · 必填 · `object`

  获取位置信息时使用的选项对象。

  * **options.accuracy** · 必填 · `Accuracy`

    这是位置信息精度级别。详细值请参考下面的 `Accuracy` 类型。

**返回值**

* `Promise<Location>`

  返回包含设备位置信息的对象。详细内容请参考下面的 `Location` 类型。

**权限方法**

* getCurrentLocation.getPermission

  返回位置权限的当前状态。 `allowed` · `denied` · `notDetermined` · `osPermissionDenied` 之一。
* getCurrentLocation.openPermissionDialog

  显示重新请求位置权限的对话框。允许时 `allowed`，拒绝时 `denied`则返回。

**错误**

当权限被拒绝时 `GetCurrentLocationPermissionError`会发生。

```typescript
class GetCurrentLocationPermissionError extends PermissionError {
  constructor();
}
```

**示例**

{% tabs %}
{% tab title="Web（JS）" %}

```js
import { Accuracy, getCurrentLocation, GetCurrentLocationPermissionError } from '@apps-in-toss/web-framework';

async function handleGetCurrentLocation() {
  try {
    const response = await getCurrentLocation({ accuracy: Accuracy.Balanced });
    console.log(`位置: ${response.coords.latitude}, ${response.coords.longitude}`);
  } catch (error) {
    if (error instanceof GetCurrentLocationPermissionError) {
      console.log('没有位置权限');
    }
  }
}
```

{% endtab %}

{% tab title="Web（React）" %}

```tsx
import { Accuracy, getCurrentLocation, GetCurrentLocationPermissionError, Location } from '@apps-in-toss/web-framework';
import { useState } from 'react';

function CurrentPosition() {
  const [position, setPosition] = useState<Location | null>(null);

  const handlePress = async () => {
    try {
      const response = await getCurrentLocation({ accuracy: Accuracy.Balanced });
      setPosition(response);
    } catch (error) {
      if (error instanceof GetCurrentLocationPermissionError) {
        // 没有位置权限
      }
    }
  };

  return (
    <div>
      {position ? (
        <span>
          位置: {position.coords.latitude}, {position.coords.longitude}
        </span>
      ) : (
        <span>尚未获取位置信息</span>
      )}
      <input type="button" value="获取当前位置" onClick={handlePress} />
      <input
        type="button"
        value="检查权限"
        onClick={async () => alert(await getCurrentLocation.getPermission())}
      />
      <input
        type="button"
        value="请求权限"
        onClick={async () => alert(await getCurrentLocation.openPermissionDialog())}
      />

  );
}
```

{% endtab %}

{% tab title="React Native" %}

```tsx
import { Accuracy, getCurrentLocation, GetCurrentLocationPermissionError, Location } from '@apps-in-toss/framework';
import { useState } from 'react';
import { Alert, Button, Text, View } from 'react-native';

function CurrentPosition() {
  const [position, setPosition] = useState<Location | null>(null);

  const handlePress = async () => {
    try {
      const response = await getCurrentLocation({ accuracy: Accuracy.Balanced });
      setPosition(response);
    } catch (error) {
      if (error instanceof GetCurrentLocationPermissionError) {
        // 没有位置权限
      }
    }
  };

  return (
    <View>
      {position ? (
        <Text>
          位置: {position.coords.latitude}, {position.coords.longitude}
        </Text>
      ) : (
        <Text>尚未获取位置信息</Text>
      )}
      <Button title="获取当前位置" onPress={handlePress} />
      <Button title="检查权限" onPress={async () => Alert.alert(await getCurrentLocation.getPermission())} />
      <Button
        title="请求权限"
        onPress={async () => Alert.alert(await getCurrentLocation.openPermissionDialog())}
      />
    </View>
  );
}
```

{% endtab %}
{% endtabs %}

***

### 2. 实时追踪位置

**SDK 函数：** `startUpdateLocation`

这是一个在位置变化时执行回调的函数。可用于运动应用记录移动距离，或在地图上实时更新位置。调用返回的 cleanup 函数后，追踪将停止。

**签名**

```typescript
function startUpdateLocation(options: {
  onError: (error: unknown) => void;
  onEvent: (location: Location) => void;
  options: StartUpdateLocationOptions;
}): () => void;
```

**参数**

* **onEvent** · 必填 · `(location: Location) => void`

  这是在位置信息变化时调用的回调函数。
* **onError** · 必填 · `(error: unknown) => void`

  这是在位置信息检测失败时调用的回调函数。
* **options** · 必填 · `StartUpdateLocationOptions`

  这是位置信息检测所需的设置对象。

  * **options.accuracy** · `Accuracy`

    设置位置精度。
  * **options.timeInterval** · `number`

    这是更新位置信息的最小周期。单位为毫秒(ms)。
  * **options.distanceInterval** · `number`

    将位置变化距离设置为米(m)单位。

**返回值**

* () => void

  这是停止位置追踪的 cleanup 函数。组件卸载时请务必调用。

**权限方法**

* startUpdateLocation.getPermission

  返回位置权限的当前状态。
* startUpdateLocation.openPermissionDialog

  显示重新请求位置权限的对话框。

**错误**

当权限被拒绝时 `StartUpdateLocationPermissionError`会发生。 `error instanceof StartUpdateLocationPermissionError`即可确认。

```typescript
const StartUpdateLocationPermissionError: typeof GetCurrentLocationPermissionError;
```

**示例**

{% tabs %}
{% tab title="Web（JS）" %}

```js
import { Accuracy, startUpdateLocation, StartUpdateLocationPermissionError } from '@apps-in-toss/web-framework';

let cleanup;

function handleStartUpdateLocation() {
  cleanup?.();

  cleanup = startUpdateLocation({
    options: { accuracy: Accuracy.Balanced, timeInterval: 3000, distanceInterval: 10 },
    onEvent: (location) => {
      console.log(`纬度: ${location.coords.latitude}, 经度: ${location.coords.longitude}`);
    },
    onError: (error) => {
      if (error instanceof StartUpdateLocationPermissionError) {
        console.log('没有位置权限');
      }
    },
  });
}

window.addEventListener('pagehide', () => cleanup?.());
```

{% endtab %}

{% tab title="Web（React）" %}

```tsx
import {
  Accuracy,
  Location,
  startUpdateLocation,
  StartUpdateLocationPermissionError,
} from '@apps-in-toss/web-framework';
import { useCallback, useState } from 'react';

function LocationWatcher() {
  const [location, setLocation] = useState<Location | null>(null);

  const handlePress = useCallback(() => {
    startUpdateLocation({
      options: { accuracy: Accuracy.Balanced, timeInterval: 3000, distanceInterval: 10 },
      onEvent: (location) => setLocation(location),
      onError: (error) => {
        if (error instanceof StartUpdateLocationPermissionError) {
          // 没有位置权限
        }
      },
    });
  }, []);

  return (
    <div>
      {location != null && (
        <>
          <span>纬度: {location.coords.latitude}</span>
          <span>经度: {location.coords.longitude}</span>
        </>
      )}
      <input type="button" value="开始追踪位置" onClick={handlePress} />

  );
}
```

{% endtab %}

{% tab title="React Native" %}

```tsx
import { Accuracy, Location, startUpdateLocation, StartUpdateLocationPermissionError } from '@apps-in-toss/framework';
import { useCallback, useState } from 'react';
import { Button, Text, View } from 'react-native';

function LocationWatcher() {
  const [location, setLocation] = useState<Location | null>(null);

  const handlePress = useCallback(() => {
    startUpdateLocation({
      options: { accuracy: Accuracy.Balanced, timeInterval: 3000, distanceInterval: 10 },
      onEvent: (location) => setLocation(location),
      onError: (error) => {
        if (error instanceof StartUpdateLocationPermissionError) {
          // 没有位置权限
        }
      },
    });
  }, []);

  return (
    <View>
      {location != null && (
        <>
          <Text>纬度: {location.coords.latitude}</Text>
          <Text>经度: {location.coords.longitude}</Text>
        </>
      )}
      <Button title="开始追踪位置" onPress={handlePress} />
    </View>
  );
}
```

{% endtab %}
{% endtabs %}

***

### 类型 · 对象

**位置精度选项（`Accuracy`)**

这是设置位置精度级别的 enum。

```typescript
enum Accuracy {
  Lowest = 1, // 误差范围在 3KM 以内
  Low = 2, // 误差范围在 1KM 以内
  Balanced = 3, // 误差范围在数百米以内
  High = 4, // 误差范围在 10M 以内
  Highest = 5, // 最高精度
  BestForNavigation = 6, // 用于导航的最高精度
}
```

***

**位置对象（`Location`)**

这是表示位置信息的对象。

```typescript
interface Location {
  accessLocation?: 'FINE' | 'COARSE'; // 仅限 Android。FINE：精确位置，COARSE：大致位置
  timestamp: number; // 位置更新时的 Unix 时间戳
  coords: LocationCoords; // 详细坐标信息
}
```

***

**详细位置坐标信息（`LocationCoords`)**

这是表示详细位置坐标信息的对象。

```typescript
interface LocationCoords {
  latitude: number; // 纬度
  longitude: number; // 经度
  altitude: number; // 高度
  accuracy: number; // 位置精度
  altitudeAccuracy: number; // 海拔精度
  heading: number; // 方向
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://developers-apps-in-toss.toss.im/documentation/api-and-sdk-zh/common/permission/location.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
