Skip to content

Commit

Permalink
【feature】mapboxgl出图支持传自定义的requestParameters; review by luox
Browse files Browse the repository at this point in the history
  • Loading branch information
xiongjiaojiao committed Dec 19, 2024
1 parent 7b27cfb commit 3918cde
Show file tree
Hide file tree
Showing 11 changed files with 311 additions and 39 deletions.
3 changes: 2 additions & 1 deletion src/common/mapping/MapStyle.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ export function createMapStyleExtending(SuperClass, { MapManager, crsManager })
url: proxy ? `${proxy}${encodeURIComponent(url)}` : url,
credentials: this.webMapService.handleWithCredentials(proxy, url, this.options.withCredentials || false)
? 'include'
: undefined
: undefined,
...(this.options.tileTransformRequest && this.options.tileTransformRequest(url))
};
};
}
Expand Down
4 changes: 3 additions & 1 deletion src/common/mapping/WebMapV2.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export function createWebMapV2Extending(SuperClass, { MapManager, mapRepo, crsMa
this._cacheLayerId = new Map();
this._layerTimerList = [];
this._appendLayers = false;
this._tileTransformRequest = options.tileTransformRequest;
}

async initializeMap(mapInfo, map) {
Expand Down Expand Up @@ -303,7 +304,8 @@ export function createWebMapV2Extending(SuperClass, { MapManager, mapRepo, crsMa
const proxy = this.webMapService.handleProxy('image');
return {
url: url,
credentials: this.webMapService.handleWithCredentials(proxy, url, false) ? 'include' : undefined
credentials: this.webMapService.handleWithCredentials(proxy, url, false) ? 'include' : undefined,
...(this._tileTransformRequest && this._tileTransformRequest(url))
};
}
return { url };
Expand Down
64 changes: 36 additions & 28 deletions src/common/mapping/WebMapV3.js
Original file line number Diff line number Diff line change
Expand Up @@ -235,13 +235,8 @@ export function createWebMapV3Extending(SuperClass, { MapManager, mapRepo, crsMa
const copyLayer = { ...matchLayer, ...layerInfo, id: copyLayerId };
if (l7LayerUtil.isL7Layer(copyLayer)) {
const layers = [copyLayer];
await l7LayerUtil.addL7Layers({
map: this.map,
webMapInfo: { ...this._mapInfo, layers, sources: this._mapInfo.sources },
l7Layers: layers,
spriteDatas: this._spriteDatas,
options: this.options
});
const params = this._getAddL7LayersParams(layers, this._mapInfo.sources, layers);
await l7LayerUtil.addL7Layers(params);
} else {
if (typeof copyLayer.source === 'object') {
this.map.addSource(copyLayer.id, copyLayer.source);
Expand Down Expand Up @@ -287,18 +282,8 @@ export function createWebMapV3Extending(SuperClass, { MapManager, mapRepo, crsMa
const fontFamilys = this._getLabelFontFamily();
// 初始化 map
const mapOptions = {
transformRequest: (url, resourceType) => {
const res = { url };
if (
resourceType === 'Tile' &&
this.options.iportalServiceProxyUrl &&
url.indexOf(this.options.iportalServiceProxyUrl) >= 0
) {
res.credentials = 'include';
}
return res;
},
...this.mapOptions,
transformRequest: this._getTransformRequest(),
container: this.options.target,
crs: this._baseProjection,
center,
Expand All @@ -324,6 +309,23 @@ export function createWebMapV3Extending(SuperClass, { MapManager, mapRepo, crsMa
});
}

_getTransformRequest() {
if (this.mapOptions.transformRequest) {
return this.mapOptions.transformRequest;
}
return (url, resourceType) => {
if (resourceType === 'Tile') {
const withCredentials = this.options.iportalServiceProxyUrl && url.indexOf(this.options.iportalServiceProxyUrl) >= 0;
return {
url: url,
credentials: withCredentials ? 'include' : undefined,
...(this.options.tileTransformRequest && this.options.tileTransformRequest(url))
};
}
return { url };
}
}

_registerMapCRS(mapInfo) {
const { crs } = mapInfo;
let epsgCode = crs;
Expand Down Expand Up @@ -423,16 +425,8 @@ export function createWebMapV3Extending(SuperClass, { MapManager, mapRepo, crsMa
});
const l7Layers = layers.filter((layer) => l7LayerUtil.isL7Layer(layer));
if (l7Layers.length > 0) {
await l7LayerUtil.addL7Layers({
map: this.map,
webMapInfo: { ...this._mapInfo, layers, sources },
l7Layers,
spriteDatas: this._spriteDatas,
options: {
...this.options,
emitterEvent: this.fire.bind(this)
}
});
const params = this._getAddL7LayersParams(layers, sources, l7Layers);
await l7LayerUtil.addL7Layers(params);
}
this._createLegendInfo();
this._sendMapToUser();
Expand All @@ -442,6 +436,20 @@ export function createWebMapV3Extending(SuperClass, { MapManager, mapRepo, crsMa
}
}

_getAddL7LayersParams(layers, sources, l7Layers) {
return {
map: this.map,
webMapInfo: { ...this._mapInfo, layers, sources },
l7Layers,
spriteDatas: this._spriteDatas,
options: {
...this.options,
emitterEvent: this.fire.bind(this),
transformRequest: this._getTransformRequest()
}
}
}

/**
* @private
* @function WebMapV3.prototype._setUniqueId
Expand Down
14 changes: 8 additions & 6 deletions src/common/mapping/utils/L7LayerUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -701,12 +701,14 @@ export function L7LayerUtil(config) {
sourceLayer
}
};
if (isIportalProxyServiceUrl(result.data, options)) {
Object.assign(result.parser, {
requestParameters: {
credentials: 'include'
}
});
const requestParameters = options.transformRequest(result.data, 'Tile');
if (requestParameters) {
if (requestParameters.credentials) {
result.parser.requestParameters = { credentials: requestParameters.credentials };
}
if (requestParameters.headers) {
result.parser.requestParameters = { ...result.parser.requestParameters, headers: requestParameters.headers };
}
}
return result;
}
Expand Down
79 changes: 78 additions & 1 deletion test/common/mapping/utils/L7LayerUtilSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ describe('L7LayerUtil', () => {
const options = {
withCredentials: true,
server: 'http://localhost:8190/iportal/',
emitterEvent: function() {}
emitterEvent: function() {},
transformRequest: function() {}
};

const addOptions = {
Expand Down Expand Up @@ -513,6 +514,7 @@ describe('L7LayerUtil', () => {
webMapInfo: { ...mapstudioWebMap_L7LayersRes, layers, sources },
l7Layers: layers,
options: {
...addOptions.options,
withCredentials: false,
server: '/iportal/',
iportalServiceProxyUrl: 'http://localhost:8195/portalproxy'
Expand Down Expand Up @@ -603,4 +605,79 @@ describe('L7LayerUtil', () => {
expect(result.field).toEqual(['smpid', '新建字段']);
expect(result.values).not.toBeUndefined();
});

it('add mvt source and requestParameters', (done) => {
const layers = [
{
filter: ['all', ['==', 'smpid', 1]],
layout: {
'text-z-offset': 200000,
'text-letter-spacing': 0,
visibility: 'visible',
'text-field': '{smpid}',
'text-anchor': 'center',
'text-size': 36,
'text-allow-overlap': true
},
metadata: {
MapStudio: {
title: 'ms_label_县级行政区划_1719818803020_5'
}
},
maxzoom: 24,
paint: {
'text-halo-color': '#242424',
'text-halo-blur': 2,
'text-color': '#FFFFFF',
'text-halo-width': 1,
'text-opacity': 0.9,
'text-translate': [0, 0]
},
source: 'ms_label_县级行政区划_1719818803020_5_source',
'source-layer': '932916417$geometry',
id: 'ms_label_县级行政区划_1719818803020_5',
type: 'symbol',
minzoom: 0
}
];
const sources = {
ms_label_县级行政区划_1719818803020_5_source: {
tiles: [
'http://localhost:8190/iportal/services/../web/datas/932916417/structureddata/pointonsurface/tiles/{z}/{x}/{y}.mvt?epsgCode=3857&returnedFieldNames=%5B%22smpid%22%2C%22pac%22%2C%22Video%22%2C%22SmUserID%22%2C%22name%22%2C%22Image%22%2C%22objectid%22%2C%22URL%22%5D&geometryFieldName=geometry'
],
bounds: [102.98962307000005, 30.090978575000065, 104.89626180000005, 31.437765225000078],
type: 'vector'
}
};
const tileCustomRequestHeaders = { 'Authorization': 'test token' };
const nextOptions = {
...addOptions,
webMapInfo: { ...mapstudioWebMap_L7LayersRes, layers, sources },
l7Layers: layers,
options: {
...addOptions.options,
transformRequest: function() {
return {
credentials: 'include',
headers: tileCustomRequestHeaders
}
}
}
};
const spy1 = spyOn(nextOptions.map, 'addLayer').and.callThrough();
const spy2 = spyOn(L7, 'PointLayer').and.callFake(mockL7.PointLayer);
l7LayerUtil.addL7Layers(nextOptions).then(() => {
expect(nextOptions.map.addLayer.calls.count()).toEqual(1);
expect(layerMaplist['ms_label_县级行政区划_1719818803020_5']).toBeTruthy();
const matchLayer = layerMaplist['ms_label_县级行政区划_1719818803020_5'].getLayer();
expect(matchLayer.featureId).toBe('smpid');
const matchL7layer = layerMaplist['ms_label_县级行政区划_1719818803020_5'].getL7Layer();
expect(matchL7layer.layerSource.parser.requestParameters).not.toBeUndefined();
expect(matchL7layer.layerSource.parser.requestParameters.credentials).toBe('include');
expect(matchL7layer.layerSource.parser.requestParameters.headers).toEqual(tileCustomRequestHeaders);
spy1.calls.reset();
spy2.calls.reset();
done();
});
});
});
49 changes: 49 additions & 0 deletions test/mapboxgl/mapping/WebMapSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1399,4 +1399,53 @@ describe('mapboxgl_WebMap', () => {
});
});
});

it('test transformRequest when url includes iportalproxy', (done) => {
const iportalServiceProxyUrl = 'http://localhost:8195/portalproxy';
const tileCustomRequestHeaders = { 'Authorization': 'test token' };
const commonOption = {
server: 'http://fack:8190/iportal/',
target: 'map',
withCredentials: false,
iportalServiceProxyUrlPrefix: iportalServiceProxyUrl,
tileTransformRequest: (url) => {
if (url.includes(iportalServiceProxyUrl)) {
return { headers: tileCustomRequestHeaders };
}
}
};
const mapOptions = {
style: {
version: 8,
sources: {
baseLayer: {
type: 'raster',
tiles: ['https://test'],
tileSize: 256
}
},
layers: [{ id: 'baseLayer', type: 'raster', source: 'baseLayer' }]
},
center: [107.7815, 39.9788],
zoom: 5,
renderWorldCopies: false,
crs: 'EPSG:3857',
minzoom: 0,
maxzoom: 22
};
datavizWebmap = new WebMap('', { ...commonOption }, { ...mapOptions });
datavizWebmap.on('mapinitialized', ({ map }) => {
let mockTileUrl =
'http://localhost:8195/portalproxy/7c851958ab40a5e0/iserver/services/map_world1_y6nykx3f/rest/maps/World1/tileimage.png?scale=6.760654286410619e-9&x=1&y=0&width=256&height=256&transparent=true&redirect=false&cacheEnabled=true&origin=%7B%22x%22%3A-180%2C%22y%22%3A90%7D';
let transformed = datavizWebmap._handler.mapOptions.transformRequest(mockTileUrl, 'Tile');
expect(transformed.credentials).toBe('include');
expect(transformed.headers).toEqual(tileCustomRequestHeaders);
expect(transformed.url).toBe(mockTileUrl);
mockTileUrl = 'https://maptiles.supermapol.com/iserver/services/map_China/rest/maps/China_Dark';
transformed = map.options.transformRequest(mockTileUrl, 'Tile');
expect(transformed.credentials).toBeUndefined();
expect(transformed.headers).toBeUndefined();
done();
});
});
});
33 changes: 33 additions & 0 deletions test/mapboxgl/mapping/WebMapV2Spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2047,6 +2047,39 @@ describe('mapboxgl_WebMapV2', () => {
});
});

it('transformRequest when url includes iportalproxy', (done) => {
spyOn(FetchRequest, 'get').and.callFake((url) => {
if (url.indexOf('web/datas/1920557079/content.json') > -1) {
return Promise.resolve(new Response(layerData_CSV));
}
return Promise.resolve(new Response(JSON.stringify({})));
});
const iportalServiceProxyUrl = 'http://localhost:8195/portalproxy';
const tileCustomRequestHeaders = { 'Authorization': 'test token' };
datavizWebmap = new WebMap(vectorLayer_line, {
...commonOption,
iportalServiceProxyUrlPrefix: iportalServiceProxyUrl,
tileTransformRequest: (url) => {
if (url.includes(iportalServiceProxyUrl)) {
return { headers: tileCustomRequestHeaders };
}
}
});
datavizWebmap.on('mapcreatesucceeded', ({ map }) => {
expect(map).not.toBeUndefined();
let mockTileUrl =
'http://localhost:8195/portalproxy/7c851958ab40a5e0/iserver/services/map_world1_y6nykx3f/rest/maps/World1/tileimage.png?scale=6.760654286410619e-9&x=1&y=0&width=256&height=256&transparent=true&redirect=false&cacheEnabled=true&origin=%7B%22x%22%3A-180%2C%22y%22%3A90%7D';
let transformed = map.options.transformRequest(mockTileUrl, 'Tile');
expect(transformed.credentials).toBe('include');
expect(transformed.headers).toEqual(tileCustomRequestHeaders);
mockTileUrl = 'https://maptiles.supermapol.com/iserver/services/map_China/rest/maps/China_Dark';
transformed = map.options.transformRequest(mockTileUrl, 'Tile');
expect(transformed.credentials).toBeUndefined();
expect(transformed.headers).toBeUndefined();
done();
});
});

it('layerFilter', (done) => {
spyOn(FetchRequest, 'get').and.callFake((url) => {
if (url.indexOf('web/datas/1920557079/content.json') > -1) {
Expand Down
11 changes: 10 additions & 1 deletion test/mapboxgl/mapping/WebMapV3Spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -733,20 +733,29 @@ describe('mapboxgl-webmap3.0', () => {
});
const spyTest = spyOn(MapManagerUtil, 'default').and.callFake(mbglmap);
const mapInfo = JSON.parse(mapstudioWebMap_raster);
const iportalServiceProxyUrl = 'http://localhost:8195/portalproxy';
const tileCustomRequestHeaders = { 'Authorization': 'test token' };
mapstudioWebmap = new WebMap(mapInfo, {
server: server,
target: 'map',
iportalServiceProxyUrl: 'http://localhost:8195/portalproxy'
iportalServiceProxyUrl,
tileTransformRequest: (url) => {
if (url.includes(iportalServiceProxyUrl)) {
return { headers: tileCustomRequestHeaders };
}
}
});
mapstudioWebmap.on('mapinitialized', ({ map }) => {
expect(map).not.toBeUndefined();
let mockTileUrl =
'http://localhost:8195/portalproxy/7c851958ab40a5e0/iserver/services/map_world1_y6nykx3f/rest/maps/World1/tileimage.png?scale=6.760654286410619e-9&x=1&y=0&width=256&height=256&transparent=true&redirect=false&cacheEnabled=true&origin=%7B%22x%22%3A-180%2C%22y%22%3A90%7D';
let transformed = map.options.transformRequest(mockTileUrl, 'Tile');
expect(transformed.credentials).toBe('include');
expect(transformed.headers).toEqual(tileCustomRequestHeaders);
mockTileUrl = 'https://maptiles.supermapol.com/iserver/services/map_China/rest/maps/China_Dark';
transformed = map.options.transformRequest(mockTileUrl, 'Tile');
expect(transformed.credentials).toBeUndefined();
expect(transformed.headers).toBeUndefined();
spyTest.calls.reset();
done();
});
Expand Down
Loading

0 comments on commit 3918cde

Please sign in to comment.