I'm grouping a set of points as a cluster. Then I'm trying to draw a polygon around the points.
Please see this link: Draw Poly
I tried by sorting the points based on co-ordinates. But still I'm not able to draw the polygon correctly.
var vectorSource = new ol.source.Vector({});
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
new ol.layer.Vector({
source: vectorSource
})
],
target: 'map',
view: new ol.View({
center: [-16, 75],
zoom:2
})
});
//clusters
var min=1;
var max=20
for (j = 1; j < 3; j++) {
var polyCoords = [];
for (i = 0; i < 10; i++) {
var x = Math.random() * (max - min) + min;
var y = Math.random() * (max*2 - min*2) + min;
polyCoords.push( ol.proj.transform([-x,y],'EPSG:4326', 'EPSG:3857'));
var point = new ol.geom.Point([-x, y]).transform('EPSG:4326', 'EPSG:3857');
var fea = new ol.Feature({geometry:point});
vectorSource.addFeature(fea);
}
var thing = new ol.geom.Polygon( [polyCoords]);
var featurething = new ol.Feature({
name: "Thing",
geometry: thing
});
vectorSource.addFeature( featurething );
min=max+1;
max=max*2;
}
How can I draw a polygon around all the points?
Best Answer
As Hicham Zouarhi pointed out you want to create the convex hull from your
polyCoords
. You can find an implementation of the Graham Scan Convex Hull algorithm for JavaScript on github (MIT License). As describes the usage is simple: