OpenLayers – Drawing Polygon Over a Point in OpenLayers

geojsonopenlayerspointpolygon

I read a geojson with points and their coordinates, but on the map, I want to draw polygons, not points.

this is an example of the polygon that I want:

enter image description here
Yes, it is a boat.

How can I do it?

Best Answer

The cleanest way will be to go through all the points and create the polygon geometry by yourself. Polygon is in openLayers represented as aray of arrays of coordinates for example [[[0,0],[0,1],[1,1],[1,0],[0,0]]] where the last coordinate is allways the same as the first. So you can do something like this:

var pointsFeatures = geojson.features;//correct definition of your data
var pointsArray = [];
for(var i = 0;i<pointsFeatures.length;i++){
  pointsArray.push(pointsFeatures[i].geometry.coordinates);
}
pointsArray.push(pointsFeatures[0].geometry.coordinates);
var feat = new ol.Feature({
    geometry: new ol.geom.Polygon(pointsArray)
})
yourVectorLayer.getSource().addFeature(feat);

This will work in case you have no holes in that polygon.