forked from locationestimatr/locationestimatr.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MapManager.js
106 lines (89 loc) · 3.2 KB
/
MapManager.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
class MapManager {
async initialize() {
let response = await fetch("../data/countries.json");
this.countries = await response.json();
response = await fetch("../data/maps.json");
this.maps = await response.json();
}
getAreaMap(lat, lon, radius, numSides = 20) {
radius *= 1000;
let center = new google.maps.LatLng(lat, lon);
const paths = [], degreeStep = 360 / numSides;
for (let i = 0; i < numSides; i++) {
const gpos = google.maps.geometry.spherical.computeOffset(center, radius, degreeStep * i);
paths.push({lat: gpos.lat(), lng: gpos.lng()});
}
paths.push(paths[0]);
console.log(paths);
let poly = new google.maps.Polygon({
paths: paths,
strokeColor: "#FFC107",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FFC107",
fillOpacity: 0.35
});
return this.getMapByPoly(poly, "my_area");
}
async getMapByName(key) {
let poly;
if (this.maps[key] === undefined) {
poly = this.kmlsToPolygon(this.countries[key]);
} else {
let map = this.maps[key];
if (map.type === "collection") {
console.log("Map collection:", map.countries);
poly = this.kmlsToPolygon(...map.countries.map(country => this.countries[country]));
} else if (map.type === "kml") {
let response = await fetch("../data/kml/" + map.file);
let kml = await response.text();
poly = this.kmlsToPolygon(kml);
}
}
return this.getMapByPoly(poly, key);
}
getMapByPoly(poly, mapName) {
let area = 0;
poly.getPaths().forEach(path => {
area += google.maps.geometry.spherical.computeArea(path);
});
let minimumDistanceForPoints = Math.sqrt(area) * 2;
return new GeoMap(poly, minimumDistanceForPoints, mapName);
}
kmlsToPolygon(...kmls) {
let paths = [];
for (let kml of kmls) {
paths = paths.concat(this.kmlToPaths(kml));
}
return new google.maps.Polygon({
paths: paths,
strokeColor: "#FFC107",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FFC107",
fillOpacity: 0.35
});
}
kmlToPaths(kml) {
let paths = [];
let addPolygonToPaths = (polygon, paths) => {
let poly = [];
let coordString = polygon.textContent.trim();
for (let coordinate of coordString.split(" ")) {
let [lng, lat, _] = coordinate.split(",").map(n => +n);
poly.push({
lat, lng
});
}
paths.push(poly);
}
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(kml, "text/xml").firstChild;
if (xmlDoc.nodeName === "MultiGeometry")
for (let polygon of xmlDoc.children)
addPolygonToPaths(polygon, paths);
else if (xmlDoc.nodeName === "Polygon")
addPolygonToPaths(xmlDoc, paths);
return paths;
}
}