跳到主要内容

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

代码演示

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>
);
};

Hook 支持度

微信小程序H5ReactNative
✔️✔️