下面总结公共库的封装函数(JavaScript),在项目中可以直接使用已封装好的函数库:

数据处理

1. 常用数据处理
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
class DataProcess {
// 获取完整时间
getFullTime() {
let date = new Date();
return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
}

// 获取日期
getDate() {
let date = new Date();
return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
}

// 获取时间
getTime() {
let date = new Date();
return date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
}

// 格式化金额,单位:分(eg:430分=4.30元)
formatFee(fee, suffix = '') {
if (!fee) {
return 0;
}
return Number(fee).toFixed(2) + suffix;
}

// 将金额变为美元书写方式
formatToDollar(val) {
//金额转换 分->元 保留2位小数 并每隔3位用逗号分开 1,234.56
var str = (val / 100).toFixed(2) + '';
var intSum = str.substring(0, str.indexOf(".")).replace(/\B(?=(?:\d{3})+$)/g, ','); //取到整数部分
var dot = str.substring(str.length, str.indexOf(".")) //取到小数部分搜索
var ret = '$' + intSum + dot;
return ret;
}

// 隐藏手机号中间4位
formatPhone(phone) {
phone += '';
return phone.replace(/(\d{3})\d*(\d{4})/g, '$1***$2')
}

// 隐藏身份证号中11位
formatIdentity(number) {
number += '';
return number.replace(/(\d{3})\d*(\d{4})/g, '$1***********$2')
}

// 将句子的每个单词的首字母大写
firstUpperCase(str) {
return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
}

// 句子首字母大写
formatEnSentence(str) {
if (!str) return '';
str = str.trim();
let strArr = str.split('')
strArr[0] = strArr[0].toUpperCase()
let marks = ['.', '?', '!'];
for (let i = 0; i < strArr.length; i++) {
i = parseInt(i)
if (marks.includes(strArr[i])) {
while (strArr[i + 1] === ' ') {
strArr[i + 1] = ''
i++;
}
if (strArr[i + 1]) strArr[i + 1] = strArr[i + 1].toUpperCase()
}
}

return strArr.join('')
}
}

export default DataProcess
2. 常用DOM操作
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
// 为DOM添加class
export function addClass(el, className) {
// 首先要判断 el对象 是否有这个类名 如果有就直接返回 如果没有就添加
if (hasClass(el, className)) {
return
}
let newClass = el.className.split(' ')
newClass.push(className)
el.className = newClass.join(' ')
}

// 判断DOM是否有某个class
export function hasClass(el, className) {
let reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
return reg.test(el.className)
}

// 获取DOM属性name的值
export function getData(el, name, value) {
var prefix = 'data-'
var name = prefix + name
if (value) {
return el.setAttribute(name, value)
} else {
return el.getAttribute(name)
}
}

let elementStyle = document.createElement('div').style

let vendor = (() => {
let transformNames = {
webkit: 'webkitTransform',
Moz: 'MozTransform',
O: 'OTransform',
ms: 'msTransform', //IE
standard: 'transform'
}
for (const key in transformNames) {
if (elementStyle[transformNames[key]] !== undefined) {
return key
}
}
return false
})()

export function prefixStyle(style) {
if (vendor === false) {
return false
}
if (vendor === 'standard') {
return style
}
return vendor + style.charAt(0).toUpperCase() + style.substr(1)
}
3. 常用工具函数
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
// 获取随机数
export function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}

// 洗牌函数
export function shuffle(arr) {
let newArr = arr.slice()
for (let i = 0; i < newArr.length; i++) {
let j = getRandomInt(0, i)
let tmp = newArr[i]
newArr[i] = newArr[j]
newArr[j] = tmp
}
return newArr
}

// 防抖函数
export function simpeDebounce(func, delay) {
let timer;
return () => {
clearTimeout(timer);
timer = setTimeout(func, delay);
};
};

export function debounce(fun, delay) {
return function(arguments) {
//获取函数的作用域和变量
let that = this;
let args = arguments;
clearTimeout(fun.id) // 清除定时器
fun.id = setTimeout(function() {
fun.call(that, args)
}, delay)
}
}

// 节流函数
export function simpleThrottle(func, delay) {
let timer;
return () => {
if (timer) {
return;
}
timer = setTimeout(() => {
func();
timer = null;
}, delay);
};
};

export function throttle(fn, delay) {
let lastTime;
let timer;
delay || (delay = 300); // 默认间隔为300ms
return function(arguments) {
let context = this;
let args = arguments;
let nowTime = +new Date(); // 获取系统当前的时间
if (lastTime && nowTime < lastTime + delay) { // 当前距离上次执行的时间小于设置的时间间隔
clearTimeout(timer); // 清除定时器
timer = setTimeout(function() { // delay时间后,执行函数
lastTime = nowTime;
fn.apply(context, args);
}, delay);
} else { // 当前距离上次执行的时间大于等于设置的时间,直接执行函数
lastTime = nowTime;
fn.apply(context, args);
}
};
}


const toString = Object.prototype.toString

// 判断是否为时间
export function isDate(val) {
return toString.call(val) === '[object Date]'
}
// 判断是否为对象
export function isObject(val) {
return val !== null && typeof val === 'object'
}
// 判断是否为普通对象,不包含了formData、binaryData等
export function isPlainObject(val) {
return toString.call(val) === '[object Object]'
}


// encode解码
export function encode(val) {
return encodeURIComponent(val)
.replace(/%40/g, '@')
.replace(/%3A/gi, ':')
.replace(/%24/g, '$')
.replace(/%2C/gi, ',')
.replace(/%20/g, '+')
.replace(/%5B/gi, '[')
.replace(/%5D/gi, ']')
}

// xss字符转义函数
export function xssEncode(str) {

}

// 构建ajax的url
export function buildURL(url, params) {
if (!params) {
return url
}
const parts = []
Object.keys(params).forEach((key) => {
let val = params[key]
if (val === null || typeof val === 'undefined') {
return
}
let values = []
if (Array.isArray(val)) {
values = val
key += '[]'
} else {
values = [val]
}
values.forEach((val) => {
if (isDate(val)) {
val = val.toISOString()
} else if (isPlainObject(val)) {
val = JSON.stringify(val)
}
parts.push(`${encode(key)}=${encode(val)}`)
})
})
let serializedParams = parts.join('&')
if (serializedParams) {
const markIndex = url.indexOf('#')
if (markIndex !== -1) {
url = url.slice(0, markIndex)
}

url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams
}

return url
}

文件处理

1. 简单文件处理
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
class File {
// 删除文件夹(文件夹内有文件也一并删除)
deleteFolder(path) {
let files = [];
if (fs.existsSync(path)) {
files = fs.readdirSync(path);
files.forEach(function(file, index) {
let curPath = path + "/" + file;
if (fs.statSync(curPath).isDirectory()) {
this.deleteFolder(curPath);
} else {
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
}

// 后端根据url下载文件,存至服务器目录
download(urlArr, dirPath) {
Promise.all(
urlArr.map(async(url, i) => {
let fileName = `${i + 1}.wav`;
let stream = fs.createWriteStream(path.join(dirPath, fileName));
// 下载文件并压缩
await new Promise((resolve, reject) => {
request(url)
.pipe(stream)
.on("close", err => {
if (err) reject(err);
else {
console.log("文件[" + fileName + "]下载完毕");
resolve();
}
});
});
})
).then(() => {
zip.addLocalFolder(dirPath);
let zippath = path.join(__dirname, "zip");
zip.writeZip(zippath + "/adm-archive.zip", err => {
console.log(err);
});
});
}

// 后端返回文件下载
returnFile(filePath, fileName) {
let file = path.join(__dirname, filePath);
let size = fs.statSync(file).size;
let f = fs.createReadStream(file);
res.writeHead(200, {
"Content-Type": "application/force-download",
"Content-Disposition": "attachment; filename=" + fileName,
"Content-Length": size
});
f.pipe(res);
}
}

export default new File()
2. 详细文件处理
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
const fs = require('fs')
const path = require('path')
const unzip = require("unzip")
const AdmZip = require("adm-zip")

class File {
//递归创建目录 同步方法
mkdirsSync(dirname) {
if (fs.existsSync(dirname)) {
return true
} else {
if (mkdirsSync(path.dirname(dirname))) {
fs.mkdirSync(dirname)
return true
}
}
}

//递归创建目录 异步方法
mkdirs(dirname, callback) {
fs.exists(dirname, function(exists) {
if (exists) {
callback()
} else {
//console.log(path.dirname(dirname))
mkdirs(path.dirname(dirname), function() {
fs.mkdir(dirname, callback)
})
}
})
}

/**
*同步创建文件夹
*
* @param {string[]} folders 要创建的文件夹,由键值对表示
*/
createFolderSync(...folders) {
Promise.all(folders.map(folder => {
for (const key in folder) {
if (folder[key] != "") mkdirsSync(folder[key])
}
}))
}

/**
*异步创建文件夹
*
* @param {string[]} folders 要创建的文件夹,由键值对表示
*/
createFolder(...folders) {
Promise.all(folders.map(folder => {
for (const key in folder) {
if (folder[key] != "")
mkdirs(folder[key], () => {
console.log(`${folder[key]}已存在`)
})
}
}))
}

/**
* @description 递归删除文件夹
* @param {string} path 要删除的文件夹
*/
deleteFolderRecursiveSync(path) {
if (fs.existsSync(path)) {
fs.readdirSync(path).forEach((file) => {
let curPath = `${path}/${file}`
if (fs.statSync(curPath).isDirectory()) {
// recurse
deleteFolderRecursiveSync(curPath)
} else {
deleteFileSync(curPath)
}
})
fs.rmdirSync(path)
}
}

/**
* @description 同步删除文件
* @param {string} file 文件路径
*/
deleteFileSync(file) {
if (fs.existsSync(file)) {
try {
fs.unlinkSync(file)
} catch (error) {
console.log(error, `删除${file}失败`)
}
}
}

/**
* @description 异步删除文件
* @param {string} file 文件路径
*/
deleteFile(file) {
fs.exists(file, (exists) => {
if (exists) {
fs.unlink(file, (err) => {
if (err) {
console.log(`删除${file}失败`)
}
})
}
})
}

/**
* @description 同步移动文件夹中的文件
* @param {string} oldPath 源文件夹
* @param {string} newPath 目标文件夹
*/
async moveFolderFileSync(oldPath, newPath) {
try {
fs.readdirSync(oldPath).forEach((file) => {
if (!fs.statSync(`${oldPath}\\${file}`).isDirectory())
fs.renameSync(`${oldPath}\\${file}`, `${newPath}\\${file}`)
})
} catch (error) {
console.log(error, `移动文件夹${oldPath}失败`)
}
}

/**
* @description 异步移动文件夹中的文件
* @param {string} oldPath 源文件夹
* @param {string} newPath 目标文件夹
*/
moveFolderFile(oldPath, newPath) {
fs.readdir(oldPath, (err, files) => {
if (!err)
files.forEach((file) => {
fs.stat(`${oldPath}\\${file}`, (err, stats) => {
if (err) {
console.log(err, `读取${oldPath}\\${file}文件状态失败`)
} else {
if (!stats.isDirectory()) {
try {
fs.rename(`${oldPath}\\${file}`, `${newPath}\\${file}`)
} catch (error) {
console.log(error, `移动${oldPath}\\${file}失败`)
}
}
}
})
})
})
}

/**
* @description 同步复制文件夹
* @param {string} oldPath 源文件夹
* @param {string} newPath 目标文件夹
*/
async moveFolderSync(oldPath, newPath) {
if (fs.existsSync(newPath)) {
deleteFolderRecursiveSync(newPath)
}
try {
fs.renameSync(oldPath, newPath)
} catch (error) {
console.log(error, `${oldPath}移动失败`)
}
}

/**
* @description 异步复制文件夹
* @param {string} oldPath 源文件夹
* @param {string} newPath 目标文件夹
*/
moveFolder(oldPath, newPath) {
fs.exists(newPath, (exists) => {
if (exists) {
deleteFolderRecursiveSync(oldPath)
}
fs.rename(oldPath, newPath, (err) => {
if (err) {
console.log(err, `${oldPath}移动失败`)
}
})
})

}

/**
* @description 同步复制文件
* @param {string} oldFile 源文件
* @param {string} newFile 新文件
*/
async copyFileSync(oldFile, newFile) {
try {
fs.writeFileSync(newFile, fs.readFileSync(oldFile))
} catch (error) {
console.log(error, `复制文件${oldFile}失败`)
}
}

/**
* @description 异步复制文件
* @param {string} oldFile 源文件
* @param {string} newFile 新文件
*/
copyFile(oldFile, newFile) {
fs.createReadStream(oldFile)
.pipe(fs.createWriteStream(newFile))
.on("finish", () => {
console.log(`${oldFile}文件复制完成`)
})
.on("error", (error) => {
console.log(error, "文件复制失败")
})
}

/**
* 异步复制文件夹,可以通过参数决定是否复制子文件夹,可根据名字过滤并重命名为filter
* @param {string}oldPath 要复制的文件夹
* @param {string}newPath 复制到的文件夹
* @param {Boolean}OnlyFile 是否复制子文件夹
* @param {string}filter 根据名字过滤要复制的对象
* @param {Boolean}rename 是否重命名为filter
*/
copyFolder(oldPath, newPath, OnlyFile = false, filter = "", rename = false) {
fs.readdir(oldPath, (err, files) => {
if (!err) {
files.forEach((file) => {
if (file.indexOf(filter) > -1) {
if (!fs.statSync(`${oldPath}\\${file}`).isDirectory()) {
let name = file
if (rename) name = `${filter}${path.extname(file)}`
copyFile(`${oldPath}\\${file}`, `${newPath}\\${name}`)
} else {
if (!OnlyFile)
copyFolder(
`${oldPath}\\${file}`,
`${newPath}\\${file}`,
OnlyFile,
filter,
rename,
)
}
}
})
}
})
}

/**
* 同步复制文件夹,可以通过参数决定是否复制子文件夹,可根据名字过滤并重命名为filter
* @param {string}oldPath 要复制的文件夹
* @param {string}newPath 复制到的文件夹
* @param {Boolean}OnlyFile 是否复制子文件夹
* @param {string}filter 根据名字过滤要复制的对象
* @param {Boolean}rename 是否重命名为filter
*/
copyFolderSync(oldPath, newPath, OnlyFile = false, filter = "", rename = false) {
fs.readdirSync(oldPath).forEach((file) => {
if (file.indexOf(filter) > -1) {
if (!fs.statSync(`${oldPath}\\${file}`).isDirectory()) {
name = file
if (rename) name = `${filter}${path.extname(file)}`
copyFileSync(`${oldPath}\\${file}`, `${newPath}\\${name}`)
} else {
if (!OnlyFile)
copyFolderSync(
`${oldPath}\\${file}`,
`${newPath}\\${file}`,
OnlyFile,
filter,
rename,
)
}
}
})
}

/**
* @description 同步解压文件夹,用adm-zip解压
* @param {string} filePath 压缩文件
* @param {string} extracePath 解压文件夹
*/
ExtractZipSync(filePath, extracePath) {
return new Promise((resolve, reject) => {
try {
var zip = new AdmZip(filePath)
zip.extractAllTo(extracePath, true)
return resolve()
} catch (error) {
return reject(error)
}
})
}

/**
* @description 异步解压文件夹,用unzip解压
* @param {string} filePath 压缩文件
* @param {string} extracePath 解压文件夹
*/
ExtractZip(filePath, extracePath, callback = () => {}) {
fs.createReadStream(filePath)
.pipe(
unzip.Extract({
path: extracePath,
}),
)
.on("finish", () => {
console.log("解压完成")
callback()
})
.on("error", (error) => {
console.log(error, "解压失败")
})
}


/**
* @description 将多个文件夹文件移动到一个文件夹
* @param path 源文件夹
* @param newpath 新文件夹
*/
moveToOne(path, newpath) {
fs.readdir(path, (err, files) => {
if (!err) {
files.forEach(file => {
let OldFile = `${path}\\${file}`
if (!fs.statSync(OldFile).isDirectory())
fs.createReadStream(OldFile)
.pipe(fs.createWriteStream(`${newpath}\\${file}`));
else {
move(OldFile, newpath);
}
});
}
})
}

// 为文件夹下的全部文件增加前缀,复制至另一文件夹
renameAllFileWithPrefix(fileDirectory, newfileDirectory, prefix) {
if (fs.existsSync(fileDirectory)) {
var files = fs.readdirSync(fileDirectory);
for (var i = 0; i < files.length; i++) {
var filePath = fileDirectory + "/" + files[i];
var fileName = prefix + files[i];
var newFilePath = newfileDirectory + "/" + fileName;
fs.rename(filePath, newFilePath, function(err) {
if (err) throw err;
});
}
} else {
console.log(fileDirectory + " Not Found!");
}
}

// 为文件夹下的全部文件增加后缀,复制至另一文件夹
renameAllFileWithSuffix(fileDirectory, newfileDirectory, suffix) {
if (fs.existsSync(fileDirectory)) {
var files = fs.readdirSync(fileDirectory);
for (var i = 0; i < files.length; i++) {
var filePath = fileDirectory + "/" + files[i];
var fileName = files[i] + suffix;
var newFilePath = newfileDirectory + "/" + fileName;
fs.rename(filePath, newFilePath, function(err) {
if (err) throw err;
});
}
} else {
console.log(fileDirectory + " Not Found!");
}
}
}

export default new File()

http请求

1. axios库封装
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
import JsonP from 'jsonp'
import axios from 'axios'

class Axios {
static jsonp(options) {
return new Promise((resolve, reject) => {
JsonP(options.url, {
param: 'callback'
}, function(err, response) {
if (response.status == 'success') {
resolve(response);
} else {
reject(response.messsage);
}
})
})
}

static ajax(options, baseApi, loadingDomId) {
let loading;
if (options.data && options.data.isShowLoading !== false) {
loading = document.getElementById(loadingDomId);
loading.style.display = 'block';
}
return new Promise((resolve, reject) => {
axios({
url: options.url,
method: 'get',
baseURL: baseApi,
timeout: 5000,
params: (options.data && options.data.params) || ''
}).then((response) => {
if (options.data && options.data.isShowLoading !== false) {
loading = document.getElementById(loadingDomId);
loading.style.display = 'none';
}
if (response.status == '200') {
let res = response.data;
if (res.code == '0') {
resolve(res);
} else {
Modal.info({
title: "提示",
content: res.msg
})
}
} else {
reject(response.data);
}
})
});
}
}

export default new Axios()
2. jsonp封装
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
import originJsonp from 'jsonp'

// 三个参数粉笔为 目标url 需要拼接在url上的参数 以及jsonp插件 需要的option
export default function jsonp(url, paramdata, options) {
// 在这里引入一个 拼接字符串的方法
url += (url.indexOf('?') < 0 ? '?' : '&') + param(paramdata)

// 在这里返回一个Promise对象
return new Promise((resolve, reject) => {
// 在这里的data 跟上面的paramdata是不一样的 一个是 json的返回对象 一个是你传入的参数
originJsonp(url, options, (err, data) => {
if (!err) {
resolve(data)
} else {
reject(err)
}
})
})
}

function param(paramdata) {
let url = ''
for (var k in paramdata) {
// 对参数对象里的每一项进行判断
let value = paramdata[k] == undefined ? '' : paramdata[k]
url += `&${k}=${encodeURIComponent(value)}`
}
// 循环结束 url 拼接完毕 将其返回
return url
}

nodejs操作mysql

1. 直接操作,批量修改值
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
const mysql = require("mysql");
const inspect = require("eyes").inspector({
maxLength: false,
});
//使用数据库连接池
const mysqlCofig = {
host: "localhost",
port: 3306,
database: "test4",
user: "root",
password: "574820ypczjs",
};
const pool = mysql.createPool(mysqlCofig);
pool.getConnection(function(err, connection) {
//通过getConnection()方法进行数据库连接
if (err) {
console.log(`mysql链接失败${err}`);
} else {
let EIDs = [],
centerX = [],
centerY = [];
connection.query("select EID,extent from extent", (err, result) => {
for (const key in result) {
const element = result[key];
let EID = element['EID'],
extent = element['extent'];
extent = JSON.parse(extent);
let x = (extent['minX'] + extent['maxX']) / 2;
let y = (extent['minY'] + extent['maxY']) / 2;
EIDs.push(EID);
centerX.push(x);
centerY.push(y);
}

let res = [];
for (const key in EIDs) {
res.push({
EID: EIDs[key],
centerX: centerX[key],
centerY: centerY[key]
})
}
for (const key in res) {
if (res.hasOwnProperty(key)) {
const element = res[key];
connection.query('update extent set ? where EID=?', [element, element['EID']], (err, result) => {
if (err) {
inspect(err, '更新数据出错');
} else {
inspect('更新数据成功');
}
})
}
}
})
}
});

openlayer绘图函数

1. 图形绘制
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
class Map {
/**
* @function 绘制点
* @param {Object} map 地图对象
* @param {Number} x x坐标
* @param {Number} y y坐标
* @param {String} fillColor 填充色
* @param {String} strokeColor 边线颜色
* @param {String} imageColor 图案颜色
*/
drawPoint(map, x, y, fillColor = '#000', strokeColor = '#000', imageColor = '#000') {
let point = new ol.Feature({
geometry: new ol.geom.Point([x, y])
});
point.setStyle(new ol.style.Style({
fill: new ol.style.Fill({
color: fillColor
}),
stroke: new ol.style.Stroke({
color: strokeColor,
width: 1
}),
image: new ol.style.Circle({
radius: 8,
fill: new ol.style.Fill({
color: imageColor
})
})
}));
let source = new ol.source.Vector({
features: [point]
});
let vector = new ol.layer.Vector({
source: source
});
map.addLayer(vector);
}

/**
*
* @param {Object} map 地图
* @param {Array} startPoint 起始点坐标
* @param {Array} endPoint 结束点坐标
*/
drawStaticLine(map, startPoint, endPoint, fillColor = '#000', strokeColor = '#000', imageColor = '#000') {
//创建一个线
let Line = new ol.Feature({
geometry: new ol.geom.LineString([startPoint, endPoint])
});

//设置线的样式
Line.setStyle(new ol.style.Style({
//填充色
fill: new ol.style.Fill({
color: fillColor
}),
//边线颜色
stroke: new ol.style.Stroke({
lineDash: [1, 4],
color: strokeColor,
width: 2
}),
//形状
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: imageColor
})
})
}));
let source = new ol.source.Vector({
features: [Line]
});
let vector = new ol.layer.Vector({
source: source
});
map.addLayer(vector);
}

/**
*
* @param {Object} map
* @param {Array} center 中心点坐标
* @param {Array} others 其余点坐标
*/
drawDynamicLine(map, center, others) {
let style = new ol.style.Style({
stroke: new ol.style.Stroke({
color: '#EAE911',
width: 2
})
});
let flightsSource;
let addLater = function(feature, timeout) {
window.setTimeout(function() {
feature.set('start', new Date().getTime());
flightsSource.addFeature(feature);
}, timeout);
};
let pointsPerMs = 0.1;
let animateFlights = function(event) {
let vectorContext = event.vectorContext;
let frameState = event.frameState;
vectorContext.setStyle(style);
let features = flightsSource.getFeatures();
for (let i = 0; i < features.length; i++) {
let feature = features[i];
if (!feature.get('finished')) {
let coords = feature.getGeometry().getCoordinates();
let elapsedTime = frameState.time - feature.get('start');
let elapsedPoints = elapsedTime * pointsPerMs;
if (elapsedPoints >= coords.length) {
feature.set('finished', true);
}
let maxIndex = Math.min(elapsedPoints, coords.length);
let currentLine = new ol.geom.LineString(coords.slice(0, maxIndex));
//根据要素来描绘出线条
vectorContext.drawGeometry(currentLine);
}
}
//继续动画效果
map.render();
};
flightsSource = new ol.source.Vector({
wrapX: false,
loader: function() {
for (let i = 0; i < others.length; i++) {
let from = center[0];
let to = others[i];
//创建一个两个地点之间的弧段
let arcGenerator = new arc.GreatCircle({
x: from[1],
y: from[0]
}, {
x: to[1],
y: to[0]
});

let arcLine = arcGenerator.Arc(100, {
offset: 10
});
if (arcLine.geometries.length === 1) {
let line = new ol.geom.LineString(arcLine.geometries[0].coords);
line.transform(ol.proj.get('EPSG:4326'), ol.proj.get('EPSG:3857'));

let feature = new ol.Feature({
geometry: line,
finished: false
});
//添加动画的特性与延迟所有功能并不在同一时间开始
addLater(feature, i * 50);
}
}
map.on('postcompose', animateFlights);
}
});

let flightsLayer = new ol.layer.Vector({
source: flightsSource,
style: function(feature) {
//如果动画仍然是活跃的特性,不渲染图层样式的特性
if (feature.get('finished')) {
return style;
} else {
return null;
}
}
});
map.addLayer(flightsLayer);
}

// 为非中心点创建注记
createOtherLabelStyle(feature) {
return new ol.style.Style({
text: new ol.style.Text({
//位置
textAlign: 'center',
//基准线
textBaseline: 'middle',
//文字样式
font: 'normal 10px 微软雅黑',
//文本内容
text: feature.get('name'),
//文本填充样式(即文字颜色)
fill: new ol.style.Fill({
color: '#aa3300'
}),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 1
})
})
});
}

// 为中心点创建注记
createCenterLabelStyle(feature) {
return new ol.style.Style({
text: new ol.style.Text({
//位置
textAlign: 'center',
//基准线
textBaseline: 'middle',
//文字样式
font: 'normal 18px 微软雅黑',
//文本内容
text: feature.get('name'),
fill: new ol.style.Fill({
color: '#104E8B'
}),
stroke: new ol.style.Stroke({
color: '#104E8B',
width: 1
})
})
});
}

createIconStyle(feature, src) {
return new ol.style.Style({
/**{olx.style.IconOptions}类型*/
image: new ol.style.Icon(
({
anchor: [0.5, 60],
anchorOrigin: 'top-right',
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
offsetOrigin: 'top-right',
opacity: 0.75,
src: src
})
)
});
}

/**
* @description 添加图层注记
* @param {*} map 地图
* @param {*} point 点
* @param {*} name 名称
* @param {*} type 类型
*/
mark(map, point, name, type) {
let iconFeature = new ol.Feature({
geometry: new ol.geom.Point(point),
name: name,
});
if (type === 1) {
iconFeature.setStyle(this.createCenterLabelStyle(iconFeature))
} else {
iconFeature.setStyle(this.createOtherLabelStyle(iconFeature));
}
let vectorSource = new ol.source.Vector({
features: [iconFeature]
});
let vectorLayer = new ol.layer.Vector({
source: vectorSource
});
map.addLayer(vectorLayer);
}

/**
* @description 为中心点添加icon
* @param {*} map
* @param {*} point
*/
addIcon(map, point, imgSrc) {
let iconFeature = new ol.Feature({
geometry: new ol.geom.Point(point)
});
iconFeature.setStyle(this.createIconStyle(iconFeature, imgSrc));
let vectorSource = new ol.source.Vector({
features: [iconFeature]
});
let vectorLayer = new ol.layer.Vector({
source: vectorSource
});
map.addLayer(vectorLayer);
}
}

export default new Map()