| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535 |
- const api = require('../../api/index.js');
-
- Page({
- data: {
- // 地图基础配置
- longitude: 0,
- latitude: 0,
- scale: 10,
- polyline: [],
- markers: [],
- // 选项卡默认选中车
- activeType: 'car',
- // 四类点位数据(车+电站+用户+司机)
- pointData: {
- car: [],
- station: [],
- user: [],
- driver: [] // 新增司机数据字段
- },
- currentList: [],
- // 四类点位自定义图标(新增司机图标)
- markerIcons: {
- car: 'https://esos-iot.com/myminio/project/e9c0fba9b61448e59458054d335b162b.png', // 储能车图标
- station: 'https://esos-iot.com/myminio/project/62a7a9c509f948558436bc56ee9bfe2e.png', // 电站图标
- user: 'https://esos-iot.com/myminio/project/42dd004817dd4f268d97dcd1145ca113.png', // 用户用电图标
- driver: 'https://esos-iot.com/myminio/project/6dc37b15321b462f9ab59c47263dd224.png' // 司机图标(替换为实际路径)
- },
- selectcardata: [],
- powerindex: 0,
- objectArray: []
- },
-
- onLoad(options) {
- wx.$on('wsMessage', this.handleWsMessage);
-
- if (wx.getStorageSync('projectId') == '') {
- wx.setStorage({
- key: 'projectId',
- data: ''
- });
- this.getaddredisredis()
- }
- this.getproject()
-
- // 初始化地图(延迟执行确保数据加载完成)
- setTimeout(() => {
- this.initAllMarkers();
- }, 2000);
- },
-
- onHide() {
- // 取消WebSocket订阅,防止内存泄漏
- wx.$off('wsMessage', this.handleWsMessage);
- },
-
- /**
- * 处理WebSocket消息
- */
- handleWsMessage(message) {
- console.log('收到WebSocket消息:', message);
- switch (message.api) {
- case '/syscar/selectcar':
- this.getproject();
- break;
- }
- },
-
- /**
- * 获取电站列表
- */
- getproject() {
- api.request(`/sysproject/selectproject`, 'post', {}, { isPublic: false })
- .then((res) => {
- console.log('电站列表:', res.data);
- if (res.code === 200) {
- // 新增"全部电站"选项
- const projectList = [{
- createTime: "",
- electric: "",
- partnership: "",
- projectId: "",
- projectType: "",
- projectName: "全部电站"
- }, ...res.data];
-
- this.setData({
- objectArray: projectList
- });
-
- // 设置默认选中项
- for (let i = 0; i < projectList.length; i++) {
- if (projectList[i].projectId === wx.getStorageSync('projectId')) {
- this.setData({ powerindex: i });
- break;
- }
- }
-
- // 重新加载所有数据
- this.getaddredisredis();
- this.oncar();
- this.onstation();
- this.onuser();
- this.ondriver(); // 新增加载司机数据
- }
- })
- .catch((err) => {
- console.error('获取电站列表失败:', err);
- });
- },
-
- /**
- * 缓存项目ID到redis
- */
- getaddredisredis() {
- const data = {
- projectId: wx.getStorageSync('projectId')
- };
- api.request(`/sysproject/insertredis`, 'POST', data)
- .then((res) => {
- console.log('Redis缓存结果:', res);
- })
- .catch((err) => {
- console.error('Redis缓存失败:', err);
- });
- },
-
- /**
- * 选择电站下拉框事件
- */
- bindPickerChange(e) {
- console.log('选择电站:', e.detail.value);
- const selectedIndex = e.detail.value;
- const selectedProject = this.data.objectArray[selectedIndex];
-
- // 缓存选中的项目ID
- wx.setStorage({
- key: 'projectId',
- data: selectedProject.projectId
- });
-
- // 更新redis缓存
- api.request(`/sysproject/insertredis`, 'POST', {
- projectId: selectedProject.projectId
- }).then((res) => {
- console.log('切换电站缓存结果:', res);
- this.getproject(); // 重新加载数据
- }).catch((err) => {
- console.error('切换电站缓存失败:', err);
- });
- },
-
- /**
- * 获取车辆数据
- */
- oncar() {
- api.request(`/syscar/selectcar`, 'post', {}, { isPublic: false })
- .then((res) => {
- console.log('车辆数据:', res.data);
- if (res.code === 200) {
- // 处理车辆数据,拆分经纬度
- const processedData = res.data.map(item => {
- // 拆分并清洗经纬度
- const posArr = item.carPosition?.split(',')
- .map(pos => pos.trim())
- .filter(pos => pos);
-
- const latitude = parseFloat(posArr?.[0]) || 0;
- const longitude = parseFloat(posArr?.[1]) || 0;
-
- return {
- ...item,
- latitude,
- longitude,
- type: 'car'
- };
- });
-
- this.setData({
- "pointData.car": processedData
- });
-
- // 如果当前选中的是车辆标签,更新列表
- if (this.data.activeType === 'car') {
- this.switchType({ currentTarget: { dataset: { type: 'car' } } });
- }
- }
- })
- .catch((err) => {
- console.error('获取车辆数据失败:', err);
- });
- },
-
- /**
- * 获取购电电站数据
- */
- onstation() {
- api.request(`/sysaddress/selectaddress`, 'post', { addressType: 1 }, { isPublic: false })
- .then((res) => {
- console.log('购电电站数据:', res.data);
- if (res.code === 200) {
- // 处理电站数据,补充经纬度和类型
- const processedData = res.data.map(item => {
- // 解析经纬度(根据实际字段调整)
- const latitude = parseFloat(item.latitude || item.addressLat) || 0;
- const longitude = parseFloat(item.longitude || item.addressLng) || 0;
-
- return {
- ...item,
- latitude,
- longitude,
- type: 'station'
- };
- });
-
- this.setData({
- "pointData.station": processedData
- });
-
- // 如果当前选中的是购电标签,更新列表
- if (this.data.activeType === 'station') {
- this.switchType({ currentTarget: { dataset: { type: 'station' } } });
- }
- }
- })
- .catch((err) => {
- console.error('获取购电电站数据失败:', err);
- });
- },
-
- /**
- * 获取售电用户数据
- */
- onuser() {
- api.request(`/sysaddress/selectaddress`, 'post', { addressType: 2 }, { isPublic: false })
- .then((res) => {
- console.log('售电用户数据:', res.data);
- if (res.code === 200) {
- // 处理用户数据,补充经纬度和类型
- const processedData = res.data.map(item => {
- // 解析经纬度(根据实际字段调整)
- const latitude = parseFloat(item.latitude || item.addressLat) || 0;
- const longitude = parseFloat(item.longitude || item.addressLng) || 0;
-
- return {
- ...item,
- latitude,
- longitude,
- type: 'user'
- };
- });
-
- this.setData({
- "pointData.user": processedData
- });
-
- // 如果当前选中的是售电标签,更新列表
- if (this.data.activeType === 'user') {
- this.switchType({ currentTarget: { dataset: { type: 'user' } } });
- }
- }
- })
- .catch((err) => {
- console.error('获取售电用户数据失败:', err);
- });
- },
-
- /**
- * 新增:获取司机数据
- */
- ondriver() {
- // 请替换为实际的司机接口地址和参数
- api.request(`/sysoperation/selectoperation`, 'post', {}, { isPublic: false })
- .then((res) => {
- console.log('司机数据:', res.data);
- if (res.code === 200) {
- // 处理司机数据,补充经纬度和类型
- const processedData = res.data.map(item => {
- // 解析经纬度(根据实际字段调整)
- const posArr = item.driverPosition?.split(',')
- .map(pos => pos.trim())
- .filter(pos => pos);
-
- const latitude = parseFloat(posArr?.[0] || item.latitude || 0);
- const longitude = parseFloat(posArr?.[1] || item.longitude || 0);
-
- return {
- ...item,
- latitude,
- longitude,
- type: 'driver',
- id: item.driverId || item.id, // 统一ID字段
- driverName: item.driverName || item.name || '未知司机' // 统一名称字段
- };
- });
-
- this.setData({
- "pointData.driver": processedData
- });
-
- // 如果当前选中的是司机标签,更新列表
- if (this.data.activeType === 'driver') {
- this.switchType({ currentTarget: { dataset: { type: 'driver' } } });
- }
- }
- })
- .catch((err) => {
- console.error('获取司机数据失败:', err);
- });
- },
-
- /**
- * 初始化所有点位标记
- */
- initAllMarkers() {
- // 合并所有四类点位数据
- const allPoints = [
- ...this.data.pointData.car,
- ...this.data.pointData.station,
- ...this.data.pointData.user,
- ...this.data.pointData.driver // 新增司机点位
- ];
-
- console.log('所有点位数据:', allPoints);
-
- // 适配地图视野并生成标记
- this.autoFitMap(allPoints);
- this.generateAllMarkers(allPoints);
- },
-
- /**
- * 自动适配地图视野,确保所有点位都可见
- */
- autoFitMap(pointList) {
- if (!pointList || pointList.length === 0) {
- // 无数据时默认定位上海
- this.setData({ longitude: 121.473701, latitude: 31.230416, scale: 14 });
- return;
- }
-
- // 提取有效经纬度
- const longitudes = pointList.map(item => Number(item.longitude)).filter(v => !isNaN(v) && v !== 0);
- const latitudes = pointList.map(item => Number(item.latitude)).filter(v => !isNaN(v) && v !== 0);
-
- if (longitudes.length === 0 || latitudes.length === 0) {
- this.setData({ longitude: 121.473701, latitude: 31.230416, scale: 14 });
- return;
- }
-
- // 计算极值和中心点
- const maxLng = Math.max(...longitudes);
- const minLng = Math.min(...longitudes);
- const maxLat = Math.max(...latitudes);
- const minLat = Math.min(...latitudes);
-
- const centerLng = (maxLng + minLng) / 2;
- const centerLat = (maxLat + minLat) / 2;
-
- // 计算跨度并添加缓冲
- const lngDiff = (maxLng - minLng) + 0.01;
- const latDiff = (maxLat - minLat) + 0.01;
-
- // 计算缩放级别
- const systemInfo = wx.getSystemInfoSync();
- const screenWidth = systemInfo.windowWidth;
- let scale = 1;
-
- if (lngDiff > 0) {
- scale = Math.log2((360 * screenWidth) / (lngDiff * 256 * Math.cos(centerLat * Math.PI / 180)));
- }
-
- const latScale = Math.log2((180 * screenWidth) / (latDiff * 256));
- scale = Math.min(scale, latScale);
-
- // 限制缩放范围(1-20)
- scale = Math.max(1, Math.min(20, Math.floor(scale)));
-
- // 更新地图配置
- this.setData({
- longitude: centerLng,
- latitude: centerLat,
- scale: scale
- });
- },
-
- /**
- * 生成所有点位的标记
- */
- generateAllMarkers(pointList) {
- if (!pointList || pointList.length === 0) {
- this.setData({ markers: [] });
- return;
- }
-
- // 生成标记数组
- const markers = pointList.map((item, index) => {
- // 构建标记弹窗内容
- let calloutContent = '';
- if (item.type === 'car') {
- calloutContent = `${item.carName || '储能车'}\n编号: ${item.controllerId || item.carId}\n状态: ${item.lineType === 1 ? '在线' : '离线'}`;
- } else if (item.type === 'station') {
- calloutContent = `${item.poiName || '购电站'}\n地址: ${item.addressName || '未知'}\n状态: ${item.addressDeletetype === 0 ? '在线' : '离线'}`;
- } else if (item.type === 'user') {
- calloutContent = `${item.poiName || '用电用户'}\n地址: ${item.addressName || '未知'}\n状态: ${item.addressDeletetype === 0 ? '在线' : '离线'}`;
- } else if (item.type === 'driver') {
- calloutContent = `${item.driverName || '司机'}\nID: ${item.driverId || item.id}\n状态: ${item.status === 0 ? '在线' : '离线'}`;
- }
-
- return {
- id: index + 1, // 唯一ID
- longitude: Number(item.longitude),
- latitude: Number(item.latitude),
- iconPath: this.data.markerIcons[item.type] || this.data.markerIcons.station, // 兜底图标
- width: 40,
- height: 40,
- anchor: { x: 0.5, y: 0.5 }, // 图标中心点对齐
- callout: {
- content: calloutContent,
- fontSize: 12,
- borderRadius: 8,
- bgColor: '#fff',
- padding: 8,
- display: 'BYCLICK',
- textAlign: 'left'
- },
- customData: item // 携带原始数据
- };
- });
-
- this.setData({ markers });
- },
-
- /**
- * 切换选项卡
- */
- switchType(e) {
- const type = e.currentTarget.dataset.type;
- this.setData({
- activeType: type,
- currentList: this.data.pointData[type] || []
- });
- },
-
- /**
- * 定位到指定点位
- */
- toPosition(e) {
- const item = e.currentTarget.dataset.item;
- if (!item || !item.longitude || !item.latitude || item.longitude === 0 || item.latitude === 0) {
- wx.showToast({
- title: '该点位无坐标信息',
- icon: 'none'
- });
- return;
- }
-
- // 定位到指定点位并放大
- this.setData({
- longitude: Number(item.longitude),
- latitude: Number(item.latitude),
- scale: 17
- });
-
- // 显示提示
- let title = '';
- if (item.type === 'car') title = `已定位到${item.carName || '储能车'}`;
- else if (item.type === 'station') title = `已定位到${item.poiName || '购电站'}`;
- else if (item.type === 'user') title = `已定位到${item.poiName || '用电用户'}`;
- else if (item.type === 'driver') title = `已定位到${item.driverName || '司机'}`;
-
- wx.showToast({
- title: title,
- icon: 'success',
- duration: 1200
- });
- },
-
- /**
- * 点击地图标记点
- */
- onMarkerTap(e) {
- const marker = this.data.markers.find(item => item.id === e.detail.markerId);
- if (marker) {
- this.setData({
- longitude: marker.longitude,
- latitude: marker.latitude,
- scale: 18
- });
- }
- },
-
- /**
- * 地图视野变化监听
- */
- onRegionChange(e) {
- if (e.type === 'end' && e.causedBy === 'drag') {
- this.setData({
- longitude: e.detail.centerLongitude,
- latitude: e.detail.centerLatitude,
- scale: e.detail.scale
- });
- }
- },
-
- /**
- * 查看详情
- */
- ondetails(e) {
- const item = e.currentTarget.dataset.item;
- console.log('查看详情:', item);
-
- // 根据类型跳转到不同详情页
- let url = '';
- if (item.type === 'car') {
- url = `/pages/car/index?id=${item.carId || item.id}&type=${item.type}`;
- } else if (item.type === 'station' || item.type === 'user') {
- url = `/pages/stationdetail/index?id=${item.addressId || item.id}&type=${item.type}`;
- } else if (item.type === 'driver') {
- url = `/pages/driverdetail/index?id=${item.operationId || item.id}&type=${item.type}`; // 新增司机详情页
- }
-
- if (url) {
- wx.navigateTo({ url });
- } else {
- wx.showToast({
- title: '暂无详情页面',
- icon: 'none'
- });
- }
- },
-
- onUnload() {
- // 页面卸载时清理WebSocket监听
- wx.$off('wsMessage', this.handleWsMessage);
- }
- });
|