-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathtable2geo.js
111 lines (98 loc) · 2.31 KB
/
table2geo.js
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
export function table2geo(data, lat, lon) {
let arr = JSON.parse(JSON.stringify(data));
let coords = lat;
// check fields
if (lat == undefined && lon == undefined && coords == undefined) {
let checkcoords = [
"coords",
"Coords",
"coord",
"Coords",
"Coordinates",
"coordinates",
"Coordinate",
"coordinate",
];
let checklat = ["lat", "Lat", "LAT", "Latitude", "latitude"];
let checklon = [
"lon",
"Lon",
"LON",
"lng",
"Lng",
"LNG",
"Longitude",
"longitude",
];
let keys = [];
arr.forEach((d) => keys.push(Object.keys(d)));
keys = Array.from(new Set(keys.flat()));
lat = checklat.filter((d) => keys.includes(d))[0];
lon = checklon.filter((d) => keys.includes(d))[0];
coords = checkcoords.filter((d) => keys.includes(d))[0];
}
// case1: lat & lng coords in separate columns
if (lat && lon) {
let x = lat;
let y = lon;
return {
type: "FeatureCollection",
features: data.map((d) => ({
type: "Feature",
properties: d,
geometry: {
type: "Point",
coordinates: [+d[y], +d[x]],
},
})),
};
}
// case2: lat & lng coords in a single column
if (coords) {
return {
type: "FeatureCollection",
features: data.map((d) => ({
type: "Feature",
properties: d,
geometry: {
type: "Point",
coordinates: getcoords(d[coords]).reverse(),
},
})),
};
}
return coords;
}
function txt2coords(str, sep = ",") {
str = str.replace(/[ ]+/g, "");
let coords = str
.split(sep)
.map((d) => d.replace(",", "."))
.map((d) => d.replace(/[^\d.-]/g, ""))
.map((d) => +d);
if (coords.length != 2) {
coords = [undefined, undefined];
}
return coords;
}
function wkt2coords(str) {
let result = str.match(/\(([^)]+)\)/g);
return result === null
? [undefined, undefined]
: result[0]
.replace(/\s\s+/g, " ")
.replace("(", "")
.replace(")", "")
.trimStart()
.trimEnd()
.split(" ")
.map((d) => d.replace(",", "."))
.map((d) => +d);
}
function getcoords(str) {
return str
? str.toLowerCase().includes("point")
? wkt2coords(str)
: txt2coords(str)
: null;
}