-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeojson.ts
404 lines (360 loc) · 10.9 KB
/
geojson.ts
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
export class GeoJSON {
version = "0.5.0";
private geomAttrs = [];
private geoms = [
"Point",
"MultiPoint",
"LineString",
"MultiLineString",
"Polygon",
"MultiPolygon",
"GeoJSON"
];
// Allow user to specify default parameters
default: object = {
doThrows: {
invalidGeometry: false
}
};
constructor() {}
InvalidGeometryError(...arguments_arr: any[]): Error {
var args = 1 <= arguments_arr.length ? [].slice.call(arguments_arr, 0) : [];
var item = args.shift();
var params = args.shift();
throw Error(
"Invalid Geometry: " +
"item: " +
JSON.stringify(item) +
", params: " +
JSON.stringify(params)
);
}
errors: object = {
InvalidGeometryError: this.InvalidGeometryError
};
public isGeometryValid = function(geometry: any): boolean {
if (!geometry || !Object.keys(geometry).length) {
return false;
}
};
public parse(objects: [] | object, params: object, callback?: Function): any {
let geojson,
settings = this.applyDefaults(params, this.default),
propFunc;
this.geomAttrs.length = 0; // Reset the list of geometry fields
this.setGeom(settings);
propFunc = this.getPropFunction(settings);
if (Array.isArray(objects)) {
geojson = { type: "FeatureCollection", features: [] };
objects.forEach(function(item) {
geojson.features.push(
this.getFeature({ item: item, params: settings, propFunc: propFunc })
);
});
this.addOptionals(geojson, settings);
} else {
geojson = this.getFeature({
item: objects,
params: settings,
propFunc: propFunc
});
this.addOptionals(geojson, settings);
}
if (callback && typeof callback === "function") {
callback(geojson);
} else {
return geojson;
}
}
// Adds default settings to user-specified params
// Does not overwrite any settings--only adds defaults
// the the user did not specify
private applyDefaults(params: object, defaults: object): object {
let settings = params || {};
for (let setting in settings) {
if (defaults.hasOwnProperty(setting) && !settings[setting]) {
settings[setting] = defaults[setting];
}
}
return settings;
}
// Adds the optional GeoJSON properties crs and bbox
// if they have been specified
private addOptionals(geojson, settings) {
if (settings.crs && this.checkCRS(settings.crs)) {
if (settings.isPostgres) {
geojson.geometry.crs = settings.crs;
} else {
geojson.crs = settings.crs;
}
}
if (settings.bbox) {
geojson.bbox = settings.bbox;
}
if (settings.extraGlobal) {
geojson.properties = {};
for (let key in settings.extraGlobal) {
geojson.properties[key] = settings.extraGlobal[key];
}
}
}
// Verify that the structure of CRS object is valid
private checkCRS(crs): boolean {
if (crs.type === "name") {
if (crs.properties && crs.properties.name) {
return true;
} else {
throw new Error('Invalid CRS. Properties must contain "name" key');
}
} else if (crs.type === "link") {
if (crs.properties && crs.properties.href && crs.properties.type) {
return true;
} else {
throw new Error(
'Invalid CRS. Properties must contain "href" and "type" key'
);
}
} else {
throw new Error('Invald CRS. Type attribute must be "name" or "link"');
}
}
// Moves the user-specified geometry parameters
// under the `geom` key in param for easier access
private setGeom(params: any): void {
params.geom = {};
for (let param in params) {
if (params.hasOwnProperty(param) && this.geoms.indexOf(param) !== -1) {
params.geom[param] = params[param];
delete params[param];
}
}
this.setGeomAttrList(params.geom);
}
// Adds fields which contain geometry data
// to geomAttrs. This list is used when adding
// properties to the features so that no geometry
// fields are added the properties key
private setGeomAttrList(params: any): void {
for (let param in params) {
if (params.hasOwnProperty(param)) {
if (typeof params[param] === "string") {
this.geomAttrs.push(params[param]);
} else if (typeof params[param] === "object") {
// Array of coordinates for Point
this.geomAttrs.push(params[param][0]);
this.geomAttrs.push(params[param][1]);
}
}
}
if (this.geomAttrs.length === 0) {
throw new Error("No geometry attributes specified");
}
}
// Creates a feature object to be added
// to the GeoJSON features array
private getFeature(args): object {
let item = args.item,
params = args.params,
propFunc = args.propFunc;
let feature = { type: "Feature" };
let that = this;
feature["geometry"] = this.buildGeom(item, params);
feature["properties"] = propFunc.call(item, that);
return feature;
}
private isNested(val) {
return /^.+\..+$/.test(val);
}
// Assembles the `geometry` property
// for the feature output
private buildGeom(item, params): any {
let geom = {};
// attr;
for (let gtype in params.geom) {
let val = params.geom[gtype];
// Geometry parameter specified as: {Point: 'coords'}
if (typeof val === "string" && item.hasOwnProperty(val)) {
if (gtype === "GeoJSON") {
geom = item[val];
} else {
geom["type"] = gtype;
geom["coordinates"] = item[val];
}
} else if (typeof val === "object" && !Array.isArray(val)) {
/* Handle things like:
Polygon: {
northeast: ['lat', 'lng'],
southwest: ['lat', 'lng']
}
*/
/*jshint loopfunc: true */
let points = Object.keys(val).map(function(key) {
let order = val[key];
let newItem = item[key];
return this.buildGeom(newItem, { geom: { Point: order } });
});
geom["type"] = gtype;
/*jshint loopfunc: true */
geom["coordinates"] = [].concat(
points.map(function(p) {
return p.coordinates;
})
);
} else if (
// Geometry parameter specified as: {Point: ['lat', 'lng', 'alt']}
Array.isArray(val) &&
item.hasOwnProperty(val[0]) &&
item.hasOwnProperty(val[1]) &&
item.hasOwnProperty(val[2])
) {
geom["type"] = gtype;
geom["coordinates"] = [
Number(item[val[1]]),
Number(item[val[0]]),
Number(item[val[2]])
];
} else if (
// Geometry parameter specified as: {Point: ['lat', 'lng']}
Array.isArray(val) &&
item.hasOwnProperty(val[0]) &&
item.hasOwnProperty(val[1])
) {
geom["type"] = gtype;
geom["coordinates"] = [Number(item[val[1]]), Number(item[val[0]])];
} else if (
// Geometry parameter specified as: {Point: ['container.lat', 'container.lng', 'container.alt']}
Array.isArray(val) &&
this.isNested(val[0]) &&
this.isNested(val[1]) &&
this.isNested(val[2])
) {
let coordinates = [];
for (let i = 0; i < val.length; i++) {
// i.e. 0 and 1
var paths = val[i].split(".");
var itemClone = item;
for (var j = 0; j < paths.length; j++) {
if (!itemClone.hasOwnProperty(paths[j])) {
return false;
}
itemClone = itemClone[paths[j]]; // Iterate deeper into the object
}
coordinates[i] = itemClone;
}
geom["type"] = gtype;
geom["coordinates"] = [
Number(coordinates[1]),
Number(coordinates[0]),
Number(coordinates[2])
];
}
// Geometry parameter specified as: {Point: ['container.lat', 'container.lng']}
else if (
Array.isArray(val) &&
this.isNested(val[0]) &&
this.isNested(val[1])
) {
var coordinates = [];
for (var i = 0; i < val.length; i++) {
// i.e. 0 and 1
var paths = val[i].split(".");
var itemClone = item;
for (var j = 0; j < paths.length; j++) {
if (!itemClone.hasOwnProperty(paths[j])) {
return false;
}
itemClone = itemClone[paths[j]]; // Iterate deeper into the object
}
coordinates[i] = itemClone;
}
geom["type"] = gtype;
geom["coordinates"] = [Number(coordinates[1]), Number(coordinates[0])];
} else if (
// Geometry parameter specified as: {Point: [{coordinates: [lat, lng]}]}
Array.isArray(val) &&
val[0].constructor.name === "Object" &&
Object.keys(val[0])[0] === "coordinates"
) {
geom["type"] = gtype;
geom["coordinates"] = [
Number(item.coordinates[val[0].coordinates.indexOf("lng")]),
Number(item.coordinates[val[0].coordinates.indexOf("lat")])
];
}
}
if (
params.doThrows &&
params.doThrows.invalidGeometry &&
!this.isGeometryValid(geom)
) {
throw this.InvalidGeometryError(item, params);
}
return geom;
}
// Returns the function to be used to
// build the properties object for each feature
private getPropFunction(params) {
var func;
if (!params.exclude && !params.include) {
func = function(properties, that) {
for (var attr in this) {
if (
this.hasOwnProperty(attr) &&
that.geomAttrs.indexOf(attr) === -1
) {
properties[attr] = this[attr];
}
}
};
} else if (params.include) {
func = function(properties, that) {
params.include.forEach(function(attr) {
properties[attr] = this[attr];
}, this);
};
} else if (params.exclude) {
func = function(properties, that) {
for (var attr in this) {
if (
this.hasOwnProperty(attr) &&
that.geomAttrs.indexOf(attr) === -1 &&
params.exclude.indexOf(attr) === -1
) {
properties[attr] = this[attr];
}
}
};
}
return function(that) {
var properties = {};
func.call(this, properties, that);
if (params.extra) {
this.addExtra(properties, params.extra);
}
return properties;
};
}
// Adds data contained in the `extra`
// parameter if it has been specified
private addExtra(properties, extra) {
for (var key in extra) {
if (extra.hasOwnProperty(key)) {
properties[key] = extra[key];
}
}
return properties;
}
}
let geo = new GeoJSON();
var data = {
name: "Location A",
category: "Store",
street: "Market",
lat: 39.984,
lng: -75.343
};
let res = geo.parse(data, { Point: ["lat", "lng"] });
let res1 = geo.parse(data, { Point: ["lat", "lng"] });
console.log(res);
console.log(res1);
console.log("end");