0

This question is an exact duplicate of:

I am trying to develop a web portal using ol5 API where user click on map and then it takes map click event coordinates as centroid of rectangle and create a rectangle of particular height and width.

Here is the to create square

image: new ol.style.RegularShape({
        fill: fill,
        points: 4,
        radius: 30,
        angle: Math.PI / 4
    })

But I want to create rectangle with center point , height and width. How to achieve this?

marked as duplicate by LaughU, Fran Raga, Hornbydd, Vince, whyzar May 23 at 16:00

This question was marked as an exact duplicate of an existing question.

2

RegularShape only works for regular polygons. One way to display a point feature as a rectangle with different width and height would be to use a geometry function to produce a polygon from the point coordinates, for example

new ol.style.Style({
  geometry: function(feature) {
     var coordinate = feature.getGeometry().getCoordinates();
     return ol.geom.Polygon.fromExtent([coordinate[0]-width/2, coordinate[1]-height/2, coordinate[0]+width/2, coordinate[1]+height/2])
  }
  fill: fill
  stroke: stroke
})

or a style function

function(feature, resolution) {
  var coordinate = feature.getGeometry().getCoordinates();
  return new ol.style.Style({
    geometry: ol.geom.Polygon.fromExtent([
      coordinate[0] - width*resolution/2,
      coordinate[1] - height*resolution/2,
      coordinate[0] + width*resolution/2,
      coordinate[1] + height*resolution/2
    ]),
    fill: fill
    stroke: stroke
  })
}
  • i did not understand how to use this code? – sanju verma May 23 at 10:45
  • ok thanks. got it. – sanju verma May 23 at 10:57
  • is height and width is in meter for this one "coordinate[0]-width/2"? – sanju verma May 23 at 10:58
  • In that case width and height would be map units, so it would scale with the view. To set a size in pixels you would need to multiple by resolution, which would need a style function. – Mike May 23 at 11:10
  • ok Mike sir. thanks. – sanju verma May 23 at 11:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.