useLocation
地理位置
何时使用
当需使用地理位置时
API
const [
location,
{
get,
choose,
choosePOI,
open,
toggleUpdate,
on,
off,
},
] = useLocation(options?);
参数说明
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
options | 获取地理信息配置(若指定后面可与新的配置合并) | ExcludeOption<Taro.getLocation.Option> | - |
返回值说明
返回值 | 说明 | 类型 |
---|---|---|
location | 根据初始化配置获取的地理信息 | WithUndefind<Taro.getLocation.SuccessCallbackResult> |
get | 获取当前的地理位置、速度(h5 支持) | PromiseOptionalAction<Option, Taro.getLocation.SuccessCallbackResult> |
choose | 打开地图选择位置 | PromiseOptionalAction<ExcludeOption<Taro.chooseLocation.Option>, Taro。chooseLocation.SuccessCallbackResult> |
choosePOI | 打开地图选择位置 | PromiseWithoutOptionAction<Taro.choosePoi.SuccessCallbackResult> |
toggleUpdate | 开启/关闭小程序进入前台(或后台)时接收位置消息 | PromiseParamsAction<(onOff?: boolean, background?: boolean) => void> |
open | 使用微信内置地图查看位置 | PromiseAction<ExcludeOption<Taro.openLocation.Option>> |
on | 监听实时地理位置变化事件(h5 支持) | (callback: ChangeCallback \| ChangErrorCallback, error?: boolean) => void |
off | 取消监听实时地理位置变化事件(h5 支持) | (callback: Callback \| ChangErrorCallback, error?: boolean) => void |
代码演示
- React
- Vue
device/useLocation/index
import React from 'react';
import { useRef, useEffect, useState } from '@taro-hooks/core';
import { escapeState } from '@taro-hooks/shared';
import { useLocation, useModal } from 'taro-hooks';
import DemoContent from '@src/components/DemoContent';
import { Button, Cell } from '@taroify/core';
export default () => {
const [locationInfo, setLocationInfo] = useState({});
const updateStatus = useRef<boolean>(false);
const listenStatus = useRef<boolean>(false);
const show = useModal({
title: 'useLocation',
showCancel: false,
});
const [location, { get, choose, choosePOI, open, toggleUpdate, on, off }] =
useLocation({
isHighAccuracy: true,
altitude: true,
type: 'gcj02',
});
useEffect(() => {
setLocationInfo(escapeState(location));
}, [location]);
const handleChoose = async () => {
try {
const chooseInfo = await choose();
setLocationInfo(chooseInfo);
show({ content: JSON.stringify(chooseInfo) });
} catch (e) {
show({ content: '获取位置失败' });
}
};
const handleChoosePOI = async () => {
try {
const chooseInfo = await choosePOI();
show({ content: JSON.stringify(chooseInfo) });
} catch (e) {
show({ content: '获取POI失败' });
}
};
const handleOpen = () => {
open({
latitude: escapeState(locationInfo).latitude,
longitude: escapeState(locationInfo).longitude,
});
};
const handleToggle = async () => {
try {
await toggleUpdate(!updateStatus.current);
show({
content: (updateStatus.current ? '关闭' : '打开') + '前台接收成功',
});
updateStatus.current = !updateStatus.current;
} catch (e) {
show({
content: (updateStatus.current ? '关闭' : '打开') + '前台接收失败',
});
}
};
const listener = (result) => {
setLocationInfo(result);
};
const handleToggleListener = async () => {
try {
const method = listenStatus.current ? off : on;
await method(listener);
show({ content: (listenStatus.current ? '关闭' : '打开') + '监听成功' });
listenStatus.current = !listenStatus.current;
} catch (e) {
show({ content: (listenStatus.current ? '关闭' : '打开') + '监听失败' });
}
};
return (
<DemoContent>
<Cell.Group title="位置信息">
{Object.entries(locationInfo ?? {}).map(([key, value]) => (
<Cell key={key} title={key} brief={JSON.stringify(value)}></Cell>
))}
</Cell.Group>
<Button
block
color="primary"
className="gap"
onClick={() => get()}
shape="square"
>
获取当前位置
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => handleChoose()}
shape="square"
>
选择地理位置
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => handleChoosePOI()}
shape="square"
>
选择POI位置
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => handleOpen()}
shape="square"
>
查看位置
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => handleToggle()}
shape="square"
>
切换前台接受地理
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => handleToggleListener()}
shape="square"
>
切换监听地理位置
</Button>
</DemoContent>
);
};
device/useLocation/index
<template>
<demo-content>
<nut-cell-group title="位置信息">
<nut-cell
v-for="(value, index) in locationInfo"
:key="index"
:title="index"
:sub-title="$filters.stringify(value)"
>
</nut-cell>
</nut-cell-group>
<nut-button shape="square" type="primary" class="gap" block @click="get()"
>获取当前位置</nut-button
>
<nut-button
shape="square"
type="primary"
class="gap"
block
@click="handleChoose()"
>选择地理位置</nut-button
>
<nut-button
shape="square"
type="primary"
class="gap"
block
@click="handleChoosePOI()"
>选择POI位置</nut-button
>
<nut-button
shape="square"
type="primary"
class="gap"
block
@click="handleOpen()"
>查看位置</nut-button
>
<nut-button
shape="square"
type="primary"
class="gap"
block
@click="handleToggle()"
>切换前台接受地理</nut-button
>
<nut-button
shape="square"
type="primary"
class="gap"
block
@click="handleToggleListener()"
>切换监听地理位置</nut-button
>
</demo-content>
</template>
<script setup lang="ts">
import { useState, useEffect, useRef } from '@taro-hooks/core';
import { escapeState } from '@taro-hooks/shared';
import { useLocation, useModal } from 'taro-hooks';
const [locationInfo, setLocationInfo] = useState({});
const updateStatus = useRef<boolean>(false);
const listenStatus = useRef<boolean>(false);
const show = useModal({ title: 'useLocation', mask: true, showCancel: false });
const [location, { get, choose, choosePOI, open, toggleUpdate, on, off }] =
useLocation({
isHighAccuracy: true,
altitude: true,
type: 'gcj02',
});
useEffect(() => {
setLocationInfo(escapeState(location));
}, [location]);
const handleChoose = async () => {
try {
const chooseInfo = await choose();
setLocationInfo(chooseInfo);
show({ content: JSON.stringify(chooseInfo) });
} catch (e) {
show({ content: '获取位置失败' });
}
};
const handleChoosePOI = async () => {
try {
const chooseInfo = await choosePOI();
show({ content: JSON.stringify(chooseInfo) });
} catch (e) {
show({ content: '获取POI失败' });
}
};
const handleOpen = () => {
open({
latitude: escapeState(locationInfo).latitude,
longitude: escapeState(locationInfo).longitude,
});
};
const handleToggle = async () => {
try {
await toggleUpdate(!updateStatus.current);
show({
content: (updateStatus.current ? '关闭' : '打开') + '前台接收成功',
});
updateStatus.current = !updateStatus.current;
} catch (e) {
show({
content: (updateStatus.current ? '关闭' : '打开') + '前台接收失败',
});
}
};
const listener = (result) => {
setLocationInfo(result);
};
const handleToggleListener = async () => {
try {
const method = listenStatus.current ? off : on;
await method(listener);
show({ content: (listenStatus.current ? '关闭' : '打开') + '监听成功' });
listenStatus.current = !listenStatus.current;
} catch (e) {
show({ content: (listenStatus.current ? '关闭' : '打开') + '监听失败' });
}
};
</script>
Hook 支持度
微信小程序 | H5 | ReactNative |
---|---|---|
✔️ | ✔️ |