封装
const MyArcGISLayer = window.L.TileLayer.extend({
options: {
layerType: 'NGS_Topo_US_2D',
url: "http://services.arcgisonline.com/ArcGIS/rest/services/{layerType}/MapServer/tile/{z}/{y}/{x}.jpg",
tileSize: 256,
f: 'image',
format: 'png',
dpi: 96,
transparent: true,
attribution: "ArcGIS"
},
initialize: function (options) {
options = options || {};
window.L.setOptions(this, options);
window.L.stamp(this);
},
onAdd: function (map) {
this._url = this.options.url;
if (this.options.layerType && this._url.indexOf('{layerType}/MapServer/tile/{z}/{y}/{x}') > 0) {
this._url = this.options.url.replace("{layerType}", this.options.layerType);
} else {
this._crs = this.options.crs || map.options.crs;
}
window.L.TileLayer.prototype.onAdd.call(this, map);
},
getTileUrl: function (coords) {
var url = null;
if (this._url.indexOf('tile/{z}/{y}/{x}') > 0) {
var zoom = this._getZoomForUrl();
url = this._url.replace("{x}", coords.x).replace("{y}", coords.y).replace("{z}", zoom);
} else {
var tileBounds = this._tileCoordsToBounds(coords);
var nw = this._crs.project(tileBounds.getNorthWest());
var se = this._crs.project(tileBounds.getSouthEast());
var bbox = nw.x + "," + se.y + "," + se.x + "," + nw.y;
var obj = {
bbox: bbox,
f: this.options.f,
format: this.options.format,
transparent: this.options.transparent,
size: this.options.tileSize + ',' + this.options.tileSize,
bboxsr: this._crs.code.split(":")[1],
imagesr: this._crs.code.split(":")[1],
dpi: 96
};
var str = window.L.Util.getParamString(obj, url);
str = str.slice(1, str.length);
// 两种方式:1、无 export? 表示全部指定加载,2、有则按需加载
if(this._url.indexOf('/export?') > 0) {
url = this._url + '&' + str;
}
else {
url = this._url + '/export?' + str;
}
console.log(str, url);
}
return url;
}
});
export default MyArcGISLayer;
调用
1. 矢量:显示全部
// 显示全部
var options = {
url: 'http://localhost:6080/arcgis/rest/services/china/MapServer',
}
// 添加
var layer = new MyArcGISLayer(options).addTo(map);
2. 矢量:过滤显示,多个用英文逗号隔开
// 过滤显示,多个用英文逗号隔开
var options = {
url: 'http://localhost:6080/arcgis/rest/services/china/MapServer/export?layers=show:0,1',
}
// 添加
var layer = new MyArcGISLayer(options).addTo(map);
3. 瓦片:无法过滤(已验证可用,暂无截图)
// 瓦片,无法过滤
var options = {
url: 'http://localhost/arcgis/rest/services/world/MapServer/tile/{z}/{y}/{x}',
}
// 添加
var layer = new MyArcGISLayer(options).addTo(map);