2011-01-19 10:50 4735人阅读 (11)
说到实时监控,我们不能不承认Openlayers功能的确非常强大。Openlayers中通过很多方式都能实现实时监控。我讲讲我的实现方式。
我的方式很简单:页面发起异步请求;服务端程序将请求结果处理成GeoJSON串回传至请求页面;请求页面通过OpenLayers提供的OpenLayers.Format.GeoJSON解析GeoJSON串,将结果展现到地图上。
下面的示例显示:实时获得油机的位置数据,展示到页面上。
页面程序:
- //初始地图
- function init(){
- ......
- vectors = new OpenLayers.Layer.Vector(...);
- geojson = new OpenLayers.Format.GeoJSON();
- map.addLayer(vectors);
- }
- //通过DWR异步取得GeoJSon串,交由OpenLayers.Format.GeoJSON来处理.
- function locorie(){
- //异步发出请求
- dwrService.orie(orieSeri,function(data){
- //通过OpenLayers.Format.GeoJSON处理服务端提供的GenJSon串
- var features = geojson.read(data,"FeatureCollection");
- if(features) {
- //将结果展示到地图上
- vectors.addFeatures(features);
- }
- });
- }
- //十秒更新一次数据
- function startOrie(){
- var t=setTimeout("locorie();startOrie();",10000);
- }
服务端程序:
- public String[] orie(String orieSeri) {
- String orieStr = "";
- boolean state = true;
- if (null == orieStr || "".equals(orieSeri)) {
- state = false;
- }
- int dataSeri = Integer.parseInt(orieSeri);
- List<Location> list = null;
- if (state) {
- // 获得dataSeri之后的位置数据 Location.getDataSeri >= dataSeri
- list = locDao.findLocByFlow(dataSeri);
- }
- if (state && (list == null || list.size() == 0)) {
- // 没有数据
- state = false;
- }
- if (state&&(list.size() == 1 && dataSeri == list.get(0).getDataSeri()
- .intValue())) {
- // 没有新的数据
- state = false;
- }
- if (state) {
- LineString line = new LineString();
- StringBuffer geo = new StringBuffer();
- Point pointEnd = new Point();
- Feature feaPoint = new Feature(pointEnd);
- Map<String, String> propoint = new HashMap<String, String>();
- feaPoint.setProperties(propoint);
- for (int i = 0; i < list.size(); i++) {
- geo.append("[" + list.get(i).getCurLoc() + "]");
- if (i != (list.size() - 1)) {
- geo.append(",");
- }
- }
- line.setLine(geo.toString());
- Feature feaLine = new Feature(line);
- Map<String, String> properties = new HashMap<String, String>();
- properties.put("color", "#1A60CA");
- feaLine.setProperties(properties);
- List<Component> components = new ArrayList<Component>();
- components.add(feaLine);
- components.add(feaPoint);
- FeatureCollection feaCol = new FeatureCollection(components);
- orieStr = feaCol.draw();
- }
- }
服务器端提供的数据格式如下:
- //一条线
- {
- "type":"FeatureCollection",
- "features":[{
- "type":"Feature",
- "geometry":{
- "type":"LineString",
- "coordinates":[[42.895131111145, 22.148587703705],[43.895131111145, 23.148587703705]]}}]
- }
服务器端生成json串,我用装饰者模式写了一个模块,只要调用这个模块的API就会生成需要的Json串。