> 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** · 必需 · `对象`

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

  * **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`)**

这是用于设置位置精度级别的枚举。

```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.
