forked from mbostock/shapefile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
89 lines (75 loc) · 2.26 KB
/
index.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
var events = require("events");
var shp = require("./shp"),
dbf = require("./dbf");
exports.readStream = function(filename) {
var emitter = new events.EventEmitter();
if (/\.shp$/.test(filename)) filename = filename.substring(0, filename.length - 4);
readProperties(filename, function(error, properties) {
if (error) return void emitter.emit("error", error);
var geometries = [],
convert;
properties.reverse(); // for efficient pop
shp.readStream(filename + ".shp")
.on("header", function(header) { convert = convertGeometry[header.shapeType]; })
.on("record", function(record) {
emitter.emit("feature", {
type: "Feature",
properties: properties.pop(),
geometry: record == null ? null : convert(record)
});
})
.on("error", function() { emitter.emit("error", error); })
.on("end", function() { emitter.emit("end"); });
});
return emitter;
};
function readProperties(filename, callback) {
var properties = [],
convert;
dbf.readStream(filename + ".dbf")
.on("header", function(header) {
convert = new Function("d", "return {"
+ header.fields.map(function(field, i) { return JSON.stringify(field.name) + ":d[" + i + "]"; })
+ "};");
})
.on("record", function(record) { properties.push(convert(record)); })
.on("error", callback)
.on("end", function() { callback(null, properties); });
}
var convertGeometry = {
1: convertPoint,
3: convertPolyLine,
5: convertPolygon,
8: convertMultiPoint
};
function convertPoint(record) {
return {
type: "Point",
coordinates: [record.x, record.y]
};
}
function convertPolyLine(record) {
return record.parts.length === 1 ? {
type: "LineString",
coordinates: record.points
} : {
type: "MultiLineString",
coordinates: record.parts.map(function(i, j) {
return record.points.slice(i, record.parts[j + 1]);
})
};
}
function convertPolygon(record) {
return {
type: "Polygon",
coordinates: record.parts.map(function(i, j) {
return record.points.slice(i, record.parts[j + 1]);
})
};
}
function convertMultiPoint(record) {
return {
type: "MultiPoint",
coordinates: record.points
};
}