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:
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.
This is happening only when you click on last vertex of your polygon to close the polygon. If you double click to close it no such error occurs.
The problem comes because you have select and draw interactions active at the same time. So single click for closing the polygon fires the unselect action of select interaction.
To overcome the issue do as follows
create a drawstart event and disable the select interaction
within the drawend event you allready have, re-enable the select interaction with delay 300 ms. (251ms is the time ol needs to distinguish single click from double click)
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:This will work in case you have no holes in that polygon.