forked from SuperMap/iClient-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtil.js
More file actions
434 lines (411 loc) · 14.9 KB
/
Util.js
File metadata and controls
434 lines (411 loc) · 14.9 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
/* Copyright© 2000 - 2020 SuperMap Software Co.Ltd. All rights reserved.
* This program are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution and is available at http://www.apache.org/licenses/LICENSE-2.0.html.*/
import {Unit, Bounds, GeoJSON as GeoJSONFormat, FilterParameter,
GetFeaturesBySQLParameters,
GetFeaturesBySQLService,
QueryBySQLParameters,
QueryOption
} from '@supermap/iclient-common';
import { QueryService } from '../services/QueryService';
import * as olUtil from 'ol/util';
/**
* @class ol.supermap.Util
* @category BaseTypes Util
* @classdesc 工具类。
*/
export class Util {
constructor() {
}
static getOlVersion(){
if(olUtil && olUtil.VERSION) {
return olUtil.VERSION.split('.')[0]
}
if(window && window.ol){
if(window.ol.util){
return '6'
}
if(window.ol.WebGLMap){
return '5'
}
}
return '4'
}
/**
* @function ol.supermap.Util.toGeoJSON
* @description 将传入对象转为 GeoJSON 格式。
* @param {Object} smObj - 待转参数。
*/
static toGeoJSON(smObj) {
if (smObj) {
var format = new GeoJSONFormat();
return format.toGeoJSON(smObj);
}
}
/**
* @function ol.supermap.Util.toSuperMapGeometry
* @description 将 GeoJSON 对象转为 SuperMap 几何图形。
* @param {GeoJSONObject} geoJSON - GeoJSON 对象。
*/
static toSuperMapGeometry(geoJSON) {
if (geoJSON && geoJSON.type) {
var format = new GeoJSONFormat();
var result = format.read(geoJSON, "FeatureCollection");
return result[0].geometry;
}
}
/**
* @function ol.supermap.Util.resolutionToScale
* @description 通过分辨率计算比例尺。
* @param {number} resolution - 分辨率。
* @param {number} dpi - 屏幕分辨率。
* @param {string} mapUnit - 地图单位。
* @returns {number} 比例尺。
*/
static resolutionToScale(resolution, dpi, mapUnit) {
var inchPerMeter = 1 / 0.0254;
// 地球半径。
var meterPerMapUnit = this.getMeterPerMapUnit(mapUnit);
var scale = resolution * dpi * inchPerMeter * meterPerMapUnit;
scale = 1 / scale;
return scale;
}
/**
* @function ol.supermap.Util.toSuperMapBounds
* @description 转为 SuperMapBounds 格式。
* @param {Array.<number>} bounds - bounds 数组。
* @returns {SuperMap.Bounds} 返回 SuperMap 的 Bounds 对象。
*/
static toSuperMapBounds(bounds) {
return new Bounds(
bounds[0],
bounds[1],
bounds[2],
bounds[3]
);
}
/**
* @function ol.supermap.Util.toProcessingParam
* @description 将 Region 节点数组转为 Processing 服务需要的分析参数。
* @param {Array} points - Region 各个节点数组。
* @returns processing 服务裁剪、查询分析的分析参数。
*/
static toProcessingParam(points) {
var geometryParam = {};
if (points.length < 1) {
geometryParam = "";
} else {
var results = [];
for (var i = 0; i < points.length; i++) {
var point = {};
point.x = points[i][0];
point.y = points[i][1];
results.push(point);
}
results.push(results[0]);
geometryParam.type = "REGION";
geometryParam.points = results;
}
return geometryParam;
}
/**
* @function ol.supermap.Util.scaleToResolution
* @description 通过比例尺计算分辨率。
* @param {number} scale - 比例尺。
* @param {number} dpi - 屏幕分辨率。
* @param {string} mapUnit - 地图单位。
* @returns {number} 分辨率。
*/
static scaleToResolution(scale, dpi, mapUnit) {
var inchPerMeter = 1 / 0.0254;
var meterPerMapUnitValue = this.getMeterPerMapUnit(mapUnit);
var resolution = scale * dpi * inchPerMeter * meterPerMapUnitValue;
resolution = 1 / resolution;
return resolution;
}
/**
* @private
* @function ol.supermap.Util.getMeterPerMapUnit
* @description 获取每地图单位多少米。
* @param {string} mapUnit - 地图单位。
* @returns {number} 返回每地图单位多少米。
*/
static getMeterPerMapUnit(mapUnit) {
var earchRadiusInMeters = 6378137;
var meterPerMapUnit;
if (mapUnit === Unit.METER) {
meterPerMapUnit = 1;
} else if (mapUnit === Unit.DEGREE) {
// 每度表示多少米。
meterPerMapUnit = Math.PI * 2 * earchRadiusInMeters / 360;
} else if (mapUnit === Unit.KILOMETER) {
meterPerMapUnit = 1.0E-3;
} else if (mapUnit === Unit.INCH) {
meterPerMapUnit = 1 / 2.5399999918E-2;
} else if (mapUnit === Unit.FOOT) {
meterPerMapUnit = 0.3048;
} else {
return meterPerMapUnit;
}
return meterPerMapUnit;
}
/**
* @function ol.supermap.Util.isArray
* @description 判断是否为数组格式。
* @param {Object} obj - 待判断对象。
* @returns {boolean} 是否是数组。
*/
static isArray(obj) {
return Object.prototype.toString.call(obj) == '[object Array]'
}
/**
* @function ol.supermap.Util.Csv2GeoJSON
* @description 将 csv 格式转为 GeoJSON。
* @param {Object} csv - csv 对象。
* @param {Object} options - 转换参数。
*/
static Csv2GeoJSON(csv, options) {
var defaultOptions = {
titles: ['lon', 'lat'],
latitudeTitle: 'lat',
longitudeTitle: 'lon',
fieldSeparator: ',',
lineSeparator: '\n',
deleteDoubleQuotes: true,
firstLineTitles: false
};
options = options || defaultOptions;
var _propertiesNames = []
if (typeof csv === 'string') {
var titulos = options.titles;
if (options.firstLineTitles) {
csv = csv.split(options.lineSeparator);
if (csv.length < 2) {
return;
}
titulos = csv[0];
csv.splice(0, 1);
csv = csv.join(options.lineSeparator);
titulos = titulos.trim().split(options.fieldSeparator);
for (let i = 0; i < titulos.length; i++) {
titulos[i] = _deleteDoubleQuotes(titulos[i]);
}
options.titles = titulos;
}
for (let i = 0; i < titulos.length; i++) {
var prop = titulos[i].toLowerCase().replace(/[^\w ]+/g, '').replace(/ +/g, '_');
if (prop == '' || prop == '_') {
prop = 'prop-' + i;
}
_propertiesNames[i] = prop;
}
csv = _csv2json(csv);
}
return csv;
function _deleteDoubleQuotes(cadena) {
if (options.deleteDoubleQuotes) {
cadena = cadena.trim().replace(/^"/, "").replace(/"$/, "");
}
return cadena;
}
function _csv2json(csv) {
var json = {};
json["type"] = "FeatureCollection";
json["features"] = [];
var titulos = options.titles;
csv = csv.split(options.lineSeparator);
for (var num_linea = 0; num_linea < csv.length; num_linea++) {
var campos = csv[num_linea].trim().split(options.fieldSeparator)
, lng = parseFloat(campos[titulos.indexOf(options.longitudeTitle)])
, lat = parseFloat(campos[titulos.indexOf(options.latitudeTitle)]);
var isInRange = lng < 180 && lng > -180 && lat < 90 && lat > -90;
if (!(campos.length == titulos.length && isInRange)) {
continue;
}
var feature = {};
feature["type"] = "Feature";
feature["geometry"] = {};
feature["properties"] = {};
feature["geometry"]["type"] = "Point";
feature["geometry"]["coordinates"] = [lng, lat];
for (var i = 0; i < titulos.length; i++) {
if (titulos[i] != options.latitudeTitle && titulos[i] != options.longitudeTitle) {
feature["properties"][_propertiesNames[i]] = _deleteDoubleQuotes(campos[i]);
}
}
json["features"].push(feature);
}
return json;
}
}
/**
* @function ol.supermap.Util.createCanvasContext2D
* @description 创建 2D 画布。
* @param {number} opt_width - 画布宽度。
* @param {number} opt_height - 画布高度。
*/
static createCanvasContext2D(opt_width, opt_height) {
var canvas = document.createElement('CANVAS');
if (opt_width) {
canvas.width = opt_width;
}
if (opt_height) {
canvas.height = opt_height;
}
return canvas.getContext('2d');
}
/**
* @function ol.supermap.Util.supportWebGL2
* @description 是否支持 webgl2。
*/
static supportWebGL2() {
var canvas = document.createElement('canvas');
return Boolean(canvas && canvas.getContext("webgl2"));
}
/**
* @function ol.supermap.Util.isString
* @description 是否为字符串
* @param {string} str - 需要判断的内容
* @returns {boolean}
*/
static isString(str) {
return (typeof str === 'string') && str.constructor === String;
}
/**
* @function ol.supermap.Util.trim
* @description 字符串裁剪两边的空格
* @param {string} str - 需要裁剪的字符串
* @returns {boolean}
*/
static trim(str = '') {
return str.replace(/(^\s*)|(\s*$)/g, "");
}
/**
* @function ol.supermap.Util.newGuid
* @description 随机生成id
* @param {string} attr - 几位数字的id
* @returns {string}
*/
static newGuid(attr) {
let len = attr || 32;
let guid = "";
for (let i = 1; i < len; i++) {
let n = Math.floor(Math.random() * 16.0).toString(16);
guid += n;
}
return guid;
}
/**
* @function ol.supermap.Util.isNumber
* @description 检测数据是否为number
* @param {string} value - 值,未知数据类型
* @returns {boolean}
*/
static isNumber(value) {
if (value === '') {
return false;
}
let mdata = Number(value);
if (mdata === 0) {
return true;
}
return !isNaN(mdata);
}
/**
* @function ol.supermap.Util.getFeatureBySQL
* @description 获取feature
* @param {string} url - 获取feature的请求地址
* @param {string} datasetNames - 数据集名称
* @param {function} processCompleted - 成功请求的回调函数
* @param {function} processFaild - 失败请求的回调函数
*/
static getFeatureBySQL(url, datasetNames, processCompleted, processFaild) {
let getFeatureParam, getFeatureBySQLService, getFeatureBySQLParams;
getFeatureParam = new FilterParameter({
name: datasetNames.join().replace(":", "@"),
attributeFilter: 'SMID > 0'
});
getFeatureBySQLParams = new GetFeaturesBySQLParameters({
queryParameter: getFeatureParam,
datasetNames: datasetNames,
fromIndex: 0,
toIndex: 100000,
maxFeatures: 100000,
returnContent: true
});
let options = {
eventListeners: {
processCompleted: function (getFeaturesEventArgs) {
processCompleted && processCompleted(getFeaturesEventArgs);
},
processFailed: function (e) {
processFaild && processFaild(e);
}
},
withCredentials: true
};
getFeatureBySQLService = new GetFeaturesBySQLService(url, options);
getFeatureBySQLService.processAsync(getFeatureBySQLParams);
}
static queryFeatureBySQL(url, layerName, attributeFilter, fields, epsgCode, processCompleted, processFaild, startRecord, recordLength, onlyAttribute) {
var queryParam, queryBySQLParams, queryBySQLService;
queryParam = new FilterParameter({
name: layerName,
attributeFilter: attributeFilter
});
if (fields) {
queryParam.fields = fields;
}
var params = {
queryParams: [queryParam]
};
if (onlyAttribute) {
params.queryOption = QueryOption.ATTRIBUTE;
}
startRecord && (params.startRecord = startRecord);
recordLength && (params.expectCount = recordLength);
if (epsgCode) {
params.prjCoordSys = {
epsgCode: epsgCode
}
}
queryBySQLParams = new QueryBySQLParameters(params);
queryBySQLService = new QueryService(url);
queryBySQLService.queryBySQL(queryBySQLParams, function (data) {
data.type === 'processCompleted' ? processCompleted(data) : processFaild(data)
});
}
/**
* @function ol.supermap.Util.getFeatureProperties
* @description 从feature中获取properties
* @param {array} features 要素数组
* @returns {array} 属性
*/
static getFeatureProperties(features) {
let properties = [];
if (Util.isArray(features) && features.length) {
features.forEach(feature => {
let property = feature.get('attributes');
property && properties.push(property);
});
}
return properties;
}
/**
* @function ol.supermap.Util.isMatchAdministrativeName
* @param {string} featureName 原始数据中的地名
* @param {string} fieldName 需要匹配的地名
* @returns {boolean} 是否匹配
*/
static isMatchAdministrativeName(featureName, fieldName) {
if (Util.isString(fieldName)) {
let shortName = featureName.substr(0, 2);
// 张家口市和张家界市 特殊处理
if (shortName === '张家') {
shortName = featureName.substr(0, 3);
}
return !!fieldName.match(new RegExp(shortName));
}
return false;
}
}