[GIS] How to create a polygon with a circular hole in openlayers 3

donut-polygonsopenlayerspolygon

To highlight an area on my map I need to make a circular hole in a polygon. The rectangle polygon covers the whole map, the circle hole should act as a spot on my area to highlight.

But actually I only manage to make a rectangle hole, for example using Polygon's appendLinearRing function:

mypolygon.appendLinearRing(new ol.geom.LinearRing([
    [239850, 5069850],
    [239850, 5070150],
    [240150, 5070150],
    [240150, 5069850],
    [239850, 5069850]
]));

The problem is that I can't find out how to add "Circle" as optional geometry (opt_layout) to ol.geom.LinearRing. Any hints?

Best Answer

I guess you create a Circle using the ol.geom.Circle(center, opt_radius, opt_layout) contructor api doc here. And then you want to update the polygon geometry with this circle. Right???

If so you can create the coordinates of your circle and pass these coords to appendLinearRing function.

You may do that as: (I havent test. Minor bugs may exist)

var circleCenterX = 200; //the X center of your circle
var circleCenterY = 100; //the Y center of your circle
var circleRadius = 100;  //the radius of your circle
var pointsToFind = 360;  //point to generate in order to create the circle. 
//I use 360 wich is fine in terms of detail as this will make one point for each rad
//but if you need more occuracy you may suply a higher number. If less a lower number
var circleCoords = createCirclePointCoords(circleCenterX,circleCenterY,circleRadius,pointsToFind);
console.log("circleCoords.length",circleCoords.length);

function createCirclePointCoords(circleCenterX,circleCenterY,circleRadius,pointsToFind){
  var angleToAdd = 360/pointsToFind;
  var coords = [];  
  var angle = 0;
    for (var i=0;i<pointsToFind;i++){
    angle = angle+angleToAdd;
        console.log(angle);
    var coordX = circleCenterX + circleRadius * Math.cos(angle*Math.PI/180);
    var coordY = circleCenterY + circleRadius * Math.sin(angle*Math.PI/180);
        coords.push([coordX,coordY]);
    }

return coords;
}
//check if last coordinate equals first coordinate. 
//If not add one more pair of coorinates to meet this critirion  
//and then pass these coordinates to your function  
mypolygon.appendLinearRing(new ol.geom.LinearRing([
circleCoords
]));