javascript
复制代码
<template>
<div id="map-container" ref="mapContainer" style="height: 600px;"></div>
</template>
<script setup>
import { onMounted, ref, onUnmounted } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import MQTT from 'mqtt';
import mqtt from 'mqtt';
import { ElMessage } from 'element-plus';
// 地图和MQTT配置信息
const amapKey = '高德key';
const mqttTopic = ''; // 订阅的主题
//mqtt配置
let options = {
username: 'admin',
password: 'public',//密码
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),// 随机生成客户端ID
connectTimeout: 600000,
keepalive: 10,//心跳,单位秒,如果后台开启监听可以快速知道有没有退出
clean: true,
reconnecrPeriod: 3000,//重连周期,1000毫秒,两次之间的时间间隔
resubscribe: true,//如果连接断开并重新连接,则会再次自动订阅已订阅的主题(默认true)
}
//ws wss是在h5网页上websoket协议 而wx wxs是针对微信小程序使用 当然如果你用uniapp做app的话 使用的也是wx
const client = MQTT.connect(`ws://你的ip:8083/mqtt`, options);
client.on('connect', (res) => {
ElMessage.success("链接成功")
client.subscribe(mqttTopic, (err) => {
if (!err) {
ElMessage.success("订阅成功")
}
})
}).on('message', (topic, message) => {
console.log(topic, JSON.parse(message))
//接受服务端信息
}).on('reconnect', (topic, message) => {
ElMessage.warning("重连")
}).on('error', () => {
console.log('77877')
//重新连接
client.reconnect()
})
// 地图容器的引用
const mapContainer = ref(null);
onMounted(async () => {
try {
// 加载高德地图API
const AMap = await AMapLoader.load({
key: amapKey,
version: '2.0',
plugins: ['AMap.Polyline'],
});
// 初始化地图
const map = new AMap.Map(mapContainer.value, {
zoom: 10,
center: [116.397428, 39.90923], // 北京市中心点
});
// 地图上的点位,示例为北京的几个点
const points = [
new AMap.LngLat(116.191031, 39.988585),
new AMap.LngLat(116.389275, 39.925818),
new AMap.LngLat(116.287444, 39.810742),
];
// 绘制航线
const polyline = new AMap.Polyline({
path: points,
strokeColor: "#FF33FF",
strokeWeight: 6,
strokeOpacity: 0.2,
strokeOpacity: 1,
});
map.add(polyline);
// 序列化航线数据
const lineData = JSON.stringify({ points: points.map(p => [p.lng, p.lat]) });
// 发布消息到MQTT主题
client.publish(mqttTopic, lineData, { qos: 1 }, (err) => {
if (err) {
console.error('MQTT消息发布失败:', err);
} else {
console.log('MQTT消息发布成功');
}
});
} catch (error) {
console.error('地图或MQTT初始化失败:', error);
}
});
// MQTT消息接收回调
client.on('message', (topic, message) => {
console.log(`从主题${topic}接收到消息: ${message.toString()}`);
});
// 组件销毁时断开MQTT连接
onUnmounted(() => {
client.end();
});
</script>
<style>
#map-container {
width: 100%;
}
</style>