实时展示GPS的数据是webgis中比较常见的一个需求,本文通过nodejs-websocket
模拟GPS数据的更新,实现GPS数据的实施推送与地图数据的展示。
nodejs-websocket
模拟数据// websocket.js
// websocket.js
const ws = require('nodejs-websocket')
const createServer = () => {
let server = ws.createServer(connection => {
connection.on('text', function(result) {
console.log('发送消息', result)
})
connection.on('connect', function(code) {
console.log('开启连接', code)
})
connection.on('close', function(code) {
console.log('关闭连接', code)
})
connection.on('error', function(code) {
console.log('异常关闭', code)
})
})
return server
}
module.exports = createServer()
// app.js
// 导入nodejs-websocket模块
const io = require('nodejs-websocket')
let connection = null
let gps = {}
for (let i = 0; i < 200; i++) {
gps['gps' + i] = {
offset: randomNum(-0.2, 0.2)
}
}
// 执行websocket处理连接方法
io.createServer(con => {
console.log('new connection...')
connection = con
sendData()
//处理客户端发送过来的消息
// connection.on("text",function(data){
// console.log("接收到的客户端消息:" + data);
// })
//监听关闭
connection.on("close", function (code, reason) {
console.log("Connection closed")
})
//监听异常
connection.on("error",() => {
console.log('服务异常关闭...')
})
}).listen(3000)
function sendData() {
connection.sendText(getGpsPositions())
setTimeout(sendData, 1000)
}
function getGpsPositions() {
const [xmin, ymin, xmax, ymax] = [36.6324, 8.04789, 171.6324, 57.96]
let data = []
for (let k in gps) {
const d = gps[k]
let lon, lat
if(!d.lon) {
lon = randomNum(xmin, xmax)
lat = randomNum(ymin, ymax)
} else {
lon = d.lon + d.offset
lat = d.lat + d.offset
}
gps[k] = {
lon: lon,
lat: lat,
offset: d.offset
}
data.push({code: k, coords: [lon, lat]})
}
return JSON.stringify(data)
}
function randomNum(min, max){
return Math.random() * (max - min) + min
}
const center = [104.1324, 36.92669]
var map = null, ws = null
var mapDom = document.getElementById('map')
fetch('../data/style.json').then(res => res.json()).then(res => {
map = new mapboxgl.Map({
accessToken: 'pk.eyJ1IjoibHp1bml1anAwOCIsImEiOiJjajJqcmlrMTYwMDI2MzJuaXd0NmRtZTl5In0.eMIg2fpiFaDInq2YVE4_2A',
container: mapDom, // container ID
style: res,
center: center, // starting position [lng, lat]
zoom: 3
});
map.on('load', () => {
map.addSource('points', {
type: 'geojson',
data: getGeojson([])
});
map.addLayer({
id: "circle",
type: "circle",
source: "points",
paint: {
"circle-color": 'red',
"circle-radius": 4,
"circle-stroke-color": 'white',
"circle-stroke-width": 2
}
});
ws = new WebSocket("ws://localhost:3000")
ws.onopen = function() {
console.log("当前客户端已经连接到websocket服务器")
}
ws.onmessage = function (evt) {
const data = JSON.parse(evt.data)
let features = data.map(d => {
return {
"type":"Feature",
"properties": d,
"geometry":{
"type":"Point",
"coordinates": d.coords
}
}
})
map.getSource('points').setData(getGeojson(features))
};
ws.onclose = function(){
alert("连接已关闭...");
};
})
})
function getGeojson(features) {
return {
"type": "FeatureCollection",
"features": features
}
}