I am using the following code to get the vertices from a boost::geometry::polygon
:
using namespace boost::geometry;
using PointType = model::d2::point_xy<double>;
using PolygonType = model::polygon<PointType, false>; // clockwise ordering
PolygonType poly;
// set several vertices here
for(auto pos = 0; pos < num_points(poly); ++pos) {
PointType pt = poly.outer()[pos];
// do something with the point here
}
However, I can’t find an easy way to set the values of a specific point in the polygon. The following doesn’t work:
PointType new_pt{3, 3};
poly.outer()[pos] = new_pt;
What am I doing wrong?
See my comment below – this DOES work
2
We can’t really know what type of problem you run into. So let me illustrate how I’d do this – and that works:
Live On Coliru
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
namespace bg = boost::geometry;
using PointType = bg::model::d2::point_xy<double>;
using PolygonType = bg::model::polygon<PointType, false>; // clockwise ordering
int main ()
{
PolygonType poly;
bg::read_wkt("POLYGON((0 0 0 1 1 1 1 0 0 0))", poly);
auto num_points = poly.outer().size();
PointType const shift(100,100);
for (auto pos = 0ul; pos < num_points; ++pos)
{
PointType pt = poly.outer ()[pos];
// do something with the point here
bg::add_point(pt, shift);
poly.outer ()[pos] = pt;
}
std::cout << "first: " << bg::wkt(poly) << "n";
That prints the shifted rectangle. But it could be simpler:
// simpler
for (auto pos = 0ul; pos < num_points; ++pos)
bg::add_point(poly.outer ()[pos], shift);
std::cout << "second: " << bg::wkt(poly) << "n";
Or indeed much simpler
// even simpler
for (auto& pt: poly.outer())
bg::add_point(pt, shift);
std::cout << "third: " << bg::wkt(poly) << "n";
Last but not least, there’s a more idiomatic way to operate on any BG geometry. This has the advantage that it will actually correctly work on inner rings of your polygon if they are present:
bg::for_each_point(poly, [shift](auto& pt) {
bg::add_point(pt, shift);
});
std::cout << "fourth: " << bg::wkt(poly) << "n";
}
The output on Coliru:
first: POLYGON((100 100,100 101,101 101,101 100,100 100))
second: POLYGON((200 200,200 201,201 201,201 200,200 200))
third: POLYGON((300 300,300 301,301 301,301 300,300 300))
fourth: POLYGON((400 400,400 401,401 401,401 400,400 400))
2