概述
很多時候,我們有這樣的使用情境:外業人員在外作業,我們需要知道人員的當前的即時位置和人員資訊,如何?呢。本文將為大家簡單的說明該情境下我們應該實現。 效果
思路
解決即時位置的展示,最核心的有兩點:1、資料的傳輸與儲存;2、裝置端如何和監控端進行資料互動。
首先,我們來說第一個的問題:資料的傳輸與儲存。大多時候,裝置傳輸過來的位置資訊數需要做儲存的,除了個別情況外。因此,我們可以考慮在資料庫中建立一張表,來記錄裝置的即時位置資料。
-- 建立表CREATE TABLE location_track( id serial NOT NULL, lon double precision NOT NULL, lat double precision NOT NULL, create_time time(10) with time zone NOT NULL, geom geometry not null, PRIMARY KEY (id))
其次,資料互動問題。這個問題的解決方式有兩種:1、前端的定時重新整理;2、後端的即時推送。如果是前端的定時重新整理,我們可以用setInterval(function, time)來處理;如果是後端的即時推送,這裡面涉及兩個方面的思考:a、位置資訊傳輸過來入庫後的觸發器;b、websocket資料的即時推送。 實現 在本demo中,為了實現效果,表建立完成後,先在在表中插入了一批資料,以作測試。
insert into location_track(lon, lat, create_time, geom) values(116.379883, 39.865601, now(), st_point(116.379883, 39.865601));insert into location_track(lon, lat, create_time, geom) values(116.379997, 39.865498, now(), st_point(116.379997, 39.865498));insert into location_track(lon, lat, create_time, geom) values(116.380104, 39.865364, now(), st_point(116.380104, 39.865364));
一次性將全部資料取出來,做個定時處理,來類比位置的即時更新效果(在實際中,只需要在觸發器裡面擷取最新的記錄即可)。
package com.lzugis.web.websocket;import com.lzugis.services.TestService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.socket.CloseStatus;import org.springframework.web.socket.TextMessage;import org.springframework.web.socket.WebSocketSession;import org.springframework.web.socket.handler.TextWebSocketHandler;import java.util.List;import java.util.Map;import java.util.Timer;import java.util.TimerTask;@RequestMapping("/websocket")public class LocationTrackEndPoint extends TextWebSocketHandler { @Autowired private TestService testService; private Timer timer; private static int rownum = 1; private List gpsData; @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { if(!session.isOpen()){ timer.cancel(); return; } super.handleTextMessage(session, message); session.sendMessage(message); } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { timer = new Timer(true); long delay = 0; rownum = 0; OrderTimeTask orderTimeTask = new OrderTimeTask(session); gpsData = testService.getGpsData(); timer.schedule(orderTimeTask, delay, 1000);// 設定指定的時間time,此處為5s } class OrderTimeTask extends TimerTask{ private WebSocketSession session; public OrderTimeTask(WebSocketSession session){ this.session = session; } @Override public void run() { try { String lonlat = ((Map)gpsData.get(rownum)).get("lonlat").toString(); TextMessage textMessage = new TextMessage(lonlat); handleMessage(session,textMessage); rownum++; if(rownum>gpsData.size()-1){ rownum = 0; } } catch (Exception e){ e.printStackTrace(); } } } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { System.out.println("Connection Closed。"); }}
3、前端擷取位置,並將所有的位置資訊儲存下來,用以渲染回顯路徑。
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>websocket</title> <link rel="stylesheet" type="text/css" href="plugin/ol4/ol.css"/> <style> body, #map { border: 0px; margin: 0px; padding: 0px; width: 100%; height: 100%; font-size: 13px; overflow: hidden; } #map{ background: #000000; } </style></head><body><div id="map"></div><script src="plugin/ol4/ol.js"></script><script type="text/javascript"> function getTdtSource(lyr) { var url = "http://t0.tianditu.com/DataServer?T=" + lyr + "&X={x}&Y={y}&L={z}"; return new ol.source.XYZ({ url: url }); } var base_lyr = new ol.layer.Tile({ source: getTdtSource("vec_w") }); var anno_lyr = new ol.layer.Tile({ source: getTdtSource("cva_w") }); var vector = new ol.layer.Vector({ source: null, style:new ol.style.Style({ stroke: new ol.style.Stroke({ color: '#3a8c4a', width: 4 }), image: new ol.style.Circle({ radius: 8, stroke: new ol.style.Stroke({ color: '#ffffff', width: 2 }), fill: new ol.style.Fill({ color: '#ab2e2a' }) }) }) }); var projection = new ol.proj.Projection({ code: 'EPSG:3857', units: 'm' }); var linesdata = []; var map = new ol.Map({ controls: ol.control.defaults({ attribution: false }), target: 'map', layers: [ base_lyr, anno_lyr, vector ], view: new ol.View({ projection: projection, center: ol.proj.transform([116.397428, 39.90923], 'EPSG:4326', 'EPSG:3857'), zoom: 13 }) }); var websocket = null; //判斷當前瀏覽器是否支援WebSocket if ('WebSocket' in window) { websocket = new WebSocket("ws://localhost:8081/lzugis-web/websocket"); } else { alert('當前瀏覽器 Not support websocket') } //串連發生錯誤的回調方法 websocket.onerror = function () { console.log("WebSocket串連發生錯誤"); }; //串連成功建立的回調方法 websocket.onopen = function () { console.log("WebSocket串連成功"); }; //接收到訊息的回調方法 websocket.onmessage = function (event) { setMessageInnerHTML(event.data); }; //串連關閉的回調方法 websocket.onclose = function () { console.log("WebSocket串連關閉"); }; //監聽視窗關閉事件,當視窗關閉時,主動去關閉websocket串連,防止串連還沒斷開就關閉視窗,server端會拋異常。 window.onbeforeunload = function () { closeWebSocket(); }; //將訊息顯示在網頁上 function setMessageInnerHTML(data) { var features = []; var location = data.split(","); var coord = ol.proj.transform([parseFloat(location[0]),parseFloat(location[1])],"EPSG:4326","EPSG:3857"); linesdata.push(coord); if(linesdata.length>1){ var line = new ol.Feature({ geometry: new ol.geom.LineString(linesdata) }); features.push(line); } var feature = new ol.Feature({ geometry: new ol.geom.Point(coord) }); features.push(feature); var source = new ol.source.Vector({ features: features }); vector.setSource(source); } //關閉WebSocket串連 function closeWebSocket() { websocket.close(); }</script></body></html>
技術部落格
CSDN:http://blog.csdn.NET/gisshixisheng
部落格園:http://www.cnblogs.com/lzugis/
線上教程
https://edu.csdn.net/course/detail/7471
Github
https://github.com/lzugis/
連絡方式
| 類型 |
內容 |
| qq |
1004740957 |
| 公眾號 |
lzugis15 |
| e-mail |
niujp08@qq.com |
| webgis群 |
452117357 |
| Android群 |
337469080 |
| GIS資料視覺效果群 |
458292378 |