import React, { useState, useEffect, useRef } from 'react';
import './index.scss';
import { View, Map } from '@tarojs/components';
import { Button } from '@nutui/nutui-react-taro';
import Taro from '@tarojs/taro';
const Index = () => {
const mapRef = useRef(null);
// 标记点
const markers = [
{
id: 0,
latitude: 30.572269,
longitude: 104.066541,
title: '成都',
width: 20,
height: 20
}]
// 路线
const polyline = [
{
points: [
{ latitude: 30.572269, longitude: 104.066541 },
{ latitude: 30.572379, longitude: 104.066745 },
{ latitude: 30.572489, longitude: 104.067242 }
],
color: '#FF0000',
width: 5,
dottedLine: false
}
];
// 显示用户当前位置---失败
// 在app.config.js文件和pages同级配置permission
// permission: {
// 'scope.userLocation': {
// desc: '你的位置信息将用于小程序位置接口的效果展示'
// }
// }
// 在 handleShowLocation 函数中请求用户位置信息,并传递给 Map 组件
const handleShowLocation = async () => {
try {
const res = await Taro.getLocation();
if (mapRef.current) {
mapRef.current.moveToLocation({
longitude: res.longitude,
latitude: res.latitude
});
}
} catch (error) {
console.error('获取用户位置失败:', error);
}
}
// 可以在这里处理获取到的经纬度信息,比如显示在页面上或发送给后端
const handleTap = (e) => {
console.log('用户点击地图坐标:', e.detail.longitude, e.detail.latitude);
};
return (
<View className='map'>
<Map
ref={mapRef} // 显示用户当前位置
longitude={104.066541} //中心经度
latitude={30.572269} //中心纬度
scale={16} //缩放
markers={markers} //标记点
polyline={polyline} //路线
onTap={handleTap} //用户选择位置
style={{ width: '100%', height: '300px' }}
/>
<Button onClick={handleShowLocation}>显示当前位置</Button>
</View>
);
};
export default Index;
01-24
607
07-02
1123
05-19