シンプルにポリゴンの中心を求めたいときに。
const getCentroid = (geometry) => {
var polygon = [];
switch (geometry.type) {
case "MultiPolygon":
geometry.coordinates.forEach( (d, i) => {
if (i == 0 || polygon.length < d[0].length) polygon = d[0];
});
break;
case "Polygon":
polygon = geometry.coordinates[0];
break;
}
return polygon.reduce(
(a, b) => {
return [a[0] + b[0] / polygon.length, a[1] + b[1] / polygon.length];
},
[0, 0]
);
}
geojsonのgeometryプロパティを渡す。
const geojson = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[138.7309,35.3628],[138.8079,35.1983],[139.0248,35.2248],[138.7309,35.3628]
]
]
}
}
//中心地を求める
const center = getCentroid(geo.geometry);
// -> [138.823625, 35.287175000000005]