OpenLayers官方QQ群
群号 259159743 259159561
实时路况信息对于我们来说还是比较重要的,
当然实时路况的发布是需要条件的,我们可以调用别人已经发布好的实时路况
这里以北京实时路况为例,仅作学习 交流之用。请勿商用。。。。否则责任自负!
1.首先我们要有路况发布的服务。可以是瓦片形式的,也可以是wms或其他形式的服务
2.要得到当前路况的时间。
3.叠加到地图之上
4.实时刷新路况图层,这个要用到ajax
下面直接上代码
同样
一 、我们在lib\OpenLayers\Layer目录下面新建一共LTTrafficLayer2.js
新建一共OpenLayers.Layer.LTTrafficLayer2.js类继承自OpenLayers.Layer.TileCache ,重新定义getURL方法
并添加获取获取实时路况时间戳的方法
/** * 对自定义规则切割的图片进行拼装的类 */ OpenLayers.Layer.LTTrafficLayer2 = OpenLayers.Class(OpenLayers.Layer.TileCache, { /*获取图片的地址的定时器*/ timer : null, mapMaxExtent: null, initialize: function (name, url, options) { var tempoptions = OpenLayers.Util.extend({ 'format': 'image/png', isBaseLayer: true }, options); OpenLayers.Layer.TileCache.prototype.initialize.apply(this, [name, url, {}, tempoptions]); this.numZoomLevels = 6; this.maxResolution = 152.87405654296875; this.realtimeurl = url; this.transitionEffect = null; }, destroy : function() { OpenLayers.Layer.TileCache.prototype.destroy.apply(this,arguments); this.destroyTimer(); },refresh: function () { if (this.visibility) { this.clearGrid(); this.redraw();} }, createTimer : function() { function time() {//获取图片路径与时间戳 OpenLayers.loadURL('http://eye.bjjtw.gov.cn/Web-T_bjjt_new/query.do', { serviceType : 'traffic', acode : '110000', cls : 1, type : 0, timestamp : Math.random() }, this, this.success, this.failure); } var _time = OpenLayers.Function.bind(time, this); _time(); this.timer = window.setInterval(_time, 60 * 1000);},destroyTimer : function(){ if (this.timer) { window.clearInterval(this.timer); this.timer = null; } },success : function(resp){ var txt = resp.responseText; if (txt === '') { return; }resp = eval('(' + txt + ')'); if (resp) { var time = resp.sTime+""; var times=time.substring(8,10) + ":" + time.substring(10,12); if(this.visibility){ $('traffictime').innerHTML = times; if($('traffictime').timestmp&&$('traffictime').timestmp!=times){ $('traffictime').timestmp = times; this.refresh();} if(!$('traffictime').timestmp){ $('traffictime').timestmp = times; this.refresh(); } } } }, failure : function(resp) {},/** * 按地图引擎切图规则实现的拼接方式 */ getURL: function (bounds) { var res = this.map.getResolution(); var bbox = this.map.getMaxExtent(); var size = this.tileSize; //计算列号 var tileX = Math.round((bounds.left - bbox.left) / (res * size.w)); //计算行号 var tileY = Math.round((bbox.top - bounds.top) / (res * size.h)); //当前的等级 var tileZ = this.map.zoom; if (tileX < 0) tileX = tileX + Math.round(bbox.getWidth() / bounds.getWidth()); if (tileY < 0) tileY = tileY + Math.round(bbox.getHeight() / bounds.getHeight()); return this.getTilePic(tileX, tileY, tileZ); },clone: function (obj) {if (obj == null) { obj = new OpenLayers.Layer.LTTrafficLayer2(this.name, this.url, this.options); } obj = OpenLayers.Layer.LTTrafficLayer2.prototype.clone.apply(this, [obj]); return obj; }, //请求加随机数,解决ie6下图片缓存不更新问题 getTilePic: function (tileX, tileY, tileZ) { var dir = ''; if (tileZ > 6) { var delta = Math.pow(2, tileZ - 5); var rowDir = 'R' + Math.floor(tileY / delta); var colDir = 'C' + Math.floor(tileX / delta); dir = tileZ + "/" + rowDir + "/" + colDir + "/"; } else { dir = tileZ + '/'; }var tileNo = tileZ + "-" + tileX + "-" + tileY; var sUrl = this.url + dir + tileNo + '.png?r='; var d = Math.random(); sUrl += d; //alert(sUrl); return sUrl; }, CLASS_NAME: "OpenLayers.Layer.LTTrafficLayer2" });
二、在lib文件夹下的OpenLayers.js 中加载js文件的函数中添加"OpenLayers/Layer/LTTrafficLayer2.js"
三、新建一个html页面
添加触发实时路况的checkbox的函数onDispTraffic
function onDispTraffic(obj)
{
if(trafficLayer.visibility){
trafficLayer.setVisibility(false);
trafficLayer.destroyTimer();
$('traffictime').innerHTML="";
if($('showTraCheck').checked)
$('showTraCheck').checked = false;
}else{
trafficLayer.setVisibility(true);
trafficLayer.createTimer();
}
}
四、在map容器中添加实时路况控制的div层
<div style="position:absolute; right:5px; top:5px; color:#000; z-index:1000;">
<input type="checkbox" id="showTraCheck" /><span id="spantra"><font style="font-weight:bold;color:#000000">显示实时路况</font></span>
<font class="traffictext" id="traffictime" ></font>
</div>
整体代码如下
<html xmlns="http://www.w3.org/1999/xhtml"> <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"><meta name="apple-mobile-web-app-capable" content="yes"><title>OpenLayers TileCache Example</title><link rel="stylesheet" href="img/style.css" type="text/css"> <script src="lib/OpenLayers.js"></script><script type="text/javascript"> var map, layer,marker; var layerOptions=null; var trafficLayer; OpenLayers.INCHES_PER_UNIT["千米"] = OpenLayers.INCHES_PER_UNIT["km"]; OpenLayers.INCHES_PER_UNIT["米"] = OpenLayers.INCHES_PER_UNIT["m"]; OpenLayers.INCHES_PER_UNIT["英里"] = OpenLayers.INCHES_PER_UNIT["mi"]; OpenLayers.INCHES_PER_UNIT["英寸"] = OpenLayers.INCHES_PER_UNIT["ft"]; function init(){map = new OpenLayers.Map( $('map'), {controls: [], maxExtent: new OpenLayers.Bounds(-20037508,-20037508,20037508,20037508), maxResolution:156543.03125, numZoomLevels:19, projection: new OpenLayers.Projection("EPSG:900913"), displayProjection: new OpenLayers.Projection("EPSG:4326"), units:'m'}); var mapabc = new OpenLayers.Layer.MapABC( "Mapabc", ["http://emap0.is.autonavi.com/appmaptile?","http://emap1.is.autonavi.com/appmaptile?","http://emap2.is.autonavi.com/appmaptile?","http://emap3.is.autonavi.com/appmaptile?"], layerOptions ); trafficLayer=new OpenLayers.Layer.LTTrafficLayer2("实时路况", "http://219.232.196.52:8081/", {isBaseLayer: false,visibility:false} ); map.addLayers([mapabc,trafficLayer]); map.addControl( new OpenLayers.Control.ScaleLine({ topOutUnits:"千米", topInUnits:"米", bottomOutUnits:"英里", bottomInUnits:"英寸" //如果底部单位为空 则不显示比例尺下部分 })); map.addControl(new OpenLayers.Control.PanZoomBar({'zoomWorldIcon':true})); map.addControl( new OpenLayers.Control.KeyboardDefaults()); map.setCenter(new OpenLayers.LonLat(116.397128, 39.916527).transform( new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject() ), 11 ); $('showTraCheck').checked = false; } OpenLayers.Util.onImageLoadErrorColor = "transparent"; //OpenLayers.Util.onImageLoadErrorColor = "pink"function onDispTraffic(obj) { if(trafficLayer.visibility){ trafficLayer.setVisibility(false); trafficLayer.destroyTimer();$('traffictime').innerHTML=""; if($('showTraCheck').checked) $('showTraCheck').checked = false; }else{ trafficLayer.setVisibility(true); trafficLayer.createTimer();}}</script> <body οnlοad="init()"><div id="map" style="position:relative;width: 100%;height: 100%;border: 1px solid #ccc;"> <div style="position:absolute; right:5px; top:5px; color:#000; z-index:1000;"><input type="checkbox" id="showTraCheck" οnclick="onDispTraffic(this);" /><span id="spantra"><font style="font-weight:bold;color:#000000">显示实时路况</font></span> <font class="traffictext" id="traffictime" ></font> </div> </div> </body></html>
效果如下
更多信息 请关注openlayers中文官方站 http://www.openlayers.cn