作者:bsy
前言
当拥有一张很大的地图,但是希望可以按照一定的需求,只显示一部分地图。针对这个需求,我们可以通过对地图进行地图裁剪,只显示裁剪部分的地图,既不会对地图进行修改,也可以按需显示,不失为一种可行方案。
接下来,我将以SuperMap iClient for Leaflet为例,进行地图裁剪操作。
1、数据准备
地图:https://iserver.supermap.io/iserver/services/map-world/rest/maps/World
面数据:Countries@World#2图层中"NAME = ‘中国’"的面对象
参数:
(其中clipRegion在Leaflet中支持的格式为L.Polygon和GeoJSONObject)
2、查询面数据
var param = new L.supermap.QueryBySQLParameters({
queryParams: {
name: "Countries@World.2",
attributeFilter: "SMID = 234"
}
});
new L.supermap.QueryService(url).queryBySQL(param, function (serviceResult) {
var result = serviceResult.result;
geoRegion = L.geoJSON(result.recordsets[0].features.features[0]);
});
3、请求地图
new L.supermap.TiledMapLayer(url, {
clipRegionEnabled: true,
clipRegion: geoRegion,
}).addTo(map);
特别特别需要注意的地方来了
如果直接这样传入clipRegion参数,会出现报错,可以看到瓦片请求失败。原因是:因为clipRegion的节点过多,导致GET请求体过长直接报错。解决方法也很简单,用POST模拟GET。
这里介绍的方法是重写Leaflet请求瓦片的方法,用POST模拟GET,实现代码如下:
L.TileLayer.include({
createTile: function(coords, done) {
var tile = document.createElement('img');
L.DomEvent.on(tile, 'load', L.Util.bind(this._tileOnLoad, this, done, tile));
L.DomEvent.on(tile, 'error', L.Util.bind(this._tileOnError, this, done, tile));
if (this.options.crossOrigin || this.options.crossOrigin === '') {
tile.crossOrigin = this.options.crossOrigin === true ? '' : this.options.crossOrigin;
}
tile.alt = '';
tile.setAttribute('role', 'presentation');
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.addEventListener('loadend', function(evt) {
var data = this.response;
if (data !== undefined) {
tile.src = URL.createObjectURL(data);
} else {
tile.setState('error');
}
});
xhr.addEventListener('error', function() {
tile.setState('error');
});
var tileURL = this.getTileUrl(coords);
xhr.open('POST', tileURL.split('?')[0]+'?_method=GET');
var parameters =tileURL.split('?')[1].split('&');
var obj ={};
for(var i=0;i<parameters.length;i++){
var key = parameters[i].split('=')[0];
var value = parameters[i].split('=')[1]
obj[key]= value;
}
xhr.send(JSON.stringify(obj));
return tile;
}
});
new L.supermap.TiledMapLayer(url, {
clipRegionEnabled: true,
clipRegion: geoRegion,
}).addTo(map);
4、效果展示

本文介绍如何使用SuperMapiClient for Leaflet通过地图裁剪技术仅显示特定区域的地图,包括数据准备、查询面数据、请求地图及效果展示等步骤。
607

被折叠的 条评论
为什么被折叠?



