02_linestring_example.cpp

The linestring example shows how linestrings can be declared and used and shows some more algorithms. One of the important concepts of the Generic Geometry Library is that it is totally built upon the standard library, using the standard containers such as std::vector.

A linestring is, as explained elsewhere in this documentation, not much more than a vector of points. Most algorithms run on linestrings, but can also run on any iterator pair. And all algorithms on std::vector can be used on geometry::linestring.

The sample shows this, shows some algorithms:

- geometry::envelope

- geometry::length

- geometry::distance

- geometry::simplify

- geometry::for_each

- geometry::intersection

This documentation illustrates the simplify algorithm and the intersection algorithm with some pictures.

The simplify algorithm simplifies a linestring. Simplification means that the less important points are removed from the line and that the points that are most important for the shape of a line are kept. Simplification is done using the well known Douglas Peucker algorithm. The library user can specify the distance or tolerance, which indicates how much the linestring should be simplified.

The image below shows the original and simplified linestring: The blue line is the original linestring; the red line is the simplified line which has one point less. In geographical applications simplification can reduce a linestring to its basic form containing only 10% of its original points.

The intersection algorithm intersects two geometries which each other, delivering a third geometry. In the case of the example a linestring is intersected with a box. Intersection with a box is often called a clip. The image below illustrates the intersection. The yellow line is intersected with the blue box. The intersection result, painted in red, contains three linestrings.

    //Boost.Geometry(akaGGL,GenericGeometryLibrary)

    //Copyright(c)2007-2012BarendGehrels,Amsterdam,theNetherlands.
    //Copyright(c)2008-2012BrunoLalande,Paris,France.
    //Copyright(c)2009-2012MateuszLoskot,London,UK.

    //Use,modificationanddistributionissubjecttotheBoostSoftwareLicense,
    //Version1.0.(SeeaccompanyingfileLICENSE_1_0.txtorcopyat
    //http://www.boost.org/LICENSE_1_0.txt)
    //
    //LinestringExample

    #include<algorithm>//forreverse,unique
    #include<iostream>
    #include<iterator>
    #include<utility>
    #include<vector>

    #include<boost/geometry/geometry.hpp>
    #include<boost/geometry/geometries/linestring.hpp>
    #include<boost/geometry/geometries/point_xy.hpp>
    #include<boost/geometry/geometries/polygon.hpp>

    //Optionalincludesanddefinestohandlec-arraysaspoints,std::vectorsaslinestrings
    #include<boost/geometry/geometries/register/linestring.hpp>
    #include<boost/geometry/geometries/adapted/c_array.hpp>

    BOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian)

    BOOST_GEOMETRY_REGISTER_LINESTRING_TEMPLATED(std::vector)
    BOOST_GEOMETRY_REGISTER_LINESTRING_TEMPLATED(std::deque)

    template<typenameP>
    inlinevoidtranslate_function(P&p)
    {
    p.x(p.x()+100.0);
    }

    template<typenameP>
    structscale_functor
    {
    inlinevoidoperator()(P&p)
    {
    p.x(p.x()*1000.0);
    p.y(p.y()*1000.0);
    }
    };

    template<typenamePoint>
    structround_coordinates
    {
    typedeftypenameboost::geometry::coordinate_type<Point>::typecoordinate_type;
    coordinate_typem_factor;

    inlineround_coordinates(coordinate_typeconst&factor)
    :m_factor(factor)
    {}

    template<intDimension>
    inlinevoidround(Point&p)
    {
    coordinate_typec=boost::geometry::get<Dimension>(p)/m_factor;
    introunded=c;
    boost::geometry::set<Dimension>(p,coordinate_type(rounded)*m_factor);
    }

    inlinevoidoperator()(Point&p)
    {
    round<0>(p);
    round<1>(p);
    }
    };

    intmain(void)
    {
    usingnamespaceboost::geometry;

    //Definealinestring,whichisavectorofpoints,andaddsomepoints
    //(weaddthemdeliberatelyindifferentways)
    typedefmodel::d2::point_xy<double>point_2d;
    typedefmodel::linestring<point_2d>linestring_2d;
    linestring_2dls;

    //pointscanbecreatedusing"make"andaddedtoalinestringusingthestd::"push_back"
    ls.push_back(make<point_2d>(1.1,1.1));

    //pointscanalsobeassignedusing"assign_values"andaddedtoalinestringusing"append"
    point_2dlp;
    assign_values(lp,2.5,2.1);
    append(ls,lp);

    //LinescanbestreamedusingDSV(delimiterseparatedvalues)
    std::cout<<dsv(ls)<<std::endl;

    //Theboundingboxoflinestringscanbecalculated
    typedefmodel::box<point_2d>box_2d;
    box_2db;
    envelope(ls,b);
    std::cout<<dsv(b)<<std::endl;

    //Thelengthofthelinecanbecalulated
    std::cout<<"length:"<<length(ls)<<std::endl;

    //Allthingsfromstd::vectorcanbecalled,becausealinestringisavector
    std::cout<<"numberofpoints1:"<<ls.size()<<std::endl;

    //Allthingsfromboostrangescanbecalledbecausealinestringisconsideredasarange
    std::cout<<"numberofpoints2:"<<boost::size(ls)<<std::endl;

    //Genericfunctionfromgeometry/OGCdeliversthesamevalue
    std::cout<<"numberofpoints3:"<<num_points(ls)<<std::endl;

    //Thedistancefromapointtoalinestringcanbecalculated
    point_2dp(1.9,1.2);
    std::cout<<"distanceof"<<dsv(p)
    <<"toline:"<<distance(p,ls)<<std::endl;

    //Alinestringisavector.However,somealgorithmsconsider"segments",
    //whicharethelinepiecesbetweentwopointsofalinestring.
    doubled=distance(p,model::segment<point_2d >(ls.front(),ls.back()));
    std::cout<<"distance:"<<d<<std::endl;

    //Addsomethreepointsmore,let'sdoitusingaclassicarray.
    //(Seedocumentationforpictureofthislinestring)
    constdoublec[][2]={{3.1,3.1},{4.9,1.1},{3.1,1.9}};
    append(ls,c);
    std::cout<<"appended:"<<dsv(ls)<<std::endl;

    //Outputasiterator-paironavector
    {
    std::vector<point_2d>v;
    std::copy(ls.begin(),ls.end(),std::back_inserter(v));

    std::cout
    <<"asvector:"
    <<dsv(v)
    <<std::endl;
    }

    //Allalgorithmsfromstdcanbeused:alinestringisavector
    std::reverse(ls.begin(),ls.end());
    std::cout<<"reversed:"<<dsv(ls)<<std::endl;
    std::reverse(boost::begin(ls),boost::end(ls));

    //Theotherway,usingavectorinsteadofalinestring,isalsopossible
    std::vector<point_2d>pv(ls.begin(),ls.end());
    std::cout<<"length:"<<length(pv)<<std::endl;

    //Iftherearedoublepointsintheline,youcanuseuniquetoremovethem
    //Soweaddthelastpoint,print,makeauniquecopyandprint
    {
    //(sidenote,wehavetomakecopies,because
    //ls.push_back(ls.back())oftensucceedsbut
    //ISdangerousanderroneous!
    point_2dlast=ls.back(),first=ls.front();
    ls.push_back(last);
    ls.insert(ls.begin(),first);
    }
    std::cout<<"extraduplicatepoints:"<<dsv(ls)<<std::endl;

    {
    linestring_2dls_copy;
    std::unique_copy(ls.begin(),ls.end(),std::back_inserter(ls_copy),
    boost::geometry::equal_to<point_2d>());
    ls=ls_copy;
    std::cout<<"uniquecopy:"<<dsv(ls)<<std::endl;
    }

    //Linescanbesimplified.Thisremovespoints,butpreservestheshape
    linestring_2dls_simplified;
    simplify(ls,ls_simplified,0.5);
    std::cout<<"simplified:"<<dsv(ls_simplified)<<std::endl;

    //for_each:
    //1)Linescanbevisitedwithstd::for_each
    //2)for_each_pointisalsodefinedforallgeometries
    //3)for_each_segmentisdefinedforallgeometriestoallsegments
    //4)loopisdefinedforgeometriestovisitsegments
    //withstateapart,andtobeabletobreakout(notshownhere)
    {
    linestring_2dlscopy=ls;
    std::for_each(lscopy.begin(),lscopy.end(),translate_function<point_2d>);
    for_each_point(lscopy,scale_functor<point_2d>());
    for_each_point(lscopy,translate_function<point_2d>);
    std::cout<<"modifiedline:"<<dsv(lscopy)<<std::endl;
    }

    //Linescanbeclippedusingaclippingbox.Clippedlinesareaddedtotheoutputiterator
    box_2dcb(point_2d(1.5,1.5),point_2d(4.5,2.5));

    std::vector<linestring_2d>clipped;
    intersection(cb,ls,clipped);

    //Alsopossible:clip-outputtoavectorofvectors
    std::vector<std::vector<point_2d>>vector_out;
    intersection(cb,ls,vector_out);

    std::cout<<"clippedoutputasvector:"<<std::endl;
    for(std::vector<std::vector<point_2d>>::const_iteratorit
    =vector_out.begin();it!=vector_out.end();++it)
    {
    std::cout<<dsv(*it)<<std::endl;
    }

    //Calculatetheconvexhullofthelinestring
    model::polygon<point_2d>hull;
    convex_hull(ls,hull);
    std::cout<<"Convexhull:"<<dsv(hull)<<std::endl;

    //Alltheaboveassumed2DCartesianlinestrings.3Dispossibleaswell
    //Let'sdefinea3Dpointourselves,thistimeusing'float'
    typedefmodel::point<float, 3, cs::cartesian>point_3d;
    model::linestring<point_3d>line3;
    line3.push_back(make<point_3d>(1,2,3));
    line3.push_back(make<point_3d>(4,5,6));
    line3.push_back(make<point_3d>(7,8,9));

    //Notallalgorithmsworkon3dlines.ForexampleconvexhulldoesNOT.
    //But,forexample,length,distance,simplify,envelopeandstreamdo.
    std::cout<<"3D:length:"<<length(line3)<<"line:"<<dsv(line3)<<std::endl;

    //WithDSVyoucanalsouseotherdelimiters,e.g.JSONstyle
    std::cout<<"JSON:"
    <<dsv(ls,",","[","]",",","[","]")
    <<std::endl;

    return0;
    }