1. 程式人生 > 其它 >openlayers學習二--利用websocket接收udp資料在地圖上畫點

openlayers學習二--利用websocket接收udp資料在地圖上畫點

websocket udp openlayers

1.在openlayers上畫點

先新建一個vector向量層,寫上渲染模式,再把vector層加入到map中

var source = new ol.source.Vector();
    var vectorLayer = new ol.layer.Vector({
      source: source,
      style: new ol.style.Style({
        fill: new ol.style.Fill({
          color: 'rgba(255,255,255,0.2)'
        }),
        stroke: new
ol.style.Stroke({ color: '#ffcc33', width: 2 }), image: new ol.style.Circle({ radius:3, fill: new ol.style.Fill({ color: '#ffcc33' }) }) }) }); map.addLayer(vectorLayer);

寫一個畫點函式,就是來一個點就將點座標設定為feature,並加入到向量層,這裡傳入一個時間變數,以備udp包傳入的引數。

    var drawPoint = function(time){
      var coord = ol.proj.transform([lon+3*Math.cos(time),lat+3*Math.sin(time)],'EPSG:4326', 'EPSG:3857');
      var feature = new ol.Feature({
        geometry: new ol.geom.Point(coord)
      });
      lon -=0.001;
      i++;
      vectorLayer.getSource().addFeature(feature);
    }

2.利用node.js處理udp包

先建立udpsocket,繫結埠,並處理包資料,這裡處理的是小端float資料。

const dgram = require('dgram');
let server = dgram.createSocket('udp4');
server.bind(6000);

var pp = [];
server.on('message',function(msg,rinfo){
    const t = msg.slice(0,4);
    const b = msg.slice(4,8);
    const l = msg.slice(8,12);

    const p = new Array(3);
    p[0] = t.readFloatLE(0).toString();
    p[1] = b.readFloatLE(0).toString();
    p[2] = l.readFloatLE(0).toString();
    pp = p;
    console.log(pp.toString());
})

3. 利用node.js傳送資料

建立websocket,監聽3000埠,並將udp資料傳送出去

var time = 1;
var ws = require('nodejs-websocket');
var wss = ws.createServer(conn =>{
    console.log("正在連線");
    conn.on('text',function(data){
        //console.log("收到:"+data);
        conn.send(pp.toString());
        time+=1;
    })
    conn.on('close',function(){
        conn.log('closed');
    })
    conn.on('error',function(){
        conn.log('error');
    })
})

wss.listen(3000,function(){
    console.log('正在監聽3000埠');
})

4.在網頁中利用websocket收數

監聽3000埠,10hz傳送hello,收到資料時,解包得到時間,並傳入drawPoint函式

    const ws = new WebSocket('ws://localhost:3000');
    ws.onopen = function(e){
      console.log('連線成功');
      setInterval(function(){
        ws.send('hello');
      },100)
    }
    ws.onmessage = function(e){
      var pp = (e.data).split(",");
      drawPoint(parseInt(pp[0]));
      console.log(pp[0]);
    };

5.寫一個c++發包程式,測一下

完活