-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkmlextractor.js
109 lines (80 loc) · 2.93 KB
/
kmlextractor.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
const fs = require('fs');
const DOMParser = require('xmldom').DOMParser;
const express = require('express');
const app = express();
async function readKML(name) {
let kmlString = fs.readFileSync(name).toString();
let googlePolygons = [];
let googleMarkers = [];
var xmlDoc = null;
//Parse the kml
try {
//Internet Explorer
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(kmlString);
} catch(e) {
try {
//Firefox, etc.
var parser = new DOMParser();
xmlDoc = parser.parseFromString(kmlString,"text/kml");
}
catch(e) {
//Failed to parse
alert(e.message);
return;
}
}
const placemark = xmlDoc.getElementsByTagName('Placemark');
const polygon = xmlDoc.getElementsByTagName('Polygon');
// console.log(placemark.toString())
placemarkArray = [];
polygonArray = [];
namesArray = [];
for(let i = 0; i < placemark.length; i++){
if (placemark[i] == undefined && polygon[i] == undefined){
break;
}
if (placemark[i] != undefined){
placemarkArray.push(placemark[i]);
};
if (polygon[i] != undefined){
polygonArray.push(polygon[i]);
};
};
if (xmlDoc.documentElement.nodeName == "kml") {
for (const item of placemarkArray) {
let markers = item.getElementsByTagName('Point');
/** POLYGONS PARSE **/
for (const polygon of polygonArray) {
let coords = polygon.getElementsByTagName('coordinates')[0].childNodes[0].nodeValue.trim();
let points = coords.split(" ");
let googlePolygonsPaths = [];
for (const point of points) {
let coord = point.split(",");
googlePolygonsPaths.push({ lat: +coord[1], lng: +coord[0] });
};
googlePolygons.push(googlePolygonsPaths);
};
/** MARKER PARSE **/
let markersArrray = [];
for(let i = 0; i <1000; i++){
if (markers[i] == undefined){
break;
};
markersArrray.push(markers[i]);;
};
for (const marker of markersArrray) {
var coords = marker.getElementsByTagName('coordinates')[0].childNodes[0].nodeValue.trim();
let coord = coords.split(",");
googleMarkers.push({ lat: +coord[1], lng: +coord[0] });
};
}
} else {
throw "error while parsing";
}
// console.log({ markers: googleMarkers, polygons: googlePolygons});
const result = { markers: googleMarkers, polygons: googlePolygons};
return result;
}
module.exports.readKML = readKML;