forked from SuperMap/iClient-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInitMap.js
More file actions
275 lines (265 loc) · 9.38 KB
/
InitMap.js
File metadata and controls
275 lines (265 loc) · 9.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import mapboxgl from 'mapbox-gl';
import { MapService } from '../services/MapService';
import { FetchRequest } from '@supermapgis/iclient-common/util/FetchRequest';
import { InitMapServiceBase, isPlaneProjection, getZoom, getTileset, getTileFormat } from '@supermapgis/iclient-common/iServer/InitMapServiceBase';
import { Util } from '@supermapgis/iclient-common/commontypes/Util';
import { SecurityManager } from '@supermapgis/iclient-common/security/SecurityManager';
import proj4 from 'proj4';
/**
* @function initMap
* @description 根据 SuperMap iServer 服务参数,创建地图与图层。目前仅支持SuperMap iServer 地图服务。
* @category BaseTypes Util
* @version 11.1.1
* @param {number} url - rest 地图服务地址。例如: http://{ip}:{port}/iserver/services/map-world/rest/maps/World。
* @param {Object} options - 参数。
* @param {Object} [options.type] - 地图类型。可选值 'raster' | 'vector-tile'。默认 'raster'。
* @param {Object} [options.mapOptions] - 地图配置,参数设置参考 {@link https://docs.mapbox.com/mapbox-gl-js/api/map/}。
* @param {string} [options.proxy] - 服务代理地址。
* @param {boolean} [options.withCredentials=false] - 请求是否携带 cookie。
* @param {boolean} [options.crossOrigin] - 是否允许跨域请求。
* @param {Object} [options.headers] - 请求头。
* @returns {Object} 实例对象。对象包括地图实例。
* @usage
* ```
* // 浏览器
* <script type="text/javascript" src="{cdn}"></script>
* <script>
* const initMap = {namespace}.initMap(url, { mapOptions });
*
* </script>
* // ES6 Import
* import { initMap } from '{npm}';
*
* initMap(url, { mapOptions })
* ```
* */
export function initMap(url, options = {}) {
const initMapService = new InitMapServiceBase(MapService, url, options);
return initMapService.getMapInfo(async (res, resolve, reject) => {
try {
if (res.type === 'processCompleted') {
const {
dynamicProjection,
prjCoordSys: { epsgCode, type }
} = res.result;
if (isPlaneProjection(type)) {
reject(new Error('mapbox-gl cannot support plane coordinate system.'));
return;
}
if (epsgCode !== 3857 && !dynamicProjection && !mapboxgl.CRS) {
reject(
new Error(
`The EPSG code ${epsgCode} needs to include mapbox-gl-enhance.js. Refer to the example: https://iclient.supermap.io/examples/mapboxgl/editor.html#mvtVectorTile_2362`
)
);
return;
}
const mapOptions = await createMapOptions(url, res.result, { ...options, initMapService });
const map = new mapboxgl.Map(mapOptions);
if (!map.loaded()) {
map.on('load', () => {
resolve({ map });
});
} else {
resolve({ map });
}
return;
}
reject(new Error('Fetch mapService is failed.'));
} catch (error) {
reject(error);
}
});
}
/**
* @private
* @function getCrsExtent
* @description 获取当前坐标系范围,[左,下,右,上]。
* @param {Object|Array} extent -坐标系范围。
* @returns {Array}
*/
function getCRSExtent(extent) {
if (extent instanceof Array) {
return extent;
}
if (extent.leftBottom && extent.rightTop) {
return [extent.leftBottom.x, extent.leftBottom.y, extent.rightTop.x, extent.rightTop.y];
}
return [extent.left, extent.bottom, extent.right, extent.top];
}
/**
* @private
* @function defineCRSByWKT
* @description 定义crs。
* @param {string} crsName - 投影名称。
* @param {string} wkt - wkt。
* @param {Object} extent - 坐标系范围。
* @returns {string}
*/
function defineCRSByWKT(crsName, wkt, extent) {
const crsExtent = getCRSExtent(extent);
const defineCRS = new mapboxgl.CRS(crsName, wkt, crsExtent);
return defineCRS;
}
/**
* @private
* @function transformMapCenter
* @description 转换center。
* @param {Object} mapInfoCenter - 中心点。
* @param {string} baseProjection - 坐标投影。
* @returns {Array}
*/
function transformMapCenter(mapInfoCenter, sourceProjection) {
let center = mapInfoCenter;
if (sourceProjection === 'EPSG:3857') {
return proj4(sourceProjection, 'EPSG:4326', mapInfoCenter);
}
if (sourceProjection !== 'EPSG:4326') {
return mapboxgl.proj4(sourceProjection, 'EPSG:4326', mapInfoCenter);
}
return center;
}
/**
* @private
* @function getVectorTileCRSExtent
* @description 获取矢量瓦片坐标系范围。
* @param {string} vectorStyleUrl - 矢量瓦片 style json 服务地址。
* @param {string} restMapUrl - 矢量瓦片 rest 地图服务地址。
* @returns {Object}
*/
async function getVectorTileCRSExtent(vectorStyleUrl, restMapUrl) {
try {
const vectorStyleDataRes = await FetchRequest.get(vectorStyleUrl);
const vectorStyleData = await vectorStyleDataRes.json();
if (vectorStyleData.metadata && vectorStyleData.metadata.indexbounds) {
return { extent: vectorStyleData.metadata.indexbounds };
}
const vectorExtentDataRes = await FetchRequest.get(Util.urlPathAppend(restMapUrl, 'prjCoordSys/projection/extent.json'));
const vectorExtentData = await vectorExtentDataRes.json();
return { extent: vectorExtentData, center: vectorStyleData.center };
} catch (error) {
return { extent: [] };
}
}
/**
* @private
* @function createMapOptions
* @description 获取地图参数。
* @param {string} url - rest 地图服务地址。
* @param {Object} resetServiceInfo - rest 地图服务信息。
* @param {Object} [options] - 参数。
* @param {string} [options.type] - 服务代理地址。
* @param {Object} [options.mapOptions] - 地图配置。
* @param {Object} [options.initMapService] - InitMapServiceBase 实例。
* @returns {Object} mapParams。
*/
async function createMapOptions(url, resetServiceInfo, options) {
if (options.type && !['raster', 'vector-tile'].includes(options.type)) {
return Promise.reject(new Error('type must be "raster" or "vector-tile".'));
}
const sourceType = options.type || 'raster';
const mapOptions = options.mapOptions || {};
const {
prjCoordSys: { epsgCode },
bounds,
center,
dpi = 96,
coordUnit,
scale
} = resetServiceInfo;
let mapCenter = center ? [center.x, center.y] : [0, 0];
let crs = `EPSG:${epsgCode}`;
let extent = bounds;
let tileUrl =
sourceType === 'vector-tile'
? Util.urlAppend(Util.urlPathAppend(url, 'tileFeature/vectorstyles.json'), 'type=MapBox_GL&styleonly=true&tileURLTemplate=ZXY')
: url;
tileUrl = SecurityManager.appendCredential(tileUrl);
let nonEnhanceExtraInfo = {};
let enhanceExtraInfo = {};
let zoom;
let tileSize = 512;
let tileFormat = 'png';
if (mapboxgl.CRS) {
const baseProjection = crs;
const wkt = await options.initMapService.getWKT();
let vectorTileInfo;
if (sourceType === 'vector-tile') {
vectorTileInfo = await getVectorTileCRSExtent(tileUrl, url);
extent = vectorTileInfo.extent;
}
crs = defineCRSByWKT(baseProjection, wkt, extent);
if (sourceType === 'raster') {
enhanceExtraInfo.rasterSource = 'iserver';
enhanceExtraInfo.dpi = dpi;
}
if (vectorTileInfo && vectorTileInfo.center) {
mapCenter = vectorTileInfo.center;
} else {
mapCenter = transformMapCenter(mapCenter, baseProjection);
}
const tilesets = await options.initMapService.getTilesets();
const tileset = getTileset(tilesets.result, { prjCoordSys: resetServiceInfo.prjCoordSys, tileType: 'Image' });
if (tileset) {
tileFormat = getTileFormat(tileset);
const maxWidth = Math.max(tileset.bounds.right - tileset.originalPoint.x, tileset.originalPoint.y - tileset.bounds.bottom);
const tileCount = maxWidth / (tileset.resolutions[0] * 256);
zoom = Math.ceil(Math.log2(tileCount));
const closestTileCount = Math.pow(2, zoom);
const width = closestTileCount * 256 * tileset.resolutions[0];
const crsBounds = [
tileset.originalPoint.x,
tileset.originalPoint.y - width,
tileset.originalPoint.x + width,
tileset.originalPoint.y
];
crs = new mapboxgl.CRS(baseProjection, crsBounds);
zoom = zoom - 1;
tileSize = tileset.tileWidth;
}
} else {
crs = 'EPSG:3857';
mapCenter = transformMapCenter(mapCenter, crs);
if (sourceType === 'raster') {
const tileSize = 256;
nonEnhanceExtraInfo.tileSize = tileSize;
const transparent = mapOptions.transparent !== false;
tileUrl = Util.urlAppend(Util.urlPathAppend(tileUrl, 'zxyTileImage.png'), `z={z}&x={x}&y={y}&width=${tileSize}&height=${tileSize}&transparent=${transparent}`);
}
}
if (zoom === undefined) {
zoom = getZoom({ scale, dpi, coordUnit }, extent);
}
return {
container: 'map',
crs,
center: mapCenter,
zoom,
style:
sourceType === 'raster'
? {
version: 8,
sources: {
'smaples-source': {
format: tileFormat,
tileSize,
type: 'raster',
tiles: [tileUrl],
...nonEnhanceExtraInfo,
...enhanceExtraInfo
}
},
layers: [
{
id: 'sample-layer',
type: 'raster',
source: 'smaples-source',
minzoom: 0,
maxzoom: 22
}
]
}
: tileUrl,
...mapOptions
};
}