# Openlayers 3: Draw Polygon (convex hull) around a cluster of points

I'm grouping a set of points as a cluster. Then I'm trying to draw a polygon around the points.

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});
}

var thing = new ol.geom.Polygon( [polyCoords]);
var featurething = new ol.Feature({
name: "Thing",
geometry: thing
});
min=max+1;
max=max*2;
}
``````

How can I draw a polygon around all the points?

• So you want to draw a convex hull around your points, right ? – Hicham Zouarhi Sep 8 '16 at 12:17

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:

``````//Create a new instance of ConvexHullGrahamScan.
var convexHull = new ConvexHullGrahamScan();

//add points using for loop on your coordinates
for (var i = 0; i < polyCoords.length ; i++) {
}

// get point array from convex hull
var hullPoints = convexHull.getHull();

// create ol.geom.Polygon from hullPoints...
``````

Another way to do it is with Turf.js, using `turf.convex` which takes a featureCollection of points and returns a feature polygon. all this is done in Geojson format

``````var yourPolygon= turf.convex(yourPoints);
``````

Here is a little description of it