OpenLayers源码学习17:图层Layer.HTTPRequest Posted on 2015-03-17 | In OpenLayers学习 | 本来想直接看wmts这个协议的实现, 结果发现Layer.WMTS继承于Layer.Grid 继承于Layer.HTTPRequest东西太多 所以还是按顺序看比较好… 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117OpenLayers.Layer.HTTPRequest = OpenLayers.Class(OpenLayers.Layer, { //哈希因子, 注释说是应对多个wms用的 全代码只有一个 URL_HASH_FACTOR: (Math.sqrt(5) - 1) / 2, // 可能string或者数组 url: null, //哈希的 k/v params: null, // 是否将此图层按base layer转换投影, 默认false reproject: false, //构造, 继承于OpenLayers.Layer. 参数名字挺好不用再解释了... initialize: function(name, url, params, options) { //调用父对象的initialize, 传新参数构造 OpenLayers.Layer.prototype.initialize.apply(this, [name, options]); //处理子类配置 this.url = url; if (!this.params) { this.params = OpenLayers.Util.extend({}, params); } }, //销毁 destroy: function() { //先处理构造时后添加的 this.url = null; this.params = null; //再调用父类的析构 OpenLayers.Layer.prototype.destroy.apply(this, arguments); }, //克隆 clone: function (obj) { if (obj == null) { obj = new OpenLayers.Layer.HTTPRequest(this.name, this.url, this.params, this.getOptions()); } //创建一个新的之后, obj = OpenLayers.Layer.prototype.clone.apply(this, [obj]); return obj; }, setUrl: function(newUrl) { this.url = newUrl; }, // 合并新参数, 触发图层重绘 mergeNewParams:function(newParams) { this.params = OpenLayers.Util.extend(this.params, newParams); var ret = this.redraw(); if(this.map != null) { this.map.events.triggerEvent("changelayer", { layer: this, property: "params" }); } return ret; }, //重绘图层, 强制重绘会mergeNewParams redraw: function(force) { if (force) { return this.mergeNewParams({"_olSalt": Math.random()}); } else { return OpenLayers.Layer.prototype.redraw.apply(this, []); } }, //选择url, //没太看懂, 应该是个哈希算法, 最终取到指定的url[idx] selectUrl: function(paramString, urls) { var product = 1; for (var i=0, len=paramString.length; i<len; i++) { product *= paramString.charCodeAt(i) * this.URL_HASH_FACTOR; product -= Math.floor(product); } return urls[Math.floor(product * urls.length)]; }, // 最终返回url形如: server?key1=value1&key2=value2&key3=value3 getFullRequestString:function(newParams, altUrl) { // 如果没有altUrl就用本图层的url var url = altUrl || this.url; // 克隆this.params, 合并传参中的newParams, 剥离k/v var allParams = OpenLayers.Util.extend({}, this.params); allParams = OpenLayers.Util.extend(allParams, newParams); var paramsString = OpenLayers.Util.getParameterString(allParams); // 如果url是数组, 利用哈希剥离 if (OpenLayers.Util.isArray(url)) { url = this.selectUrl(paramsString, url); } // 忽略大小写 var urlParams = OpenLayers.Util.upperCaseObject(OpenLayers.Util.getParameters(url)); for(var key in allParams) { if(key.toUpperCase() in urlParams) { delete allParams[key]; } } paramsString = OpenLayers.Util.getParameterString(allParams); return OpenLayers.Util.urlAppend(url, paramsString); }, CLASS_NAME: "OpenLayers.Layer.HTTPRequest"});